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 bool Smaller = PartVT.bitsLE(ValueVT);
479 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
482 // Vector -> scalar conversion.
483 assert(ValueVT.getVectorNumElements() == 1 &&
484 "Only trivial vector-to-scalar conversions should get here!");
485 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
486 PartVT, Val, DAG.getIntPtrConstant(0));
488 bool Smaller = ValueVT.bitsLE(PartVT);
489 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
497 // Handle a multi-element vector.
498 EVT IntermediateVT, RegisterVT;
499 unsigned NumIntermediates;
500 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
502 NumIntermediates, RegisterVT);
503 unsigned NumElements = ValueVT.getVectorNumElements();
505 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
506 NumParts = NumRegs; // Silence a compiler warning.
507 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
509 // Split the vector into intermediate operands.
510 SmallVector<SDValue, 8> Ops(NumIntermediates);
511 for (unsigned i = 0; i != NumIntermediates; ++i) {
512 if (IntermediateVT.isVector())
513 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
515 DAG.getIntPtrConstant(i * (NumElements / NumIntermediates)));
517 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
518 IntermediateVT, Val, DAG.getIntPtrConstant(i));
521 // Split the intermediate operands into legal parts.
522 if (NumParts == NumIntermediates) {
523 // If the register was not expanded, promote or copy the value,
525 for (unsigned i = 0; i != NumParts; ++i)
526 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT);
527 } else if (NumParts > 0) {
528 // If the intermediate type was expanded, split each the value into
530 assert(NumParts % NumIntermediates == 0 &&
531 "Must expand into a divisible number of parts!");
532 unsigned Factor = NumParts / NumIntermediates;
533 for (unsigned i = 0; i != NumIntermediates; ++i)
534 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT);
542 /// RegsForValue - This struct represents the registers (physical or virtual)
543 /// that a particular set of values is assigned, and the type information
544 /// about the value. The most common situation is to represent one value at a
545 /// time, but struct or array values are handled element-wise as multiple
546 /// values. The splitting of aggregates is performed recursively, so that we
547 /// never have aggregate-typed registers. The values at this point do not
548 /// necessarily have legal types, so each value may require one or more
549 /// registers of some legal type.
551 struct RegsForValue {
552 /// ValueVTs - The value types of the values, which may not be legal, and
553 /// may need be promoted or synthesized from one or more registers.
555 SmallVector<EVT, 4> ValueVTs;
557 /// RegVTs - The value types of the registers. This is the same size as
558 /// ValueVTs and it records, for each value, what the type of the assigned
559 /// register or registers are. (Individual values are never synthesized
560 /// from more than one type of register.)
562 /// With virtual registers, the contents of RegVTs is redundant with TLI's
563 /// getRegisterType member function, however when with physical registers
564 /// it is necessary to have a separate record of the types.
566 SmallVector<EVT, 4> RegVTs;
568 /// Regs - This list holds the registers assigned to the values.
569 /// Each legal or promoted value requires one register, and each
570 /// expanded value requires multiple registers.
572 SmallVector<unsigned, 4> Regs;
576 RegsForValue(const SmallVector<unsigned, 4> ®s,
577 EVT regvt, EVT valuevt)
578 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
580 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
581 unsigned Reg, Type *Ty) {
582 ComputeValueVTs(tli, Ty, ValueVTs);
584 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
585 EVT ValueVT = ValueVTs[Value];
586 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
587 EVT RegisterVT = tli.getRegisterType(Context, ValueVT);
588 for (unsigned i = 0; i != NumRegs; ++i)
589 Regs.push_back(Reg + i);
590 RegVTs.push_back(RegisterVT);
595 /// areValueTypesLegal - Return true if types of all the values are legal.
596 bool areValueTypesLegal(const TargetLowering &TLI) {
597 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
598 EVT RegisterVT = RegVTs[Value];
599 if (!TLI.isTypeLegal(RegisterVT))
605 /// append - Add the specified values to this one.
606 void append(const RegsForValue &RHS) {
607 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
608 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
609 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
612 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
613 /// this value and returns the result as a ValueVTs value. This uses
614 /// Chain/Flag as the input and updates them for the output Chain/Flag.
615 /// If the Flag pointer is NULL, no flag is used.
616 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
618 SDValue &Chain, SDValue *Flag) const;
620 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
621 /// specified value into the registers specified by this object. 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 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
625 SDValue &Chain, SDValue *Flag) const;
627 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
628 /// operand list. This adds the code marker, matching input operand index
629 /// (if applicable), and includes the number of values added into it.
630 void AddInlineAsmOperands(unsigned Kind,
631 bool HasMatching, unsigned MatchingIdx,
633 std::vector<SDValue> &Ops) const;
637 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
638 /// this value and returns the result as a ValueVT value. This uses
639 /// Chain/Flag as the input and updates them for the output Chain/Flag.
640 /// If the Flag pointer is NULL, no flag is used.
641 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
642 FunctionLoweringInfo &FuncInfo,
644 SDValue &Chain, SDValue *Flag) const {
645 // A Value with type {} or [0 x %t] needs no registers.
646 if (ValueVTs.empty())
649 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
651 // Assemble the legal parts into the final values.
652 SmallVector<SDValue, 4> Values(ValueVTs.size());
653 SmallVector<SDValue, 8> Parts;
654 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
655 // Copy the legal parts from the registers.
656 EVT ValueVT = ValueVTs[Value];
657 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
658 EVT RegisterVT = RegVTs[Value];
660 Parts.resize(NumRegs);
661 for (unsigned i = 0; i != NumRegs; ++i) {
664 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
666 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
667 *Flag = P.getValue(2);
670 Chain = P.getValue(1);
673 // If the source register was virtual and if we know something about it,
674 // add an assert node.
675 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
676 !RegisterVT.isInteger() || RegisterVT.isVector())
679 const FunctionLoweringInfo::LiveOutInfo *LOI =
680 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
684 unsigned RegSize = RegisterVT.getSizeInBits();
685 unsigned NumSignBits = LOI->NumSignBits;
686 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
688 // FIXME: We capture more information than the dag can represent. For
689 // now, just use the tightest assertzext/assertsext possible.
691 EVT FromVT(MVT::Other);
692 if (NumSignBits == RegSize)
693 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
694 else if (NumZeroBits >= RegSize-1)
695 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
696 else if (NumSignBits > RegSize-8)
697 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
698 else if (NumZeroBits >= RegSize-8)
699 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
700 else if (NumSignBits > RegSize-16)
701 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
702 else if (NumZeroBits >= RegSize-16)
703 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
704 else if (NumSignBits > RegSize-32)
705 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
706 else if (NumZeroBits >= RegSize-32)
707 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
711 // Add an assertion node.
712 assert(FromVT != MVT::Other);
713 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
714 RegisterVT, P, DAG.getValueType(FromVT));
717 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
718 NumRegs, RegisterVT, ValueVT);
723 return DAG.getNode(ISD::MERGE_VALUES, dl,
724 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
725 &Values[0], ValueVTs.size());
728 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
729 /// specified value into the registers specified by this object. This uses
730 /// Chain/Flag as the input and updates them for the output Chain/Flag.
731 /// If the Flag pointer is NULL, no flag is used.
732 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
733 SDValue &Chain, SDValue *Flag) const {
734 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
736 // Get the list of the values's legal parts.
737 unsigned NumRegs = Regs.size();
738 SmallVector<SDValue, 8> Parts(NumRegs);
739 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
740 EVT ValueVT = ValueVTs[Value];
741 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
742 EVT RegisterVT = RegVTs[Value];
744 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
745 &Parts[Part], NumParts, RegisterVT);
749 // Copy the parts into the registers.
750 SmallVector<SDValue, 8> Chains(NumRegs);
751 for (unsigned i = 0; i != NumRegs; ++i) {
754 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
756 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
757 *Flag = Part.getValue(1);
760 Chains[i] = Part.getValue(0);
763 if (NumRegs == 1 || Flag)
764 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
765 // flagged to it. That is the CopyToReg nodes and the user are considered
766 // a single scheduling unit. If we create a TokenFactor and return it as
767 // chain, then the TokenFactor is both a predecessor (operand) of the
768 // user as well as a successor (the TF operands are flagged to the user).
769 // c1, f1 = CopyToReg
770 // c2, f2 = CopyToReg
771 // c3 = TokenFactor c1, c2
774 Chain = Chains[NumRegs-1];
776 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
779 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
780 /// operand list. This adds the code marker and includes the number of
781 /// values added into it.
782 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
783 unsigned MatchingIdx,
785 std::vector<SDValue> &Ops) const {
786 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
788 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
790 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
791 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
794 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
795 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
796 EVT RegisterVT = RegVTs[Value];
797 for (unsigned i = 0; i != NumRegs; ++i) {
798 assert(Reg < Regs.size() && "Mismatch in # registers expected");
799 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
804 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
807 TD = DAG.getTarget().getTargetData();
810 /// clear - Clear out the current SelectionDAG and the associated
811 /// state and prepare this SelectionDAGBuilder object to be used
812 /// for a new block. This doesn't clear out information about
813 /// additional blocks that are needed to complete switch lowering
814 /// or PHI node updating; that information is cleared out as it is
816 void SelectionDAGBuilder::clear() {
818 UnusedArgNodeMap.clear();
819 PendingLoads.clear();
820 PendingExports.clear();
821 CurDebugLoc = DebugLoc();
825 /// clearDanglingDebugInfo - Clear the dangling debug information
826 /// map. This function is seperated from the clear so that debug
827 /// information that is dangling in a basic block can be properly
828 /// resolved in a different basic block. This allows the
829 /// SelectionDAG to resolve dangling debug information attached
831 void SelectionDAGBuilder::clearDanglingDebugInfo() {
832 DanglingDebugInfoMap.clear();
835 /// getRoot - Return the current virtual root of the Selection DAG,
836 /// flushing any PendingLoad items. This must be done before emitting
837 /// a store or any other node that may need to be ordered after any
838 /// prior load instructions.
840 SDValue SelectionDAGBuilder::getRoot() {
841 if (PendingLoads.empty())
842 return DAG.getRoot();
844 if (PendingLoads.size() == 1) {
845 SDValue Root = PendingLoads[0];
847 PendingLoads.clear();
851 // Otherwise, we have to make a token factor node.
852 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
853 &PendingLoads[0], PendingLoads.size());
854 PendingLoads.clear();
859 /// getControlRoot - Similar to getRoot, but instead of flushing all the
860 /// PendingLoad items, flush all the PendingExports items. It is necessary
861 /// to do this before emitting a terminator instruction.
863 SDValue SelectionDAGBuilder::getControlRoot() {
864 SDValue Root = DAG.getRoot();
866 if (PendingExports.empty())
869 // Turn all of the CopyToReg chains into one factored node.
870 if (Root.getOpcode() != ISD::EntryToken) {
871 unsigned i = 0, e = PendingExports.size();
872 for (; i != e; ++i) {
873 assert(PendingExports[i].getNode()->getNumOperands() > 1);
874 if (PendingExports[i].getNode()->getOperand(0) == Root)
875 break; // Don't add the root if we already indirectly depend on it.
879 PendingExports.push_back(Root);
882 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
884 PendingExports.size());
885 PendingExports.clear();
890 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
891 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
892 DAG.AssignOrdering(Node, SDNodeOrder);
894 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
895 AssignOrderingToNode(Node->getOperand(I).getNode());
898 void SelectionDAGBuilder::visit(const Instruction &I) {
899 // Set up outgoing PHI node register values before emitting the terminator.
900 if (isa<TerminatorInst>(&I))
901 HandlePHINodesInSuccessorBlocks(I.getParent());
903 CurDebugLoc = I.getDebugLoc();
905 visit(I.getOpcode(), I);
907 if (!isa<TerminatorInst>(&I) && !HasTailCall)
908 CopyToExportRegsIfNeeded(&I);
910 CurDebugLoc = DebugLoc();
913 void SelectionDAGBuilder::visitPHI(const PHINode &) {
914 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
917 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &) {
918 // FIXME: Handle this
921 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
922 // Note: this doesn't use InstVisitor, because it has to work with
923 // ConstantExpr's in addition to instructions.
925 default: llvm_unreachable("Unknown instruction type encountered!");
926 // Build the switch statement using the Instruction.def file.
927 #define HANDLE_INST(NUM, OPCODE, CLASS) \
928 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
929 #include "llvm/Instruction.def"
932 // Assign the ordering to the freshly created DAG nodes.
933 if (NodeMap.count(&I)) {
935 AssignOrderingToNode(getValue(&I).getNode());
939 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
940 // generate the debug data structures now that we've seen its definition.
941 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
943 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
945 const DbgValueInst *DI = DDI.getDI();
946 DebugLoc dl = DDI.getdl();
947 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
948 MDNode *Variable = DI->getVariable();
949 uint64_t Offset = DI->getOffset();
952 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
953 SDV = DAG.getDbgValue(Variable, Val.getNode(),
954 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
955 DAG.AddDbgValue(SDV, Val.getNode(), false);
958 DEBUG(dbgs() << "Dropping debug info for " << DI);
959 DanglingDebugInfoMap[V] = DanglingDebugInfo();
963 // getValue - Return an SDValue for the given Value.
964 SDValue SelectionDAGBuilder::getValue(const Value *V) {
965 // If we already have an SDValue for this value, use it. It's important
966 // to do this first, so that we don't create a CopyFromReg if we already
967 // have a regular SDValue.
968 SDValue &N = NodeMap[V];
969 if (N.getNode()) return N;
971 // If there's a virtual register allocated and initialized for this
973 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
974 if (It != FuncInfo.ValueMap.end()) {
975 unsigned InReg = It->second;
976 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
977 SDValue Chain = DAG.getEntryNode();
978 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain,NULL);
979 resolveDanglingDebugInfo(V, N);
983 // Otherwise create a new SDValue and remember it.
984 SDValue Val = getValueImpl(V);
986 resolveDanglingDebugInfo(V, Val);
990 /// getNonRegisterValue - Return an SDValue for the given Value, but
991 /// don't look in FuncInfo.ValueMap for a virtual register.
992 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
993 // If we already have an SDValue for this value, use it.
994 SDValue &N = NodeMap[V];
995 if (N.getNode()) return N;
997 // Otherwise create a new SDValue and remember it.
998 SDValue Val = getValueImpl(V);
1000 resolveDanglingDebugInfo(V, Val);
1004 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1005 /// Create an SDValue for the given value.
1006 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1007 if (const Constant *C = dyn_cast<Constant>(V)) {
1008 EVT VT = TLI.getValueType(V->getType(), true);
1010 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1011 return DAG.getConstant(*CI, VT);
1013 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1014 return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT);
1016 if (isa<ConstantPointerNull>(C))
1017 return DAG.getConstant(0, TLI.getPointerTy());
1019 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1020 return DAG.getConstantFP(*CFP, VT);
1022 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1023 return DAG.getUNDEF(VT);
1025 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1026 visit(CE->getOpcode(), *CE);
1027 SDValue N1 = NodeMap[V];
1028 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1032 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1033 SmallVector<SDValue, 4> Constants;
1034 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1036 SDNode *Val = getValue(*OI).getNode();
1037 // If the operand is an empty aggregate, there are no values.
1039 // Add each leaf value from the operand to the Constants list
1040 // to form a flattened list of all the values.
1041 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1042 Constants.push_back(SDValue(Val, i));
1045 return DAG.getMergeValues(&Constants[0], Constants.size(),
1049 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1050 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1051 "Unknown struct or array constant!");
1053 SmallVector<EVT, 4> ValueVTs;
1054 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1055 unsigned NumElts = ValueVTs.size();
1057 return SDValue(); // empty struct
1058 SmallVector<SDValue, 4> Constants(NumElts);
1059 for (unsigned i = 0; i != NumElts; ++i) {
1060 EVT EltVT = ValueVTs[i];
1061 if (isa<UndefValue>(C))
1062 Constants[i] = DAG.getUNDEF(EltVT);
1063 else if (EltVT.isFloatingPoint())
1064 Constants[i] = DAG.getConstantFP(0, EltVT);
1066 Constants[i] = DAG.getConstant(0, EltVT);
1069 return DAG.getMergeValues(&Constants[0], NumElts,
1073 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1074 return DAG.getBlockAddress(BA, VT);
1076 VectorType *VecTy = cast<VectorType>(V->getType());
1077 unsigned NumElements = VecTy->getNumElements();
1079 // Now that we know the number and type of the elements, get that number of
1080 // elements into the Ops array based on what kind of constant it is.
1081 SmallVector<SDValue, 16> Ops;
1082 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1083 for (unsigned i = 0; i != NumElements; ++i)
1084 Ops.push_back(getValue(CP->getOperand(i)));
1086 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1087 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1090 if (EltVT.isFloatingPoint())
1091 Op = DAG.getConstantFP(0, EltVT);
1093 Op = DAG.getConstant(0, EltVT);
1094 Ops.assign(NumElements, Op);
1097 // Create a BUILD_VECTOR node.
1098 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
1099 VT, &Ops[0], Ops.size());
1102 // If this is a static alloca, generate it as the frameindex instead of
1104 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1105 DenseMap<const AllocaInst*, int>::iterator SI =
1106 FuncInfo.StaticAllocaMap.find(AI);
1107 if (SI != FuncInfo.StaticAllocaMap.end())
1108 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1111 // If this is an instruction which fast-isel has deferred, select it now.
1112 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1113 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1114 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1115 SDValue Chain = DAG.getEntryNode();
1116 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
1119 llvm_unreachable("Can't get register for value!");
1123 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1124 SDValue Chain = getControlRoot();
1125 SmallVector<ISD::OutputArg, 8> Outs;
1126 SmallVector<SDValue, 8> OutVals;
1128 if (!FuncInfo.CanLowerReturn) {
1129 unsigned DemoteReg = FuncInfo.DemoteRegister;
1130 const Function *F = I.getParent()->getParent();
1132 // Emit a store of the return value through the virtual register.
1133 // Leave Outs empty so that LowerReturn won't try to load return
1134 // registers the usual way.
1135 SmallVector<EVT, 1> PtrValueVTs;
1136 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1139 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1140 SDValue RetOp = getValue(I.getOperand(0));
1142 SmallVector<EVT, 4> ValueVTs;
1143 SmallVector<uint64_t, 4> Offsets;
1144 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1145 unsigned NumValues = ValueVTs.size();
1147 SmallVector<SDValue, 4> Chains(NumValues);
1148 for (unsigned i = 0; i != NumValues; ++i) {
1149 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(),
1150 RetPtr.getValueType(), RetPtr,
1151 DAG.getIntPtrConstant(Offsets[i]));
1153 DAG.getStore(Chain, getCurDebugLoc(),
1154 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1155 // FIXME: better loc info would be nice.
1156 Add, MachinePointerInfo(), false, false, 0);
1159 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1160 MVT::Other, &Chains[0], NumValues);
1161 } else if (I.getNumOperands() != 0) {
1162 SmallVector<EVT, 4> ValueVTs;
1163 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1164 unsigned NumValues = ValueVTs.size();
1166 SDValue RetOp = getValue(I.getOperand(0));
1167 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1168 EVT VT = ValueVTs[j];
1170 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1172 const Function *F = I.getParent()->getParent();
1173 if (F->paramHasAttr(0, Attribute::SExt))
1174 ExtendKind = ISD::SIGN_EXTEND;
1175 else if (F->paramHasAttr(0, Attribute::ZExt))
1176 ExtendKind = ISD::ZERO_EXTEND;
1178 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1179 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
1181 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1182 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1183 SmallVector<SDValue, 4> Parts(NumParts);
1184 getCopyToParts(DAG, getCurDebugLoc(),
1185 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1186 &Parts[0], NumParts, PartVT, ExtendKind);
1188 // 'inreg' on function refers to return value
1189 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1190 if (F->paramHasAttr(0, Attribute::InReg))
1193 // Propagate extension type if any
1194 if (ExtendKind == ISD::SIGN_EXTEND)
1196 else if (ExtendKind == ISD::ZERO_EXTEND)
1199 for (unsigned i = 0; i < NumParts; ++i) {
1200 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1202 OutVals.push_back(Parts[i]);
1208 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1209 CallingConv::ID CallConv =
1210 DAG.getMachineFunction().getFunction()->getCallingConv();
1211 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1212 Outs, OutVals, getCurDebugLoc(), DAG);
1214 // Verify that the target's LowerReturn behaved as expected.
1215 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1216 "LowerReturn didn't return a valid chain!");
1218 // Update the DAG with the new chain value resulting from return lowering.
1222 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1223 /// created for it, emit nodes to copy the value into the virtual
1225 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1227 if (V->getType()->isEmptyTy())
1230 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1231 if (VMI != FuncInfo.ValueMap.end()) {
1232 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1233 CopyValueToVirtualRegister(V, VMI->second);
1237 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1238 /// the current basic block, add it to ValueMap now so that we'll get a
1240 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1241 // No need to export constants.
1242 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1244 // Already exported?
1245 if (FuncInfo.isExportedInst(V)) return;
1247 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1248 CopyValueToVirtualRegister(V, Reg);
1251 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1252 const BasicBlock *FromBB) {
1253 // The operands of the setcc have to be in this block. We don't know
1254 // how to export them from some other block.
1255 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1256 // Can export from current BB.
1257 if (VI->getParent() == FromBB)
1260 // Is already exported, noop.
1261 return FuncInfo.isExportedInst(V);
1264 // If this is an argument, we can export it if the BB is the entry block or
1265 // if it is already exported.
1266 if (isa<Argument>(V)) {
1267 if (FromBB == &FromBB->getParent()->getEntryBlock())
1270 // Otherwise, can only export this if it is already exported.
1271 return FuncInfo.isExportedInst(V);
1274 // Otherwise, constants can always be exported.
1278 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1279 uint32_t SelectionDAGBuilder::getEdgeWeight(MachineBasicBlock *Src,
1280 MachineBasicBlock *Dst) {
1281 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1284 BasicBlock *SrcBB = const_cast<BasicBlock*>(Src->getBasicBlock());
1285 BasicBlock *DstBB = const_cast<BasicBlock*>(Dst->getBasicBlock());
1286 return BPI->getEdgeWeight(SrcBB, DstBB);
1289 void SelectionDAGBuilder::addSuccessorWithWeight(MachineBasicBlock *Src,
1290 MachineBasicBlock *Dst) {
1291 uint32_t weight = getEdgeWeight(Src, Dst);
1292 Src->addSuccessor(Dst, weight);
1296 static bool InBlock(const Value *V, const BasicBlock *BB) {
1297 if (const Instruction *I = dyn_cast<Instruction>(V))
1298 return I->getParent() == BB;
1302 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1303 /// This function emits a branch and is used at the leaves of an OR or an
1304 /// AND operator tree.
1307 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1308 MachineBasicBlock *TBB,
1309 MachineBasicBlock *FBB,
1310 MachineBasicBlock *CurBB,
1311 MachineBasicBlock *SwitchBB) {
1312 const BasicBlock *BB = CurBB->getBasicBlock();
1314 // If the leaf of the tree is a comparison, merge the condition into
1316 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1317 // The operands of the cmp have to be in this block. We don't know
1318 // how to export them from some other block. If this is the first block
1319 // of the sequence, no exporting is needed.
1320 if (CurBB == SwitchBB ||
1321 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1322 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1323 ISD::CondCode Condition;
1324 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1325 Condition = getICmpCondCode(IC->getPredicate());
1326 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1327 Condition = getFCmpCondCode(FC->getPredicate());
1329 Condition = ISD::SETEQ; // silence warning.
1330 llvm_unreachable("Unknown compare instruction");
1333 CaseBlock CB(Condition, BOp->getOperand(0),
1334 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1335 SwitchCases.push_back(CB);
1340 // Create a CaseBlock record representing this branch.
1341 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1342 NULL, TBB, FBB, CurBB);
1343 SwitchCases.push_back(CB);
1346 /// FindMergedConditions - If Cond is an expression like
1347 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1348 MachineBasicBlock *TBB,
1349 MachineBasicBlock *FBB,
1350 MachineBasicBlock *CurBB,
1351 MachineBasicBlock *SwitchBB,
1353 // If this node is not part of the or/and tree, emit it as a branch.
1354 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1355 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1356 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1357 BOp->getParent() != CurBB->getBasicBlock() ||
1358 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1359 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1360 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1364 // Create TmpBB after CurBB.
1365 MachineFunction::iterator BBI = CurBB;
1366 MachineFunction &MF = DAG.getMachineFunction();
1367 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1368 CurBB->getParent()->insert(++BBI, TmpBB);
1370 if (Opc == Instruction::Or) {
1371 // Codegen X | Y as:
1379 // Emit the LHS condition.
1380 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1382 // Emit the RHS condition into TmpBB.
1383 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1385 assert(Opc == Instruction::And && "Unknown merge op!");
1386 // Codegen X & Y as:
1393 // This requires creation of TmpBB after CurBB.
1395 // Emit the LHS condition.
1396 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1398 // Emit the RHS condition into TmpBB.
1399 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1403 /// If the set of cases should be emitted as a series of branches, return true.
1404 /// If we should emit this as a bunch of and/or'd together conditions, return
1407 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1408 if (Cases.size() != 2) return true;
1410 // If this is two comparisons of the same values or'd or and'd together, they
1411 // will get folded into a single comparison, so don't emit two blocks.
1412 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1413 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1414 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1415 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1419 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1420 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1421 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1422 Cases[0].CC == Cases[1].CC &&
1423 isa<Constant>(Cases[0].CmpRHS) &&
1424 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1425 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1427 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1434 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1435 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1437 // Update machine-CFG edges.
1438 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1440 // Figure out which block is immediately after the current one.
1441 MachineBasicBlock *NextBlock = 0;
1442 MachineFunction::iterator BBI = BrMBB;
1443 if (++BBI != FuncInfo.MF->end())
1446 if (I.isUnconditional()) {
1447 // Update machine-CFG edges.
1448 BrMBB->addSuccessor(Succ0MBB);
1450 // If this is not a fall-through branch, emit the branch.
1451 if (Succ0MBB != NextBlock)
1452 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1453 MVT::Other, getControlRoot(),
1454 DAG.getBasicBlock(Succ0MBB)));
1459 // If this condition is one of the special cases we handle, do special stuff
1461 const Value *CondVal = I.getCondition();
1462 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1464 // If this is a series of conditions that are or'd or and'd together, emit
1465 // this as a sequence of branches instead of setcc's with and/or operations.
1466 // As long as jumps are not expensive, this should improve performance.
1467 // For example, instead of something like:
1480 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1481 if (!TLI.isJumpExpensive() &&
1483 (BOp->getOpcode() == Instruction::And ||
1484 BOp->getOpcode() == Instruction::Or)) {
1485 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1487 // If the compares in later blocks need to use values not currently
1488 // exported from this block, export them now. This block should always
1489 // be the first entry.
1490 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1492 // Allow some cases to be rejected.
1493 if (ShouldEmitAsBranches(SwitchCases)) {
1494 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1495 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1496 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1499 // Emit the branch for this block.
1500 visitSwitchCase(SwitchCases[0], BrMBB);
1501 SwitchCases.erase(SwitchCases.begin());
1505 // Okay, we decided not to do this, remove any inserted MBB's and clear
1507 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1508 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1510 SwitchCases.clear();
1514 // Create a CaseBlock record representing this branch.
1515 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1516 NULL, Succ0MBB, Succ1MBB, BrMBB);
1518 // Use visitSwitchCase to actually insert the fast branch sequence for this
1520 visitSwitchCase(CB, BrMBB);
1523 /// visitSwitchCase - Emits the necessary code to represent a single node in
1524 /// the binary search tree resulting from lowering a switch instruction.
1525 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1526 MachineBasicBlock *SwitchBB) {
1528 SDValue CondLHS = getValue(CB.CmpLHS);
1529 DebugLoc dl = getCurDebugLoc();
1531 // Build the setcc now.
1532 if (CB.CmpMHS == NULL) {
1533 // Fold "(X == true)" to X and "(X == false)" to !X to
1534 // handle common cases produced by branch lowering.
1535 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1536 CB.CC == ISD::SETEQ)
1538 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1539 CB.CC == ISD::SETEQ) {
1540 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1541 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1543 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1545 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1547 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1548 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1550 SDValue CmpOp = getValue(CB.CmpMHS);
1551 EVT VT = CmpOp.getValueType();
1553 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1554 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1557 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1558 VT, CmpOp, DAG.getConstant(Low, VT));
1559 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1560 DAG.getConstant(High-Low, VT), ISD::SETULE);
1564 // Update successor info
1565 addSuccessorWithWeight(SwitchBB, CB.TrueBB);
1566 addSuccessorWithWeight(SwitchBB, CB.FalseBB);
1568 // Set NextBlock to be the MBB immediately after the current one, if any.
1569 // This is used to avoid emitting unnecessary branches to the next block.
1570 MachineBasicBlock *NextBlock = 0;
1571 MachineFunction::iterator BBI = SwitchBB;
1572 if (++BBI != FuncInfo.MF->end())
1575 // If the lhs block is the next block, invert the condition so that we can
1576 // fall through to the lhs instead of the rhs block.
1577 if (CB.TrueBB == NextBlock) {
1578 std::swap(CB.TrueBB, CB.FalseBB);
1579 SDValue True = DAG.getConstant(1, Cond.getValueType());
1580 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1583 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1584 MVT::Other, getControlRoot(), Cond,
1585 DAG.getBasicBlock(CB.TrueBB));
1587 // Insert the false branch. Do this even if it's a fall through branch,
1588 // this makes it easier to do DAG optimizations which require inverting
1589 // the branch condition.
1590 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1591 DAG.getBasicBlock(CB.FalseBB));
1593 DAG.setRoot(BrCond);
1596 /// visitJumpTable - Emit JumpTable node in the current MBB
1597 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1598 // Emit the code for the jump table
1599 assert(JT.Reg != -1U && "Should lower JT Header first!");
1600 EVT PTy = TLI.getPointerTy();
1601 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1603 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1604 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1605 MVT::Other, Index.getValue(1),
1607 DAG.setRoot(BrJumpTable);
1610 /// visitJumpTableHeader - This function emits necessary code to produce index
1611 /// in the JumpTable from switch case.
1612 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1613 JumpTableHeader &JTH,
1614 MachineBasicBlock *SwitchBB) {
1615 // Subtract the lowest switch case value from the value being switched on and
1616 // conditional branch to default mbb if the result is greater than the
1617 // difference between smallest and largest cases.
1618 SDValue SwitchOp = getValue(JTH.SValue);
1619 EVT VT = SwitchOp.getValueType();
1620 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1621 DAG.getConstant(JTH.First, VT));
1623 // The SDNode we just created, which holds the value being switched on minus
1624 // the smallest case value, needs to be copied to a virtual register so it
1625 // can be used as an index into the jump table in a subsequent basic block.
1626 // This value may be smaller or larger than the target's pointer type, and
1627 // therefore require extension or truncating.
1628 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1630 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1631 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1632 JumpTableReg, SwitchOp);
1633 JT.Reg = JumpTableReg;
1635 // Emit the range check for the jump table, and branch to the default block
1636 // for the switch statement if the value being switched on exceeds the largest
1637 // case in the switch.
1638 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1639 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1640 DAG.getConstant(JTH.Last-JTH.First,VT),
1643 // Set NextBlock to be the MBB immediately after the current one, if any.
1644 // This is used to avoid emitting unnecessary branches to the next block.
1645 MachineBasicBlock *NextBlock = 0;
1646 MachineFunction::iterator BBI = SwitchBB;
1648 if (++BBI != FuncInfo.MF->end())
1651 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1652 MVT::Other, CopyTo, CMP,
1653 DAG.getBasicBlock(JT.Default));
1655 if (JT.MBB != NextBlock)
1656 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1657 DAG.getBasicBlock(JT.MBB));
1659 DAG.setRoot(BrCond);
1662 /// visitBitTestHeader - This function emits necessary code to produce value
1663 /// suitable for "bit tests"
1664 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1665 MachineBasicBlock *SwitchBB) {
1666 // Subtract the minimum value
1667 SDValue SwitchOp = getValue(B.SValue);
1668 EVT VT = SwitchOp.getValueType();
1669 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1670 DAG.getConstant(B.First, VT));
1673 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1674 TLI.getSetCCResultType(Sub.getValueType()),
1675 Sub, DAG.getConstant(B.Range, VT),
1678 // Determine the type of the test operands.
1679 bool UsePtrType = false;
1680 if (!TLI.isTypeLegal(VT))
1683 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1684 if ((uint64_t)((int64_t)B.Cases[i].Mask >> VT.getSizeInBits()) + 1 >= 2) {
1685 // Switch table case range are encoded into series of masks.
1686 // Just use pointer type, it's guaranteed to fit.
1692 VT = TLI.getPointerTy();
1693 Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT);
1697 B.Reg = FuncInfo.CreateReg(VT);
1698 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1701 // Set NextBlock to be the MBB immediately after the current one, if any.
1702 // This is used to avoid emitting unnecessary branches to the next block.
1703 MachineBasicBlock *NextBlock = 0;
1704 MachineFunction::iterator BBI = SwitchBB;
1705 if (++BBI != FuncInfo.MF->end())
1708 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1710 addSuccessorWithWeight(SwitchBB, B.Default);
1711 addSuccessorWithWeight(SwitchBB, MBB);
1713 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1714 MVT::Other, CopyTo, RangeCmp,
1715 DAG.getBasicBlock(B.Default));
1717 if (MBB != NextBlock)
1718 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1719 DAG.getBasicBlock(MBB));
1721 DAG.setRoot(BrRange);
1724 /// visitBitTestCase - this function produces one "bit test"
1725 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1726 MachineBasicBlock* NextMBB,
1729 MachineBasicBlock *SwitchBB) {
1731 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1734 unsigned PopCount = CountPopulation_64(B.Mask);
1735 if (PopCount == 1) {
1736 // Testing for a single bit; just compare the shift count with what it
1737 // would need to be to shift a 1 bit in that position.
1738 Cmp = DAG.getSetCC(getCurDebugLoc(),
1739 TLI.getSetCCResultType(VT),
1741 DAG.getConstant(CountTrailingZeros_64(B.Mask), VT),
1743 } else if (PopCount == BB.Range) {
1744 // There is only one zero bit in the range, test for it directly.
1745 Cmp = DAG.getSetCC(getCurDebugLoc(),
1746 TLI.getSetCCResultType(VT),
1748 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1751 // Make desired shift
1752 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT,
1753 DAG.getConstant(1, VT), ShiftOp);
1755 // Emit bit tests and jumps
1756 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1757 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1758 Cmp = DAG.getSetCC(getCurDebugLoc(),
1759 TLI.getSetCCResultType(VT),
1760 AndOp, DAG.getConstant(0, VT),
1764 addSuccessorWithWeight(SwitchBB, B.TargetBB);
1765 addSuccessorWithWeight(SwitchBB, NextMBB);
1767 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1768 MVT::Other, getControlRoot(),
1769 Cmp, DAG.getBasicBlock(B.TargetBB));
1771 // Set NextBlock to be the MBB immediately after the current one, if any.
1772 // This is used to avoid emitting unnecessary branches to the next block.
1773 MachineBasicBlock *NextBlock = 0;
1774 MachineFunction::iterator BBI = SwitchBB;
1775 if (++BBI != FuncInfo.MF->end())
1778 if (NextMBB != NextBlock)
1779 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1780 DAG.getBasicBlock(NextMBB));
1785 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1786 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1788 // Retrieve successors.
1789 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1790 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1792 const Value *Callee(I.getCalledValue());
1793 if (isa<InlineAsm>(Callee))
1796 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1798 // If the value of the invoke is used outside of its defining block, make it
1799 // available as a virtual register.
1800 CopyToExportRegsIfNeeded(&I);
1802 // Update successor info
1803 InvokeMBB->addSuccessor(Return);
1804 InvokeMBB->addSuccessor(LandingPad);
1806 // Drop into normal successor.
1807 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1808 MVT::Other, getControlRoot(),
1809 DAG.getBasicBlock(Return)));
1812 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
1815 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
1816 // FIXME: Handle this
1819 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1820 /// small case ranges).
1821 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1822 CaseRecVector& WorkList,
1824 MachineBasicBlock *Default,
1825 MachineBasicBlock *SwitchBB) {
1826 Case& BackCase = *(CR.Range.second-1);
1828 // Size is the number of Cases represented by this range.
1829 size_t Size = CR.Range.second - CR.Range.first;
1833 // Get the MachineFunction which holds the current MBB. This is used when
1834 // inserting any additional MBBs necessary to represent the switch.
1835 MachineFunction *CurMF = FuncInfo.MF;
1837 // Figure out which block is immediately after the current one.
1838 MachineBasicBlock *NextBlock = 0;
1839 MachineFunction::iterator BBI = CR.CaseBB;
1841 if (++BBI != FuncInfo.MF->end())
1844 // If any two of the cases has the same destination, and if one value
1845 // is the same as the other, but has one bit unset that the other has set,
1846 // use bit manipulation to do two compares at once. For example:
1847 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1848 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
1849 // TODO: Handle cases where CR.CaseBB != SwitchBB.
1850 if (Size == 2 && CR.CaseBB == SwitchBB) {
1851 Case &Small = *CR.Range.first;
1852 Case &Big = *(CR.Range.second-1);
1854 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
1855 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
1856 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
1858 // Check that there is only one bit different.
1859 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
1860 (SmallValue | BigValue) == BigValue) {
1861 // Isolate the common bit.
1862 APInt CommonBit = BigValue & ~SmallValue;
1863 assert((SmallValue | CommonBit) == BigValue &&
1864 CommonBit.countPopulation() == 1 && "Not a common bit?");
1866 SDValue CondLHS = getValue(SV);
1867 EVT VT = CondLHS.getValueType();
1868 DebugLoc DL = getCurDebugLoc();
1870 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
1871 DAG.getConstant(CommonBit, VT));
1872 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
1873 Or, DAG.getConstant(BigValue, VT),
1876 // Update successor info.
1877 SwitchBB->addSuccessor(Small.BB);
1878 SwitchBB->addSuccessor(Default);
1880 // Insert the true branch.
1881 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
1882 getControlRoot(), Cond,
1883 DAG.getBasicBlock(Small.BB));
1885 // Insert the false branch.
1886 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
1887 DAG.getBasicBlock(Default));
1889 DAG.setRoot(BrCond);
1895 // Rearrange the case blocks so that the last one falls through if possible.
1896 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1897 // The last case block won't fall through into 'NextBlock' if we emit the
1898 // branches in this order. See if rearranging a case value would help.
1899 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1900 if (I->BB == NextBlock) {
1901 std::swap(*I, BackCase);
1907 // Create a CaseBlock record representing a conditional branch to
1908 // the Case's target mbb if the value being switched on SV is equal
1910 MachineBasicBlock *CurBlock = CR.CaseBB;
1911 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1912 MachineBasicBlock *FallThrough;
1914 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1915 CurMF->insert(BBI, FallThrough);
1917 // Put SV in a virtual register to make it available from the new blocks.
1918 ExportFromCurrentBlock(SV);
1920 // If the last case doesn't match, go to the default block.
1921 FallThrough = Default;
1924 const Value *RHS, *LHS, *MHS;
1926 if (I->High == I->Low) {
1927 // This is just small small case range :) containing exactly 1 case
1929 LHS = SV; RHS = I->High; MHS = NULL;
1932 LHS = I->Low; MHS = SV; RHS = I->High;
1934 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1936 // If emitting the first comparison, just call visitSwitchCase to emit the
1937 // code into the current block. Otherwise, push the CaseBlock onto the
1938 // vector to be later processed by SDISel, and insert the node's MBB
1939 // before the next MBB.
1940 if (CurBlock == SwitchBB)
1941 visitSwitchCase(CB, SwitchBB);
1943 SwitchCases.push_back(CB);
1945 CurBlock = FallThrough;
1951 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1952 return !DisableJumpTables &&
1953 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1954 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1957 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1958 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1959 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
1960 return (LastExt - FirstExt + 1ULL);
1963 /// handleJTSwitchCase - Emit jumptable for current switch case range
1964 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1965 CaseRecVector& WorkList,
1967 MachineBasicBlock* Default,
1968 MachineBasicBlock *SwitchBB) {
1969 Case& FrontCase = *CR.Range.first;
1970 Case& BackCase = *(CR.Range.second-1);
1972 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1973 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1975 APInt TSize(First.getBitWidth(), 0);
1976 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1980 if (!areJTsAllowed(TLI) || TSize.ult(4))
1983 APInt Range = ComputeRange(First, Last);
1984 double Density = TSize.roundToDouble() / Range.roundToDouble();
1988 DEBUG(dbgs() << "Lowering jump table\n"
1989 << "First entry: " << First << ". Last entry: " << Last << '\n'
1990 << "Range: " << Range
1991 << ". Size: " << TSize << ". Density: " << Density << "\n\n");
1993 // Get the MachineFunction which holds the current MBB. This is used when
1994 // inserting any additional MBBs necessary to represent the switch.
1995 MachineFunction *CurMF = FuncInfo.MF;
1997 // Figure out which block is immediately after the current one.
1998 MachineFunction::iterator BBI = CR.CaseBB;
2001 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2003 // Create a new basic block to hold the code for loading the address
2004 // of the jump table, and jumping to it. Update successor information;
2005 // we will either branch to the default case for the switch, or the jump
2007 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2008 CurMF->insert(BBI, JumpTableBB);
2010 addSuccessorWithWeight(CR.CaseBB, Default);
2011 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2013 // Build a vector of destination BBs, corresponding to each target
2014 // of the jump table. If the value of the jump table slot corresponds to
2015 // a case statement, push the case's BB onto the vector, otherwise, push
2017 std::vector<MachineBasicBlock*> DestBBs;
2019 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2020 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2021 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2023 if (Low.sle(TEI) && TEI.sle(High)) {
2024 DestBBs.push_back(I->BB);
2028 DestBBs.push_back(Default);
2032 // Update successor info. Add one edge to each unique successor.
2033 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2034 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2035 E = DestBBs.end(); I != E; ++I) {
2036 if (!SuccsHandled[(*I)->getNumber()]) {
2037 SuccsHandled[(*I)->getNumber()] = true;
2038 addSuccessorWithWeight(JumpTableBB, *I);
2042 // Create a jump table index for this jump table.
2043 unsigned JTEncoding = TLI.getJumpTableEncoding();
2044 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2045 ->createJumpTableIndex(DestBBs);
2047 // Set the jump table information so that we can codegen it as a second
2048 // MachineBasicBlock
2049 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2050 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2051 if (CR.CaseBB == SwitchBB)
2052 visitJumpTableHeader(JT, JTH, SwitchBB);
2054 JTCases.push_back(JumpTableBlock(JTH, JT));
2059 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2061 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2062 CaseRecVector& WorkList,
2064 MachineBasicBlock *Default,
2065 MachineBasicBlock *SwitchBB) {
2066 // Get the MachineFunction which holds the current MBB. This is used when
2067 // inserting any additional MBBs necessary to represent the switch.
2068 MachineFunction *CurMF = FuncInfo.MF;
2070 // Figure out which block is immediately after the current one.
2071 MachineFunction::iterator BBI = CR.CaseBB;
2074 Case& FrontCase = *CR.Range.first;
2075 Case& BackCase = *(CR.Range.second-1);
2076 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2078 // Size is the number of Cases represented by this range.
2079 unsigned Size = CR.Range.second - CR.Range.first;
2081 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2082 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2084 CaseItr Pivot = CR.Range.first + Size/2;
2086 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2087 // (heuristically) allow us to emit JumpTable's later.
2088 APInt TSize(First.getBitWidth(), 0);
2089 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2093 APInt LSize = FrontCase.size();
2094 APInt RSize = TSize-LSize;
2095 DEBUG(dbgs() << "Selecting best pivot: \n"
2096 << "First: " << First << ", Last: " << Last <<'\n'
2097 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2098 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2100 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2101 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2102 APInt Range = ComputeRange(LEnd, RBegin);
2103 assert((Range - 2ULL).isNonNegative() &&
2104 "Invalid case distance");
2105 // Use volatile double here to avoid excess precision issues on some hosts,
2106 // e.g. that use 80-bit X87 registers.
2107 volatile double LDensity =
2108 (double)LSize.roundToDouble() /
2109 (LEnd - First + 1ULL).roundToDouble();
2110 volatile double RDensity =
2111 (double)RSize.roundToDouble() /
2112 (Last - RBegin + 1ULL).roundToDouble();
2113 double Metric = Range.logBase2()*(LDensity+RDensity);
2114 // Should always split in some non-trivial place
2115 DEBUG(dbgs() <<"=>Step\n"
2116 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2117 << "LDensity: " << LDensity
2118 << ", RDensity: " << RDensity << '\n'
2119 << "Metric: " << Metric << '\n');
2120 if (FMetric < Metric) {
2123 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2129 if (areJTsAllowed(TLI)) {
2130 // If our case is dense we *really* should handle it earlier!
2131 assert((FMetric > 0) && "Should handle dense range earlier!");
2133 Pivot = CR.Range.first + Size/2;
2136 CaseRange LHSR(CR.Range.first, Pivot);
2137 CaseRange RHSR(Pivot, CR.Range.second);
2138 Constant *C = Pivot->Low;
2139 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2141 // We know that we branch to the LHS if the Value being switched on is
2142 // less than the Pivot value, C. We use this to optimize our binary
2143 // tree a bit, by recognizing that if SV is greater than or equal to the
2144 // LHS's Case Value, and that Case Value is exactly one less than the
2145 // Pivot's Value, then we can branch directly to the LHS's Target,
2146 // rather than creating a leaf node for it.
2147 if ((LHSR.second - LHSR.first) == 1 &&
2148 LHSR.first->High == CR.GE &&
2149 cast<ConstantInt>(C)->getValue() ==
2150 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2151 TrueBB = LHSR.first->BB;
2153 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2154 CurMF->insert(BBI, TrueBB);
2155 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2157 // Put SV in a virtual register to make it available from the new blocks.
2158 ExportFromCurrentBlock(SV);
2161 // Similar to the optimization above, if the Value being switched on is
2162 // known to be less than the Constant CR.LT, and the current Case Value
2163 // is CR.LT - 1, then we can branch directly to the target block for
2164 // the current Case Value, rather than emitting a RHS leaf node for it.
2165 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2166 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2167 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2168 FalseBB = RHSR.first->BB;
2170 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2171 CurMF->insert(BBI, FalseBB);
2172 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2174 // Put SV in a virtual register to make it available from the new blocks.
2175 ExportFromCurrentBlock(SV);
2178 // Create a CaseBlock record representing a conditional branch to
2179 // the LHS node if the value being switched on SV is less than C.
2180 // Otherwise, branch to LHS.
2181 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2183 if (CR.CaseBB == SwitchBB)
2184 visitSwitchCase(CB, SwitchBB);
2186 SwitchCases.push_back(CB);
2191 /// handleBitTestsSwitchCase - if current case range has few destination and
2192 /// range span less, than machine word bitwidth, encode case range into series
2193 /// of masks and emit bit tests with these masks.
2194 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2195 CaseRecVector& WorkList,
2197 MachineBasicBlock* Default,
2198 MachineBasicBlock *SwitchBB){
2199 EVT PTy = TLI.getPointerTy();
2200 unsigned IntPtrBits = PTy.getSizeInBits();
2202 Case& FrontCase = *CR.Range.first;
2203 Case& BackCase = *(CR.Range.second-1);
2205 // Get the MachineFunction which holds the current MBB. This is used when
2206 // inserting any additional MBBs necessary to represent the switch.
2207 MachineFunction *CurMF = FuncInfo.MF;
2209 // If target does not have legal shift left, do not emit bit tests at all.
2210 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
2214 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2216 // Single case counts one, case range - two.
2217 numCmps += (I->Low == I->High ? 1 : 2);
2220 // Count unique destinations
2221 SmallSet<MachineBasicBlock*, 4> Dests;
2222 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2223 Dests.insert(I->BB);
2224 if (Dests.size() > 3)
2225 // Don't bother the code below, if there are too much unique destinations
2228 DEBUG(dbgs() << "Total number of unique destinations: "
2229 << Dests.size() << '\n'
2230 << "Total number of comparisons: " << numCmps << '\n');
2232 // Compute span of values.
2233 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2234 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2235 APInt cmpRange = maxValue - minValue;
2237 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2238 << "Low bound: " << minValue << '\n'
2239 << "High bound: " << maxValue << '\n');
2241 if (cmpRange.uge(IntPtrBits) ||
2242 (!(Dests.size() == 1 && numCmps >= 3) &&
2243 !(Dests.size() == 2 && numCmps >= 5) &&
2244 !(Dests.size() >= 3 && numCmps >= 6)))
2247 DEBUG(dbgs() << "Emitting bit tests\n");
2248 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2250 // Optimize the case where all the case values fit in a
2251 // word without having to subtract minValue. In this case,
2252 // we can optimize away the subtraction.
2253 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2254 cmpRange = maxValue;
2256 lowBound = minValue;
2259 CaseBitsVector CasesBits;
2260 unsigned i, count = 0;
2262 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2263 MachineBasicBlock* Dest = I->BB;
2264 for (i = 0; i < count; ++i)
2265 if (Dest == CasesBits[i].BB)
2269 assert((count < 3) && "Too much destinations to test!");
2270 CasesBits.push_back(CaseBits(0, Dest, 0));
2274 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2275 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2277 uint64_t lo = (lowValue - lowBound).getZExtValue();
2278 uint64_t hi = (highValue - lowBound).getZExtValue();
2280 for (uint64_t j = lo; j <= hi; j++) {
2281 CasesBits[i].Mask |= 1ULL << j;
2282 CasesBits[i].Bits++;
2286 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2290 // Figure out which block is immediately after the current one.
2291 MachineFunction::iterator BBI = CR.CaseBB;
2294 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2296 DEBUG(dbgs() << "Cases:\n");
2297 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2298 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2299 << ", Bits: " << CasesBits[i].Bits
2300 << ", BB: " << CasesBits[i].BB << '\n');
2302 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2303 CurMF->insert(BBI, CaseBB);
2304 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2308 // Put SV in a virtual register to make it available from the new blocks.
2309 ExportFromCurrentBlock(SV);
2312 BitTestBlock BTB(lowBound, cmpRange, SV,
2313 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2314 CR.CaseBB, Default, BTC);
2316 if (CR.CaseBB == SwitchBB)
2317 visitBitTestHeader(BTB, SwitchBB);
2319 BitTestCases.push_back(BTB);
2324 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2325 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2326 const SwitchInst& SI) {
2329 // Start with "simple" cases
2330 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2331 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2332 Cases.push_back(Case(SI.getSuccessorValue(i),
2333 SI.getSuccessorValue(i),
2336 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2338 // Merge case into clusters
2339 if (Cases.size() >= 2)
2340 // Must recompute end() each iteration because it may be
2341 // invalidated by erase if we hold on to it
2342 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
2343 J != Cases.end(); ) {
2344 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2345 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2346 MachineBasicBlock* nextBB = J->BB;
2347 MachineBasicBlock* currentBB = I->BB;
2349 // If the two neighboring cases go to the same destination, merge them
2350 // into a single case.
2351 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2359 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2360 if (I->Low != I->High)
2361 // A range counts double, since it requires two compares.
2368 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2369 MachineBasicBlock *Last) {
2371 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2372 if (JTCases[i].first.HeaderBB == First)
2373 JTCases[i].first.HeaderBB = Last;
2375 // Update BitTestCases.
2376 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2377 if (BitTestCases[i].Parent == First)
2378 BitTestCases[i].Parent = Last;
2381 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2382 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2384 // Figure out which block is immediately after the current one.
2385 MachineBasicBlock *NextBlock = 0;
2386 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2388 // If there is only the default destination, branch to it if it is not the
2389 // next basic block. Otherwise, just fall through.
2390 if (SI.getNumOperands() == 2) {
2391 // Update machine-CFG edges.
2393 // If this is not a fall-through branch, emit the branch.
2394 SwitchMBB->addSuccessor(Default);
2395 if (Default != NextBlock)
2396 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2397 MVT::Other, getControlRoot(),
2398 DAG.getBasicBlock(Default)));
2403 // If there are any non-default case statements, create a vector of Cases
2404 // representing each one, and sort the vector so that we can efficiently
2405 // create a binary search tree from them.
2407 size_t numCmps = Clusterify(Cases, SI);
2408 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2409 << ". Total compares: " << numCmps << '\n');
2412 // Get the Value to be switched on and default basic blocks, which will be
2413 // inserted into CaseBlock records, representing basic blocks in the binary
2415 const Value *SV = SI.getOperand(0);
2417 // Push the initial CaseRec onto the worklist
2418 CaseRecVector WorkList;
2419 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2420 CaseRange(Cases.begin(),Cases.end())));
2422 while (!WorkList.empty()) {
2423 // Grab a record representing a case range to process off the worklist
2424 CaseRec CR = WorkList.back();
2425 WorkList.pop_back();
2427 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2430 // If the range has few cases (two or less) emit a series of specific
2432 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2435 // If the switch has more than 5 blocks, and at least 40% dense, and the
2436 // target supports indirect branches, then emit a jump table rather than
2437 // lowering the switch to a binary tree of conditional branches.
2438 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2441 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2442 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2443 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2447 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2448 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2450 // Update machine-CFG edges with unique successors.
2451 SmallVector<BasicBlock*, 32> succs;
2452 succs.reserve(I.getNumSuccessors());
2453 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2454 succs.push_back(I.getSuccessor(i));
2455 array_pod_sort(succs.begin(), succs.end());
2456 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2457 for (unsigned i = 0, e = succs.size(); i != e; ++i) {
2458 MachineBasicBlock *Succ = FuncInfo.MBBMap[succs[i]];
2459 addSuccessorWithWeight(IndirectBrMBB, Succ);
2462 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2463 MVT::Other, getControlRoot(),
2464 getValue(I.getAddress())));
2467 void SelectionDAGBuilder::visitFSub(const User &I) {
2468 // -0.0 - X --> fneg
2469 Type *Ty = I.getType();
2470 if (isa<Constant>(I.getOperand(0)) &&
2471 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2472 SDValue Op2 = getValue(I.getOperand(1));
2473 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2474 Op2.getValueType(), Op2));
2478 visitBinary(I, ISD::FSUB);
2481 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2482 SDValue Op1 = getValue(I.getOperand(0));
2483 SDValue Op2 = getValue(I.getOperand(1));
2484 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2485 Op1.getValueType(), Op1, Op2));
2488 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2489 SDValue Op1 = getValue(I.getOperand(0));
2490 SDValue Op2 = getValue(I.getOperand(1));
2492 MVT ShiftTy = TLI.getShiftAmountTy(Op2.getValueType());
2494 // Coerce the shift amount to the right type if we can.
2495 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2496 unsigned ShiftSize = ShiftTy.getSizeInBits();
2497 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2498 DebugLoc DL = getCurDebugLoc();
2500 // If the operand is smaller than the shift count type, promote it.
2501 if (ShiftSize > Op2Size)
2502 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2504 // If the operand is larger than the shift count type but the shift
2505 // count type has enough bits to represent any shift value, truncate
2506 // it now. This is a common case and it exposes the truncate to
2507 // optimization early.
2508 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2509 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2510 // Otherwise we'll need to temporarily settle for some other convenient
2511 // type. Type legalization will make adjustments once the shiftee is split.
2513 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2516 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2517 Op1.getValueType(), Op1, Op2));
2520 void SelectionDAGBuilder::visitSDiv(const User &I) {
2521 SDValue Op1 = getValue(I.getOperand(0));
2522 SDValue Op2 = getValue(I.getOperand(1));
2524 // Turn exact SDivs into multiplications.
2525 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2527 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2528 !isa<ConstantSDNode>(Op1) &&
2529 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2530 setValue(&I, TLI.BuildExactSDIV(Op1, Op2, getCurDebugLoc(), DAG));
2532 setValue(&I, DAG.getNode(ISD::SDIV, getCurDebugLoc(), Op1.getValueType(),
2536 void SelectionDAGBuilder::visitICmp(const User &I) {
2537 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2538 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2539 predicate = IC->getPredicate();
2540 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2541 predicate = ICmpInst::Predicate(IC->getPredicate());
2542 SDValue Op1 = getValue(I.getOperand(0));
2543 SDValue Op2 = getValue(I.getOperand(1));
2544 ISD::CondCode Opcode = getICmpCondCode(predicate);
2546 EVT DestVT = TLI.getValueType(I.getType());
2547 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2550 void SelectionDAGBuilder::visitFCmp(const User &I) {
2551 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2552 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2553 predicate = FC->getPredicate();
2554 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2555 predicate = FCmpInst::Predicate(FC->getPredicate());
2556 SDValue Op1 = getValue(I.getOperand(0));
2557 SDValue Op2 = getValue(I.getOperand(1));
2558 ISD::CondCode Condition = getFCmpCondCode(predicate);
2559 EVT DestVT = TLI.getValueType(I.getType());
2560 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2563 void SelectionDAGBuilder::visitSelect(const User &I) {
2564 SmallVector<EVT, 4> ValueVTs;
2565 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2566 unsigned NumValues = ValueVTs.size();
2567 if (NumValues == 0) return;
2569 SmallVector<SDValue, 4> Values(NumValues);
2570 SDValue Cond = getValue(I.getOperand(0));
2571 SDValue TrueVal = getValue(I.getOperand(1));
2572 SDValue FalseVal = getValue(I.getOperand(2));
2574 for (unsigned i = 0; i != NumValues; ++i)
2575 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2576 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2578 SDValue(TrueVal.getNode(),
2579 TrueVal.getResNo() + i),
2580 SDValue(FalseVal.getNode(),
2581 FalseVal.getResNo() + i));
2583 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2584 DAG.getVTList(&ValueVTs[0], NumValues),
2585 &Values[0], NumValues));
2588 void SelectionDAGBuilder::visitTrunc(const User &I) {
2589 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2590 SDValue N = getValue(I.getOperand(0));
2591 EVT DestVT = TLI.getValueType(I.getType());
2592 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2595 void SelectionDAGBuilder::visitZExt(const User &I) {
2596 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2597 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2598 SDValue N = getValue(I.getOperand(0));
2599 EVT DestVT = TLI.getValueType(I.getType());
2600 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2603 void SelectionDAGBuilder::visitSExt(const User &I) {
2604 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2605 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2606 SDValue N = getValue(I.getOperand(0));
2607 EVT DestVT = TLI.getValueType(I.getType());
2608 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2611 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2612 // FPTrunc is never a no-op cast, no need to check
2613 SDValue N = getValue(I.getOperand(0));
2614 EVT DestVT = TLI.getValueType(I.getType());
2615 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2616 DestVT, N, DAG.getIntPtrConstant(0)));
2619 void SelectionDAGBuilder::visitFPExt(const User &I){
2620 // FPTrunc is never a no-op cast, no need to check
2621 SDValue N = getValue(I.getOperand(0));
2622 EVT DestVT = TLI.getValueType(I.getType());
2623 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2626 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2627 // FPToUI is never a no-op cast, no need to check
2628 SDValue N = getValue(I.getOperand(0));
2629 EVT DestVT = TLI.getValueType(I.getType());
2630 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2633 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2634 // FPToSI is never a no-op cast, no need to check
2635 SDValue N = getValue(I.getOperand(0));
2636 EVT DestVT = TLI.getValueType(I.getType());
2637 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2640 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2641 // UIToFP is never a no-op cast, no need to check
2642 SDValue N = getValue(I.getOperand(0));
2643 EVT DestVT = TLI.getValueType(I.getType());
2644 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2647 void SelectionDAGBuilder::visitSIToFP(const User &I){
2648 // SIToFP is never a no-op cast, no need to check
2649 SDValue N = getValue(I.getOperand(0));
2650 EVT DestVT = TLI.getValueType(I.getType());
2651 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2654 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2655 // What to do depends on the size of the integer and the size of the pointer.
2656 // We can either truncate, zero extend, or no-op, accordingly.
2657 SDValue N = getValue(I.getOperand(0));
2658 EVT DestVT = TLI.getValueType(I.getType());
2659 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2662 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2663 // What to do depends on the size of the integer and the size of the pointer.
2664 // We can either truncate, zero extend, or no-op, accordingly.
2665 SDValue N = getValue(I.getOperand(0));
2666 EVT DestVT = TLI.getValueType(I.getType());
2667 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2670 void SelectionDAGBuilder::visitBitCast(const User &I) {
2671 SDValue N = getValue(I.getOperand(0));
2672 EVT DestVT = TLI.getValueType(I.getType());
2674 // BitCast assures us that source and destination are the same size so this is
2675 // either a BITCAST or a no-op.
2676 if (DestVT != N.getValueType())
2677 setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
2678 DestVT, N)); // convert types.
2680 setValue(&I, N); // noop cast.
2683 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2684 SDValue InVec = getValue(I.getOperand(0));
2685 SDValue InVal = getValue(I.getOperand(1));
2686 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2688 getValue(I.getOperand(2)));
2689 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2690 TLI.getValueType(I.getType()),
2691 InVec, InVal, InIdx));
2694 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2695 SDValue InVec = getValue(I.getOperand(0));
2696 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2698 getValue(I.getOperand(1)));
2699 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2700 TLI.getValueType(I.getType()), InVec, InIdx));
2703 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2704 // from SIndx and increasing to the element length (undefs are allowed).
2705 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2706 unsigned MaskNumElts = Mask.size();
2707 for (unsigned i = 0; i != MaskNumElts; ++i)
2708 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2713 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2714 SmallVector<int, 8> Mask;
2715 SDValue Src1 = getValue(I.getOperand(0));
2716 SDValue Src2 = getValue(I.getOperand(1));
2718 // Convert the ConstantVector mask operand into an array of ints, with -1
2719 // representing undef values.
2720 SmallVector<Constant*, 8> MaskElts;
2721 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2722 unsigned MaskNumElts = MaskElts.size();
2723 for (unsigned i = 0; i != MaskNumElts; ++i) {
2724 if (isa<UndefValue>(MaskElts[i]))
2727 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2730 EVT VT = TLI.getValueType(I.getType());
2731 EVT SrcVT = Src1.getValueType();
2732 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2734 if (SrcNumElts == MaskNumElts) {
2735 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2740 // Normalize the shuffle vector since mask and vector length don't match.
2741 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2742 // Mask is longer than the source vectors and is a multiple of the source
2743 // vectors. We can use concatenate vector to make the mask and vectors
2745 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2746 // The shuffle is concatenating two vectors together.
2747 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2752 // Pad both vectors with undefs to make them the same length as the mask.
2753 unsigned NumConcat = MaskNumElts / SrcNumElts;
2754 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2755 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2756 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2758 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2759 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2763 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2764 getCurDebugLoc(), VT,
2765 &MOps1[0], NumConcat);
2766 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2767 getCurDebugLoc(), VT,
2768 &MOps2[0], NumConcat);
2770 // Readjust mask for new input vector length.
2771 SmallVector<int, 8> MappedOps;
2772 for (unsigned i = 0; i != MaskNumElts; ++i) {
2774 if (Idx < (int)SrcNumElts)
2775 MappedOps.push_back(Idx);
2777 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2780 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2785 if (SrcNumElts > MaskNumElts) {
2786 // Analyze the access pattern of the vector to see if we can extract
2787 // two subvectors and do the shuffle. The analysis is done by calculating
2788 // the range of elements the mask access on both vectors.
2789 int MinRange[2] = { static_cast<int>(SrcNumElts+1),
2790 static_cast<int>(SrcNumElts+1)};
2791 int MaxRange[2] = {-1, -1};
2793 for (unsigned i = 0; i != MaskNumElts; ++i) {
2799 if (Idx >= (int)SrcNumElts) {
2803 if (Idx > MaxRange[Input])
2804 MaxRange[Input] = Idx;
2805 if (Idx < MinRange[Input])
2806 MinRange[Input] = Idx;
2809 // Check if the access is smaller than the vector size and can we find
2810 // a reasonable extract index.
2811 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2813 int StartIdx[2]; // StartIdx to extract from
2814 for (int Input=0; Input < 2; ++Input) {
2815 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2816 RangeUse[Input] = 0; // Unused
2817 StartIdx[Input] = 0;
2818 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2819 // Fits within range but we should see if we can find a good
2820 // start index that is a multiple of the mask length.
2821 if (MaxRange[Input] < (int)MaskNumElts) {
2822 RangeUse[Input] = 1; // Extract from beginning of the vector
2823 StartIdx[Input] = 0;
2825 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2826 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2827 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2828 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2833 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2834 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2837 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2838 // Extract appropriate subvector and generate a vector shuffle
2839 for (int Input=0; Input < 2; ++Input) {
2840 SDValue &Src = Input == 0 ? Src1 : Src2;
2841 if (RangeUse[Input] == 0)
2842 Src = DAG.getUNDEF(VT);
2844 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2845 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2848 // Calculate new mask.
2849 SmallVector<int, 8> MappedOps;
2850 for (unsigned i = 0; i != MaskNumElts; ++i) {
2853 MappedOps.push_back(Idx);
2854 else if (Idx < (int)SrcNumElts)
2855 MappedOps.push_back(Idx - StartIdx[0]);
2857 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2860 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2866 // We can't use either concat vectors or extract subvectors so fall back to
2867 // replacing the shuffle with extract and build vector.
2868 // to insert and build vector.
2869 EVT EltVT = VT.getVectorElementType();
2870 EVT PtrVT = TLI.getPointerTy();
2871 SmallVector<SDValue,8> Ops;
2872 for (unsigned i = 0; i != MaskNumElts; ++i) {
2874 Ops.push_back(DAG.getUNDEF(EltVT));
2879 if (Idx < (int)SrcNumElts)
2880 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2881 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2883 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2885 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2891 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2892 VT, &Ops[0], Ops.size()));
2895 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2896 const Value *Op0 = I.getOperand(0);
2897 const Value *Op1 = I.getOperand(1);
2898 Type *AggTy = I.getType();
2899 Type *ValTy = Op1->getType();
2900 bool IntoUndef = isa<UndefValue>(Op0);
2901 bool FromUndef = isa<UndefValue>(Op1);
2903 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
2905 SmallVector<EVT, 4> AggValueVTs;
2906 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2907 SmallVector<EVT, 4> ValValueVTs;
2908 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2910 unsigned NumAggValues = AggValueVTs.size();
2911 unsigned NumValValues = ValValueVTs.size();
2912 SmallVector<SDValue, 4> Values(NumAggValues);
2914 SDValue Agg = getValue(Op0);
2916 // Copy the beginning value(s) from the original aggregate.
2917 for (; i != LinearIndex; ++i)
2918 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2919 SDValue(Agg.getNode(), Agg.getResNo() + i);
2920 // Copy values from the inserted value(s).
2922 SDValue Val = getValue(Op1);
2923 for (; i != LinearIndex + NumValValues; ++i)
2924 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2925 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2927 // Copy remaining value(s) from the original aggregate.
2928 for (; i != NumAggValues; ++i)
2929 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2930 SDValue(Agg.getNode(), Agg.getResNo() + i);
2932 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2933 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2934 &Values[0], NumAggValues));
2937 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2938 const Value *Op0 = I.getOperand(0);
2939 Type *AggTy = Op0->getType();
2940 Type *ValTy = I.getType();
2941 bool OutOfUndef = isa<UndefValue>(Op0);
2943 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
2945 SmallVector<EVT, 4> ValValueVTs;
2946 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2948 unsigned NumValValues = ValValueVTs.size();
2950 // Ignore a extractvalue that produces an empty object
2951 if (!NumValValues) {
2952 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
2956 SmallVector<SDValue, 4> Values(NumValValues);
2958 SDValue Agg = getValue(Op0);
2959 // Copy out the selected value(s).
2960 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2961 Values[i - LinearIndex] =
2963 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2964 SDValue(Agg.getNode(), Agg.getResNo() + i);
2966 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2967 DAG.getVTList(&ValValueVTs[0], NumValValues),
2968 &Values[0], NumValValues));
2971 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2972 SDValue N = getValue(I.getOperand(0));
2973 Type *Ty = I.getOperand(0)->getType();
2975 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2977 const Value *Idx = *OI;
2978 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
2979 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2982 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2983 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2984 DAG.getIntPtrConstant(Offset));
2987 Ty = StTy->getElementType(Field);
2989 Ty = cast<SequentialType>(Ty)->getElementType();
2991 // If this is a constant subscript, handle it quickly.
2992 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2993 if (CI->isZero()) continue;
2995 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2997 EVT PTy = TLI.getPointerTy();
2998 unsigned PtrBits = PTy.getSizeInBits();
3000 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
3002 DAG.getConstant(Offs, MVT::i64));
3004 OffsVal = DAG.getIntPtrConstant(Offs);
3006 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
3011 // N = N + Idx * ElementSize;
3012 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
3013 TD->getTypeAllocSize(Ty));
3014 SDValue IdxN = getValue(Idx);
3016 // If the index is smaller or larger than intptr_t, truncate or extend
3018 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
3020 // If this is a multiply by a power of two, turn it into a shl
3021 // immediately. This is a very common case.
3022 if (ElementSize != 1) {
3023 if (ElementSize.isPowerOf2()) {
3024 unsigned Amt = ElementSize.logBase2();
3025 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
3026 N.getValueType(), IdxN,
3027 DAG.getConstant(Amt, TLI.getPointerTy()));
3029 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
3030 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
3031 N.getValueType(), IdxN, Scale);
3035 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3036 N.getValueType(), N, IdxN);
3043 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3044 // If this is a fixed sized alloca in the entry block of the function,
3045 // allocate it statically on the stack.
3046 if (FuncInfo.StaticAllocaMap.count(&I))
3047 return; // getValue will auto-populate this.
3049 Type *Ty = I.getAllocatedType();
3050 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
3052 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
3055 SDValue AllocSize = getValue(I.getArraySize());
3057 EVT IntPtr = TLI.getPointerTy();
3058 if (AllocSize.getValueType() != IntPtr)
3059 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
3061 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
3063 DAG.getConstant(TySize, IntPtr));
3065 // Handle alignment. If the requested alignment is less than or equal to
3066 // the stack alignment, ignore it. If the size is greater than or equal to
3067 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3068 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
3069 if (Align <= StackAlign)
3072 // Round the size of the allocation up to the stack alignment size
3073 // by add SA-1 to the size.
3074 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3075 AllocSize.getValueType(), AllocSize,
3076 DAG.getIntPtrConstant(StackAlign-1));
3078 // Mask out the low bits for alignment purposes.
3079 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
3080 AllocSize.getValueType(), AllocSize,
3081 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3083 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3084 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3085 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
3088 DAG.setRoot(DSA.getValue(1));
3090 // Inform the Frame Information that we have just allocated a variable-sized
3092 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
3095 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3096 const Value *SV = I.getOperand(0);
3097 SDValue Ptr = getValue(SV);
3099 Type *Ty = I.getType();
3101 bool isVolatile = I.isVolatile();
3102 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3103 unsigned Alignment = I.getAlignment();
3104 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3106 SmallVector<EVT, 4> ValueVTs;
3107 SmallVector<uint64_t, 4> Offsets;
3108 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3109 unsigned NumValues = ValueVTs.size();
3114 bool ConstantMemory = false;
3115 if (I.isVolatile() || NumValues > MaxParallelChains)
3116 // Serialize volatile loads with other side effects.
3118 else if (AA->pointsToConstantMemory(
3119 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
3120 // Do not serialize (non-volatile) loads of constant memory with anything.
3121 Root = DAG.getEntryNode();
3122 ConstantMemory = true;
3124 // Do not serialize non-volatile loads against each other.
3125 Root = DAG.getRoot();
3128 SmallVector<SDValue, 4> Values(NumValues);
3129 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3131 EVT PtrVT = Ptr.getValueType();
3132 unsigned ChainI = 0;
3133 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3134 // Serializing loads here may result in excessive register pressure, and
3135 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3136 // could recover a bit by hoisting nodes upward in the chain by recognizing
3137 // they are side-effect free or do not alias. The optimizer should really
3138 // avoid this case by converting large object/array copies to llvm.memcpy
3139 // (MaxParallelChains should always remain as failsafe).
3140 if (ChainI == MaxParallelChains) {
3141 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3142 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3143 MVT::Other, &Chains[0], ChainI);
3147 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3149 DAG.getConstant(Offsets[i], PtrVT));
3150 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
3151 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3152 isNonTemporal, Alignment, TBAAInfo);
3155 Chains[ChainI] = L.getValue(1);
3158 if (!ConstantMemory) {
3159 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3160 MVT::Other, &Chains[0], ChainI);
3164 PendingLoads.push_back(Chain);
3167 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3168 DAG.getVTList(&ValueVTs[0], NumValues),
3169 &Values[0], NumValues));
3172 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3173 const Value *SrcV = I.getOperand(0);
3174 const Value *PtrV = I.getOperand(1);
3176 SmallVector<EVT, 4> ValueVTs;
3177 SmallVector<uint64_t, 4> Offsets;
3178 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3179 unsigned NumValues = ValueVTs.size();
3183 // Get the lowered operands. Note that we do this after
3184 // checking if NumResults is zero, because with zero results
3185 // the operands won't have values in the map.
3186 SDValue Src = getValue(SrcV);
3187 SDValue Ptr = getValue(PtrV);
3189 SDValue Root = getRoot();
3190 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3192 EVT PtrVT = Ptr.getValueType();
3193 bool isVolatile = I.isVolatile();
3194 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3195 unsigned Alignment = I.getAlignment();
3196 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3198 unsigned ChainI = 0;
3199 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3200 // See visitLoad comments.
3201 if (ChainI == MaxParallelChains) {
3202 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3203 MVT::Other, &Chains[0], ChainI);
3207 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3208 DAG.getConstant(Offsets[i], PtrVT));
3209 SDValue St = DAG.getStore(Root, getCurDebugLoc(),
3210 SDValue(Src.getNode(), Src.getResNo() + i),
3211 Add, MachinePointerInfo(PtrV, Offsets[i]),
3212 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3213 Chains[ChainI] = St;
3216 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3217 MVT::Other, &Chains[0], ChainI);
3219 AssignOrderingToNode(StoreNode.getNode());
3220 DAG.setRoot(StoreNode);
3223 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3224 DebugLoc dl = getCurDebugLoc();
3227 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3228 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
3229 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
3232 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3234 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3235 unsigned Intrinsic) {
3236 bool HasChain = !I.doesNotAccessMemory();
3237 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3239 // Build the operand list.
3240 SmallVector<SDValue, 8> Ops;
3241 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3243 // We don't need to serialize loads against other loads.
3244 Ops.push_back(DAG.getRoot());
3246 Ops.push_back(getRoot());
3250 // Info is set by getTgtMemInstrinsic
3251 TargetLowering::IntrinsicInfo Info;
3252 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3254 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3255 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3256 Info.opc == ISD::INTRINSIC_W_CHAIN)
3257 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3259 // Add all operands of the call to the operand list.
3260 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3261 SDValue Op = getValue(I.getArgOperand(i));
3262 assert(TLI.isTypeLegal(Op.getValueType()) &&
3263 "Intrinsic uses a non-legal type?");
3267 SmallVector<EVT, 4> ValueVTs;
3268 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3270 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3271 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3272 "Intrinsic uses a non-legal type?");
3277 ValueVTs.push_back(MVT::Other);
3279 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3283 if (IsTgtIntrinsic) {
3284 // This is target intrinsic that touches memory
3285 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3286 VTs, &Ops[0], Ops.size(),
3288 MachinePointerInfo(Info.ptrVal, Info.offset),
3289 Info.align, Info.vol,
3290 Info.readMem, Info.writeMem);
3291 } else if (!HasChain) {
3292 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3293 VTs, &Ops[0], Ops.size());
3294 } else if (!I.getType()->isVoidTy()) {
3295 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3296 VTs, &Ops[0], Ops.size());
3298 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3299 VTs, &Ops[0], Ops.size());
3303 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3305 PendingLoads.push_back(Chain);
3310 if (!I.getType()->isVoidTy()) {
3311 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3312 EVT VT = TLI.getValueType(PTy);
3313 Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result);
3316 setValue(&I, Result);
3320 /// GetSignificand - Get the significand and build it into a floating-point
3321 /// number with exponent of 1:
3323 /// Op = (Op & 0x007fffff) | 0x3f800000;
3325 /// where Op is the hexidecimal representation of floating point value.
3327 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3328 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3329 DAG.getConstant(0x007fffff, MVT::i32));
3330 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3331 DAG.getConstant(0x3f800000, MVT::i32));
3332 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3335 /// GetExponent - Get the exponent:
3337 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3339 /// where Op is the hexidecimal representation of floating point value.
3341 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3343 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3344 DAG.getConstant(0x7f800000, MVT::i32));
3345 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3346 DAG.getConstant(23, TLI.getPointerTy()));
3347 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3348 DAG.getConstant(127, MVT::i32));
3349 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3352 /// getF32Constant - Get 32-bit floating point constant.
3354 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3355 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3358 /// Inlined utility function to implement binary input atomic intrinsics for
3359 /// visitIntrinsicCall: I is a call instruction
3360 /// Op is the associated NodeType for I
3362 SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I,
3364 SDValue Root = getRoot();
3366 DAG.getAtomic(Op, getCurDebugLoc(),
3367 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
3369 getValue(I.getArgOperand(0)),
3370 getValue(I.getArgOperand(1)),
3371 I.getArgOperand(0));
3373 DAG.setRoot(L.getValue(1));
3377 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3379 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
3380 SDValue Op1 = getValue(I.getArgOperand(0));
3381 SDValue Op2 = getValue(I.getArgOperand(1));
3383 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3384 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
3388 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3389 /// limited-precision mode.
3391 SelectionDAGBuilder::visitExp(const CallInst &I) {
3393 DebugLoc dl = getCurDebugLoc();
3395 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3396 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3397 SDValue Op = getValue(I.getArgOperand(0));
3399 // Put the exponent in the right bit position for later addition to the
3402 // #define LOG2OFe 1.4426950f
3403 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3404 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3405 getF32Constant(DAG, 0x3fb8aa3b));
3406 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3408 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3409 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3410 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3412 // IntegerPartOfX <<= 23;
3413 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3414 DAG.getConstant(23, TLI.getPointerTy()));
3416 if (LimitFloatPrecision <= 6) {
3417 // For floating-point precision of 6:
3419 // TwoToFractionalPartOfX =
3421 // (0.735607626f + 0.252464424f * x) * x;
3423 // error 0.0144103317, which is 6 bits
3424 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3425 getF32Constant(DAG, 0x3e814304));
3426 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3427 getF32Constant(DAG, 0x3f3c50c8));
3428 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3429 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3430 getF32Constant(DAG, 0x3f7f5e7e));
3431 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5);
3433 // Add the exponent into the result in integer domain.
3434 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3435 TwoToFracPartOfX, IntegerPartOfX);
3437 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6);
3438 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3439 // For floating-point precision of 12:
3441 // TwoToFractionalPartOfX =
3444 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3446 // 0.000107046256 error, which is 13 to 14 bits
3447 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3448 getF32Constant(DAG, 0x3da235e3));
3449 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3450 getF32Constant(DAG, 0x3e65b8f3));
3451 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3452 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3453 getF32Constant(DAG, 0x3f324b07));
3454 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3455 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3456 getF32Constant(DAG, 0x3f7ff8fd));
3457 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7);
3459 // Add the exponent into the result in integer domain.
3460 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3461 TwoToFracPartOfX, IntegerPartOfX);
3463 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8);
3464 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3465 // For floating-point precision of 18:
3467 // TwoToFractionalPartOfX =
3471 // (0.554906021e-1f +
3472 // (0.961591928e-2f +
3473 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3475 // error 2.47208000*10^(-7), which is better than 18 bits
3476 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3477 getF32Constant(DAG, 0x3924b03e));
3478 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3479 getF32Constant(DAG, 0x3ab24b87));
3480 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3481 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3482 getF32Constant(DAG, 0x3c1d8c17));
3483 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3484 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3485 getF32Constant(DAG, 0x3d634a1d));
3486 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3487 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3488 getF32Constant(DAG, 0x3e75fe14));
3489 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3490 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3491 getF32Constant(DAG, 0x3f317234));
3492 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3493 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3494 getF32Constant(DAG, 0x3f800000));
3495 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,
3498 // Add the exponent into the result in integer domain.
3499 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3500 TwoToFracPartOfX, IntegerPartOfX);
3502 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14);
3505 // No special expansion.
3506 result = DAG.getNode(ISD::FEXP, dl,
3507 getValue(I.getArgOperand(0)).getValueType(),
3508 getValue(I.getArgOperand(0)));
3511 setValue(&I, result);
3514 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3515 /// limited-precision mode.
3517 SelectionDAGBuilder::visitLog(const CallInst &I) {
3519 DebugLoc dl = getCurDebugLoc();
3521 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3522 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3523 SDValue Op = getValue(I.getArgOperand(0));
3524 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3526 // Scale the exponent by log(2) [0.69314718f].
3527 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3528 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3529 getF32Constant(DAG, 0x3f317218));
3531 // Get the significand and build it into a floating-point number with
3533 SDValue X = GetSignificand(DAG, Op1, dl);
3535 if (LimitFloatPrecision <= 6) {
3536 // For floating-point precision of 6:
3540 // (1.4034025f - 0.23903021f * x) * x;
3542 // error 0.0034276066, which is better than 8 bits
3543 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3544 getF32Constant(DAG, 0xbe74c456));
3545 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3546 getF32Constant(DAG, 0x3fb3a2b1));
3547 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3548 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3549 getF32Constant(DAG, 0x3f949a29));
3551 result = DAG.getNode(ISD::FADD, dl,
3552 MVT::f32, LogOfExponent, LogOfMantissa);
3553 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3554 // For floating-point precision of 12:
3560 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3562 // error 0.000061011436, which is 14 bits
3563 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3564 getF32Constant(DAG, 0xbd67b6d6));
3565 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3566 getF32Constant(DAG, 0x3ee4f4b8));
3567 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3568 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3569 getF32Constant(DAG, 0x3fbc278b));
3570 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3571 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3572 getF32Constant(DAG, 0x40348e95));
3573 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3574 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3575 getF32Constant(DAG, 0x3fdef31a));
3577 result = DAG.getNode(ISD::FADD, dl,
3578 MVT::f32, LogOfExponent, LogOfMantissa);
3579 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3580 // For floating-point precision of 18:
3588 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3590 // error 0.0000023660568, which is better than 18 bits
3591 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3592 getF32Constant(DAG, 0xbc91e5ac));
3593 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3594 getF32Constant(DAG, 0x3e4350aa));
3595 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3596 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3597 getF32Constant(DAG, 0x3f60d3e3));
3598 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3599 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3600 getF32Constant(DAG, 0x4011cdf0));
3601 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3602 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3603 getF32Constant(DAG, 0x406cfd1c));
3604 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3605 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3606 getF32Constant(DAG, 0x408797cb));
3607 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3608 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3609 getF32Constant(DAG, 0x4006dcab));
3611 result = DAG.getNode(ISD::FADD, dl,
3612 MVT::f32, LogOfExponent, LogOfMantissa);
3615 // No special expansion.
3616 result = DAG.getNode(ISD::FLOG, dl,
3617 getValue(I.getArgOperand(0)).getValueType(),
3618 getValue(I.getArgOperand(0)));
3621 setValue(&I, result);
3624 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3625 /// limited-precision mode.
3627 SelectionDAGBuilder::visitLog2(const CallInst &I) {
3629 DebugLoc dl = getCurDebugLoc();
3631 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3632 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3633 SDValue Op = getValue(I.getArgOperand(0));
3634 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3636 // Get the exponent.
3637 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3639 // Get the significand and build it into a floating-point number with
3641 SDValue X = GetSignificand(DAG, Op1, dl);
3643 // Different possible minimax approximations of significand in
3644 // floating-point for various degrees of accuracy over [1,2].
3645 if (LimitFloatPrecision <= 6) {
3646 // For floating-point precision of 6:
3648 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3650 // error 0.0049451742, which is more than 7 bits
3651 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3652 getF32Constant(DAG, 0xbeb08fe0));
3653 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3654 getF32Constant(DAG, 0x40019463));
3655 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3656 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3657 getF32Constant(DAG, 0x3fd6633d));
3659 result = DAG.getNode(ISD::FADD, dl,
3660 MVT::f32, LogOfExponent, Log2ofMantissa);
3661 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3662 // For floating-point precision of 12:
3668 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3670 // error 0.0000876136000, which is better than 13 bits
3671 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3672 getF32Constant(DAG, 0xbda7262e));
3673 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3674 getF32Constant(DAG, 0x3f25280b));
3675 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3676 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3677 getF32Constant(DAG, 0x4007b923));
3678 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3679 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3680 getF32Constant(DAG, 0x40823e2f));
3681 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3682 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3683 getF32Constant(DAG, 0x4020d29c));
3685 result = DAG.getNode(ISD::FADD, dl,
3686 MVT::f32, LogOfExponent, Log2ofMantissa);
3687 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3688 // For floating-point precision of 18:
3697 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3699 // error 0.0000018516, which is better than 18 bits
3700 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3701 getF32Constant(DAG, 0xbcd2769e));
3702 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3703 getF32Constant(DAG, 0x3e8ce0b9));
3704 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3705 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3706 getF32Constant(DAG, 0x3fa22ae7));
3707 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3708 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3709 getF32Constant(DAG, 0x40525723));
3710 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3711 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3712 getF32Constant(DAG, 0x40aaf200));
3713 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3714 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3715 getF32Constant(DAG, 0x40c39dad));
3716 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3717 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3718 getF32Constant(DAG, 0x4042902c));
3720 result = DAG.getNode(ISD::FADD, dl,
3721 MVT::f32, LogOfExponent, Log2ofMantissa);
3724 // No special expansion.
3725 result = DAG.getNode(ISD::FLOG2, dl,
3726 getValue(I.getArgOperand(0)).getValueType(),
3727 getValue(I.getArgOperand(0)));
3730 setValue(&I, result);
3733 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3734 /// limited-precision mode.
3736 SelectionDAGBuilder::visitLog10(const CallInst &I) {
3738 DebugLoc dl = getCurDebugLoc();
3740 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3741 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3742 SDValue Op = getValue(I.getArgOperand(0));
3743 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3745 // Scale the exponent by log10(2) [0.30102999f].
3746 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3747 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3748 getF32Constant(DAG, 0x3e9a209a));
3750 // Get the significand and build it into a floating-point number with
3752 SDValue X = GetSignificand(DAG, Op1, dl);
3754 if (LimitFloatPrecision <= 6) {
3755 // For floating-point precision of 6:
3757 // Log10ofMantissa =
3759 // (0.60948995f - 0.10380950f * x) * x;
3761 // error 0.0014886165, which is 6 bits
3762 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3763 getF32Constant(DAG, 0xbdd49a13));
3764 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3765 getF32Constant(DAG, 0x3f1c0789));
3766 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3767 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3768 getF32Constant(DAG, 0x3f011300));
3770 result = DAG.getNode(ISD::FADD, dl,
3771 MVT::f32, LogOfExponent, Log10ofMantissa);
3772 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3773 // For floating-point precision of 12:
3775 // Log10ofMantissa =
3778 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3780 // error 0.00019228036, which is better than 12 bits
3781 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3782 getF32Constant(DAG, 0x3d431f31));
3783 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3784 getF32Constant(DAG, 0x3ea21fb2));
3785 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3786 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3787 getF32Constant(DAG, 0x3f6ae232));
3788 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3789 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3790 getF32Constant(DAG, 0x3f25f7c3));
3792 result = DAG.getNode(ISD::FADD, dl,
3793 MVT::f32, LogOfExponent, Log10ofMantissa);
3794 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3795 // For floating-point precision of 18:
3797 // Log10ofMantissa =
3802 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3804 // error 0.0000037995730, which is better than 18 bits
3805 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3806 getF32Constant(DAG, 0x3c5d51ce));
3807 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3808 getF32Constant(DAG, 0x3e00685a));
3809 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3810 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3811 getF32Constant(DAG, 0x3efb6798));
3812 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3813 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3814 getF32Constant(DAG, 0x3f88d192));
3815 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3816 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3817 getF32Constant(DAG, 0x3fc4316c));
3818 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3819 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3820 getF32Constant(DAG, 0x3f57ce70));
3822 result = DAG.getNode(ISD::FADD, dl,
3823 MVT::f32, LogOfExponent, Log10ofMantissa);
3826 // No special expansion.
3827 result = DAG.getNode(ISD::FLOG10, dl,
3828 getValue(I.getArgOperand(0)).getValueType(),
3829 getValue(I.getArgOperand(0)));
3832 setValue(&I, result);
3835 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3836 /// limited-precision mode.
3838 SelectionDAGBuilder::visitExp2(const CallInst &I) {
3840 DebugLoc dl = getCurDebugLoc();
3842 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3843 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3844 SDValue Op = getValue(I.getArgOperand(0));
3846 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3848 // FractionalPartOfX = x - (float)IntegerPartOfX;
3849 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3850 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3852 // IntegerPartOfX <<= 23;
3853 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3854 DAG.getConstant(23, TLI.getPointerTy()));
3856 if (LimitFloatPrecision <= 6) {
3857 // For floating-point precision of 6:
3859 // TwoToFractionalPartOfX =
3861 // (0.735607626f + 0.252464424f * x) * x;
3863 // error 0.0144103317, which is 6 bits
3864 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3865 getF32Constant(DAG, 0x3e814304));
3866 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3867 getF32Constant(DAG, 0x3f3c50c8));
3868 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3869 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3870 getF32Constant(DAG, 0x3f7f5e7e));
3871 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
3872 SDValue TwoToFractionalPartOfX =
3873 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3875 result = DAG.getNode(ISD::BITCAST, dl,
3876 MVT::f32, TwoToFractionalPartOfX);
3877 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3878 // For floating-point precision of 12:
3880 // TwoToFractionalPartOfX =
3883 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3885 // error 0.000107046256, which is 13 to 14 bits
3886 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3887 getF32Constant(DAG, 0x3da235e3));
3888 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3889 getF32Constant(DAG, 0x3e65b8f3));
3890 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3891 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3892 getF32Constant(DAG, 0x3f324b07));
3893 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3894 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3895 getF32Constant(DAG, 0x3f7ff8fd));
3896 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
3897 SDValue TwoToFractionalPartOfX =
3898 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3900 result = DAG.getNode(ISD::BITCAST, dl,
3901 MVT::f32, TwoToFractionalPartOfX);
3902 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3903 // For floating-point precision of 18:
3905 // TwoToFractionalPartOfX =
3909 // (0.554906021e-1f +
3910 // (0.961591928e-2f +
3911 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3912 // error 2.47208000*10^(-7), which is better than 18 bits
3913 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3914 getF32Constant(DAG, 0x3924b03e));
3915 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3916 getF32Constant(DAG, 0x3ab24b87));
3917 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3918 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3919 getF32Constant(DAG, 0x3c1d8c17));
3920 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3921 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3922 getF32Constant(DAG, 0x3d634a1d));
3923 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3924 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3925 getF32Constant(DAG, 0x3e75fe14));
3926 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3927 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3928 getF32Constant(DAG, 0x3f317234));
3929 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3930 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3931 getF32Constant(DAG, 0x3f800000));
3932 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
3933 SDValue TwoToFractionalPartOfX =
3934 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3936 result = DAG.getNode(ISD::BITCAST, dl,
3937 MVT::f32, TwoToFractionalPartOfX);
3940 // No special expansion.
3941 result = DAG.getNode(ISD::FEXP2, dl,
3942 getValue(I.getArgOperand(0)).getValueType(),
3943 getValue(I.getArgOperand(0)));
3946 setValue(&I, result);
3949 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3950 /// limited-precision mode with x == 10.0f.
3952 SelectionDAGBuilder::visitPow(const CallInst &I) {
3954 const Value *Val = I.getArgOperand(0);
3955 DebugLoc dl = getCurDebugLoc();
3956 bool IsExp10 = false;
3958 if (getValue(Val).getValueType() == MVT::f32 &&
3959 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
3960 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3961 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3962 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3964 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3969 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3970 SDValue Op = getValue(I.getArgOperand(1));
3972 // Put the exponent in the right bit position for later addition to the
3975 // #define LOG2OF10 3.3219281f
3976 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3977 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3978 getF32Constant(DAG, 0x40549a78));
3979 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3981 // FractionalPartOfX = x - (float)IntegerPartOfX;
3982 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3983 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3985 // IntegerPartOfX <<= 23;
3986 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3987 DAG.getConstant(23, TLI.getPointerTy()));
3989 if (LimitFloatPrecision <= 6) {
3990 // For floating-point precision of 6:
3992 // twoToFractionalPartOfX =
3994 // (0.735607626f + 0.252464424f * x) * x;
3996 // error 0.0144103317, which is 6 bits
3997 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3998 getF32Constant(DAG, 0x3e814304));
3999 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4000 getF32Constant(DAG, 0x3f3c50c8));
4001 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4002 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4003 getF32Constant(DAG, 0x3f7f5e7e));
4004 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
4005 SDValue TwoToFractionalPartOfX =
4006 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
4008 result = DAG.getNode(ISD::BITCAST, dl,
4009 MVT::f32, TwoToFractionalPartOfX);
4010 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
4011 // For floating-point precision of 12:
4013 // TwoToFractionalPartOfX =
4016 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4018 // error 0.000107046256, which is 13 to 14 bits
4019 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4020 getF32Constant(DAG, 0x3da235e3));
4021 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4022 getF32Constant(DAG, 0x3e65b8f3));
4023 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4024 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4025 getF32Constant(DAG, 0x3f324b07));
4026 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4027 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4028 getF32Constant(DAG, 0x3f7ff8fd));
4029 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
4030 SDValue TwoToFractionalPartOfX =
4031 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
4033 result = DAG.getNode(ISD::BITCAST, dl,
4034 MVT::f32, TwoToFractionalPartOfX);
4035 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
4036 // For floating-point precision of 18:
4038 // TwoToFractionalPartOfX =
4042 // (0.554906021e-1f +
4043 // (0.961591928e-2f +
4044 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4045 // error 2.47208000*10^(-7), which is better than 18 bits
4046 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4047 getF32Constant(DAG, 0x3924b03e));
4048 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4049 getF32Constant(DAG, 0x3ab24b87));
4050 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4051 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4052 getF32Constant(DAG, 0x3c1d8c17));
4053 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4054 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4055 getF32Constant(DAG, 0x3d634a1d));
4056 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4057 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4058 getF32Constant(DAG, 0x3e75fe14));
4059 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4060 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4061 getF32Constant(DAG, 0x3f317234));
4062 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4063 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4064 getF32Constant(DAG, 0x3f800000));
4065 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
4066 SDValue TwoToFractionalPartOfX =
4067 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4069 result = DAG.getNode(ISD::BITCAST, dl,
4070 MVT::f32, TwoToFractionalPartOfX);
4073 // No special expansion.
4074 result = DAG.getNode(ISD::FPOW, dl,
4075 getValue(I.getArgOperand(0)).getValueType(),
4076 getValue(I.getArgOperand(0)),
4077 getValue(I.getArgOperand(1)));
4080 setValue(&I, result);
4084 /// ExpandPowI - Expand a llvm.powi intrinsic.
4085 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
4086 SelectionDAG &DAG) {
4087 // If RHS is a constant, we can expand this out to a multiplication tree,
4088 // otherwise we end up lowering to a call to __powidf2 (for example). When
4089 // optimizing for size, we only want to do this if the expansion would produce
4090 // a small number of multiplies, otherwise we do the full expansion.
4091 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4092 // Get the exponent as a positive value.
4093 unsigned Val = RHSC->getSExtValue();
4094 if ((int)Val < 0) Val = -Val;
4096 // powi(x, 0) -> 1.0
4098 return DAG.getConstantFP(1.0, LHS.getValueType());
4100 const Function *F = DAG.getMachineFunction().getFunction();
4101 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
4102 // If optimizing for size, don't insert too many multiplies. This
4103 // inserts up to 5 multiplies.
4104 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4105 // We use the simple binary decomposition method to generate the multiply
4106 // sequence. There are more optimal ways to do this (for example,
4107 // powi(x,15) generates one more multiply than it should), but this has
4108 // the benefit of being both really simple and much better than a libcall.
4109 SDValue Res; // Logically starts equal to 1.0
4110 SDValue CurSquare = LHS;
4114 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4116 Res = CurSquare; // 1.0*CurSquare.
4119 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4120 CurSquare, CurSquare);
4124 // If the original was negative, invert the result, producing 1/(x*x*x).
4125 if (RHSC->getSExtValue() < 0)
4126 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4127 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4132 // Otherwise, expand to a libcall.
4133 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4136 // getTruncatedArgReg - Find underlying register used for an truncated
4138 static unsigned getTruncatedArgReg(const SDValue &N) {
4139 if (N.getOpcode() != ISD::TRUNCATE)
4142 const SDValue &Ext = N.getOperand(0);
4143 if (Ext.getOpcode() == ISD::AssertZext || Ext.getOpcode() == ISD::AssertSext){
4144 const SDValue &CFR = Ext.getOperand(0);
4145 if (CFR.getOpcode() == ISD::CopyFromReg)
4146 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4148 if (CFR.getOpcode() == ISD::TRUNCATE)
4149 return getTruncatedArgReg(CFR);
4154 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4155 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4156 /// At the end of instruction selection, they will be inserted to the entry BB.
4158 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
4161 const Argument *Arg = dyn_cast<Argument>(V);
4165 MachineFunction &MF = DAG.getMachineFunction();
4166 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4167 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4169 // Ignore inlined function arguments here.
4170 DIVariable DV(Variable);
4171 if (DV.isInlinedFnArgument(MF.getFunction()))
4175 if (Arg->hasByValAttr()) {
4176 // Byval arguments' frame index is recorded during argument lowering.
4177 // Use this info directly.
4178 Reg = TRI->getFrameRegister(MF);
4179 Offset = FuncInfo.getByValArgumentFrameIndex(Arg);
4180 // If byval argument ofset is not recorded then ignore this.
4186 if (N.getOpcode() == ISD::CopyFromReg)
4187 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4189 Reg = getTruncatedArgReg(N);
4190 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4191 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4192 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4199 // Check if ValueMap has reg number.
4200 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4201 if (VMI != FuncInfo.ValueMap.end())
4205 if (!Reg && N.getNode()) {
4206 // Check if frame index is available.
4207 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4208 if (FrameIndexSDNode *FINode =
4209 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) {
4210 Reg = TRI->getFrameRegister(MF);
4211 Offset = FINode->getIndex();
4218 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
4219 TII->get(TargetOpcode::DBG_VALUE))
4220 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
4221 FuncInfo.ArgDbgValues.push_back(&*MIB);
4225 // VisualStudio defines setjmp as _setjmp
4226 #if defined(_MSC_VER) && defined(setjmp) && \
4227 !defined(setjmp_undefined_for_msvc)
4228 # pragma push_macro("setjmp")
4230 # define setjmp_undefined_for_msvc
4233 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4234 /// we want to emit this as a call to a named external function, return the name
4235 /// otherwise lower it and return null.
4237 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4238 DebugLoc dl = getCurDebugLoc();
4241 switch (Intrinsic) {
4243 // By default, turn this into a target intrinsic node.
4244 visitTargetIntrinsic(I, Intrinsic);
4246 case Intrinsic::vastart: visitVAStart(I); return 0;
4247 case Intrinsic::vaend: visitVAEnd(I); return 0;
4248 case Intrinsic::vacopy: visitVACopy(I); return 0;
4249 case Intrinsic::returnaddress:
4250 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
4251 getValue(I.getArgOperand(0))));
4253 case Intrinsic::frameaddress:
4254 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
4255 getValue(I.getArgOperand(0))));
4257 case Intrinsic::setjmp:
4258 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
4259 case Intrinsic::longjmp:
4260 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
4261 case Intrinsic::memcpy: {
4262 // Assert for address < 256 since we support only user defined address
4264 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4266 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4268 "Unknown address space");
4269 SDValue Op1 = getValue(I.getArgOperand(0));
4270 SDValue Op2 = getValue(I.getArgOperand(1));
4271 SDValue Op3 = getValue(I.getArgOperand(2));
4272 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4273 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4274 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
4275 MachinePointerInfo(I.getArgOperand(0)),
4276 MachinePointerInfo(I.getArgOperand(1))));
4279 case Intrinsic::memset: {
4280 // Assert for address < 256 since we support only user defined address
4282 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4284 "Unknown address space");
4285 SDValue Op1 = getValue(I.getArgOperand(0));
4286 SDValue Op2 = getValue(I.getArgOperand(1));
4287 SDValue Op3 = getValue(I.getArgOperand(2));
4288 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4289 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4290 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4291 MachinePointerInfo(I.getArgOperand(0))));
4294 case Intrinsic::memmove: {
4295 // Assert for address < 256 since we support only user defined address
4297 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4299 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4301 "Unknown address space");
4302 SDValue Op1 = getValue(I.getArgOperand(0));
4303 SDValue Op2 = getValue(I.getArgOperand(1));
4304 SDValue Op3 = getValue(I.getArgOperand(2));
4305 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4306 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4307 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4308 MachinePointerInfo(I.getArgOperand(0)),
4309 MachinePointerInfo(I.getArgOperand(1))));
4312 case Intrinsic::dbg_declare: {
4313 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4314 MDNode *Variable = DI.getVariable();
4315 const Value *Address = DI.getAddress();
4316 if (!Address || !DIVariable(DI.getVariable()).Verify())
4319 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4320 // but do not always have a corresponding SDNode built. The SDNodeOrder
4321 // absolute, but not relative, values are different depending on whether
4322 // debug info exists.
4325 // Check if address has undef value.
4326 if (isa<UndefValue>(Address) ||
4327 (Address->use_empty() && !isa<Argument>(Address))) {
4328 DEBUG(dbgs() << "Dropping debug info for " << DI);
4332 SDValue &N = NodeMap[Address];
4333 if (!N.getNode() && isa<Argument>(Address))
4334 // Check unused arguments map.
4335 N = UnusedArgNodeMap[Address];
4338 // Parameters are handled specially.
4340 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable;
4341 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4342 Address = BCI->getOperand(0);
4343 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4345 if (isParameter && !AI) {
4346 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4348 // Byval parameter. We have a frame index at this point.
4349 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4350 0, dl, SDNodeOrder);
4352 // Address is an argument, so try to emit its dbg value using
4353 // virtual register info from the FuncInfo.ValueMap.
4354 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
4358 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4359 0, dl, SDNodeOrder);
4361 // Can't do anything with other non-AI cases yet.
4362 DEBUG(dbgs() << "Dropping debug info for " << DI);
4365 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4367 // If Address is an argument then try to emit its dbg value using
4368 // virtual register info from the FuncInfo.ValueMap.
4369 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
4370 // If variable is pinned by a alloca in dominating bb then
4371 // use StaticAllocaMap.
4372 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4373 if (AI->getParent() != DI.getParent()) {
4374 DenseMap<const AllocaInst*, int>::iterator SI =
4375 FuncInfo.StaticAllocaMap.find(AI);
4376 if (SI != FuncInfo.StaticAllocaMap.end()) {
4377 SDV = DAG.getDbgValue(Variable, SI->second,
4378 0, dl, SDNodeOrder);
4379 DAG.AddDbgValue(SDV, 0, false);
4384 DEBUG(dbgs() << "Dropping debug info for " << DI);
4389 case Intrinsic::dbg_value: {
4390 const DbgValueInst &DI = cast<DbgValueInst>(I);
4391 if (!DIVariable(DI.getVariable()).Verify())
4394 MDNode *Variable = DI.getVariable();
4395 uint64_t Offset = DI.getOffset();
4396 const Value *V = DI.getValue();
4400 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4401 // but do not always have a corresponding SDNode built. The SDNodeOrder
4402 // absolute, but not relative, values are different depending on whether
4403 // debug info exists.
4406 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
4407 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4408 DAG.AddDbgValue(SDV, 0, false);
4410 // Do not use getValue() in here; we don't want to generate code at
4411 // this point if it hasn't been done yet.
4412 SDValue N = NodeMap[V];
4413 if (!N.getNode() && isa<Argument>(V))
4414 // Check unused arguments map.
4415 N = UnusedArgNodeMap[V];
4417 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
4418 SDV = DAG.getDbgValue(Variable, N.getNode(),
4419 N.getResNo(), Offset, dl, SDNodeOrder);
4420 DAG.AddDbgValue(SDV, N.getNode(), false);
4422 } else if (!V->use_empty() ) {
4423 // Do not call getValue(V) yet, as we don't want to generate code.
4424 // Remember it for later.
4425 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4426 DanglingDebugInfoMap[V] = DDI;
4428 // We may expand this to cover more cases. One case where we have no
4429 // data available is an unreferenced parameter.
4430 DEBUG(dbgs() << "Dropping debug info for " << DI);
4434 // Build a debug info table entry.
4435 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4436 V = BCI->getOperand(0);
4437 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4438 // Don't handle byval struct arguments or VLAs, for example.
4441 DenseMap<const AllocaInst*, int>::iterator SI =
4442 FuncInfo.StaticAllocaMap.find(AI);
4443 if (SI == FuncInfo.StaticAllocaMap.end())
4445 int FI = SI->second;
4447 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4448 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4449 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4452 case Intrinsic::eh_exception: {
4453 // Insert the EXCEPTIONADDR instruction.
4454 assert(FuncInfo.MBB->isLandingPad() &&
4455 "Call to eh.exception not in landing pad!");
4456 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4458 Ops[0] = DAG.getRoot();
4459 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4461 DAG.setRoot(Op.getValue(1));
4465 case Intrinsic::eh_selector: {
4466 MachineBasicBlock *CallMBB = FuncInfo.MBB;
4467 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4468 if (CallMBB->isLandingPad())
4469 AddCatchInfo(I, &MMI, CallMBB);
4472 FuncInfo.CatchInfoLost.insert(&I);
4474 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4475 unsigned Reg = TLI.getExceptionSelectorRegister();
4476 if (Reg) FuncInfo.MBB->addLiveIn(Reg);
4479 // Insert the EHSELECTION instruction.
4480 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4482 Ops[0] = getValue(I.getArgOperand(0));
4484 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4485 DAG.setRoot(Op.getValue(1));
4486 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
4490 case Intrinsic::eh_typeid_for: {
4491 // Find the type id for the given typeinfo.
4492 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4493 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4494 Res = DAG.getConstant(TypeID, MVT::i32);
4499 case Intrinsic::eh_return_i32:
4500 case Intrinsic::eh_return_i64:
4501 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4502 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4505 getValue(I.getArgOperand(0)),
4506 getValue(I.getArgOperand(1))));
4508 case Intrinsic::eh_unwind_init:
4509 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4511 case Intrinsic::eh_dwarf_cfa: {
4512 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
4513 TLI.getPointerTy());
4514 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4516 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4517 TLI.getPointerTy()),
4519 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4521 DAG.getConstant(0, TLI.getPointerTy()));
4522 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4526 case Intrinsic::eh_sjlj_callsite: {
4527 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4528 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4529 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4530 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4532 MMI.setCurrentCallSite(CI->getZExtValue());
4535 case Intrinsic::eh_sjlj_setjmp: {
4536 setValue(&I, DAG.getNode(ISD::EH_SJLJ_SETJMP, dl, MVT::i32, getRoot(),
4537 getValue(I.getArgOperand(0))));
4540 case Intrinsic::eh_sjlj_longjmp: {
4541 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
4542 getRoot(), getValue(I.getArgOperand(0))));
4545 case Intrinsic::eh_sjlj_dispatch_setup: {
4546 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
4547 getRoot(), getValue(I.getArgOperand(0))));
4551 case Intrinsic::x86_mmx_pslli_w:
4552 case Intrinsic::x86_mmx_pslli_d:
4553 case Intrinsic::x86_mmx_pslli_q:
4554 case Intrinsic::x86_mmx_psrli_w:
4555 case Intrinsic::x86_mmx_psrli_d:
4556 case Intrinsic::x86_mmx_psrli_q:
4557 case Intrinsic::x86_mmx_psrai_w:
4558 case Intrinsic::x86_mmx_psrai_d: {
4559 SDValue ShAmt = getValue(I.getArgOperand(1));
4560 if (isa<ConstantSDNode>(ShAmt)) {
4561 visitTargetIntrinsic(I, Intrinsic);
4564 unsigned NewIntrinsic = 0;
4565 EVT ShAmtVT = MVT::v2i32;
4566 switch (Intrinsic) {
4567 case Intrinsic::x86_mmx_pslli_w:
4568 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4570 case Intrinsic::x86_mmx_pslli_d:
4571 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4573 case Intrinsic::x86_mmx_pslli_q:
4574 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4576 case Intrinsic::x86_mmx_psrli_w:
4577 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4579 case Intrinsic::x86_mmx_psrli_d:
4580 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4582 case Intrinsic::x86_mmx_psrli_q:
4583 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4585 case Intrinsic::x86_mmx_psrai_w:
4586 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4588 case Intrinsic::x86_mmx_psrai_d:
4589 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4591 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4594 // The vector shift intrinsics with scalars uses 32b shift amounts but
4595 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4597 // We must do this early because v2i32 is not a legal type.
4598 DebugLoc dl = getCurDebugLoc();
4601 ShOps[1] = DAG.getConstant(0, MVT::i32);
4602 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
4603 EVT DestVT = TLI.getValueType(I.getType());
4604 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt);
4605 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4606 DAG.getConstant(NewIntrinsic, MVT::i32),
4607 getValue(I.getArgOperand(0)), ShAmt);
4611 case Intrinsic::convertff:
4612 case Intrinsic::convertfsi:
4613 case Intrinsic::convertfui:
4614 case Intrinsic::convertsif:
4615 case Intrinsic::convertuif:
4616 case Intrinsic::convertss:
4617 case Intrinsic::convertsu:
4618 case Intrinsic::convertus:
4619 case Intrinsic::convertuu: {
4620 ISD::CvtCode Code = ISD::CVT_INVALID;
4621 switch (Intrinsic) {
4622 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4623 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4624 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4625 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4626 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4627 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4628 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4629 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4630 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4632 EVT DestVT = TLI.getValueType(I.getType());
4633 const Value *Op1 = I.getArgOperand(0);
4634 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4635 DAG.getValueType(DestVT),
4636 DAG.getValueType(getValue(Op1).getValueType()),
4637 getValue(I.getArgOperand(1)),
4638 getValue(I.getArgOperand(2)),
4643 case Intrinsic::sqrt:
4644 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4645 getValue(I.getArgOperand(0)).getValueType(),
4646 getValue(I.getArgOperand(0))));
4648 case Intrinsic::powi:
4649 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4650 getValue(I.getArgOperand(1)), DAG));
4652 case Intrinsic::sin:
4653 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4654 getValue(I.getArgOperand(0)).getValueType(),
4655 getValue(I.getArgOperand(0))));
4657 case Intrinsic::cos:
4658 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4659 getValue(I.getArgOperand(0)).getValueType(),
4660 getValue(I.getArgOperand(0))));
4662 case Intrinsic::log:
4665 case Intrinsic::log2:
4668 case Intrinsic::log10:
4671 case Intrinsic::exp:
4674 case Intrinsic::exp2:
4677 case Intrinsic::pow:
4680 case Intrinsic::fma:
4681 setValue(&I, DAG.getNode(ISD::FMA, dl,
4682 getValue(I.getArgOperand(0)).getValueType(),
4683 getValue(I.getArgOperand(0)),
4684 getValue(I.getArgOperand(1)),
4685 getValue(I.getArgOperand(2))));
4687 case Intrinsic::convert_to_fp16:
4688 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4689 MVT::i16, getValue(I.getArgOperand(0))));
4691 case Intrinsic::convert_from_fp16:
4692 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4693 MVT::f32, getValue(I.getArgOperand(0))));
4695 case Intrinsic::pcmarker: {
4696 SDValue Tmp = getValue(I.getArgOperand(0));
4697 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4700 case Intrinsic::readcyclecounter: {
4701 SDValue Op = getRoot();
4702 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4703 DAG.getVTList(MVT::i64, MVT::Other),
4706 DAG.setRoot(Res.getValue(1));
4709 case Intrinsic::bswap:
4710 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4711 getValue(I.getArgOperand(0)).getValueType(),
4712 getValue(I.getArgOperand(0))));
4714 case Intrinsic::cttz: {
4715 SDValue Arg = getValue(I.getArgOperand(0));
4716 EVT Ty = Arg.getValueType();
4717 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4720 case Intrinsic::ctlz: {
4721 SDValue Arg = getValue(I.getArgOperand(0));
4722 EVT Ty = Arg.getValueType();
4723 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4726 case Intrinsic::ctpop: {
4727 SDValue Arg = getValue(I.getArgOperand(0));
4728 EVT Ty = Arg.getValueType();
4729 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4732 case Intrinsic::stacksave: {
4733 SDValue Op = getRoot();
4734 Res = DAG.getNode(ISD::STACKSAVE, dl,
4735 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4737 DAG.setRoot(Res.getValue(1));
4740 case Intrinsic::stackrestore: {
4741 Res = getValue(I.getArgOperand(0));
4742 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4745 case Intrinsic::stackprotector: {
4746 // Emit code into the DAG to store the stack guard onto the stack.
4747 MachineFunction &MF = DAG.getMachineFunction();
4748 MachineFrameInfo *MFI = MF.getFrameInfo();
4749 EVT PtrTy = TLI.getPointerTy();
4751 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
4752 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4754 int FI = FuncInfo.StaticAllocaMap[Slot];
4755 MFI->setStackProtectorIndex(FI);
4757 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4759 // Store the stack protector onto the stack.
4760 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4761 MachinePointerInfo::getFixedStack(FI),
4767 case Intrinsic::objectsize: {
4768 // If we don't know by now, we're never going to know.
4769 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
4771 assert(CI && "Non-constant type in __builtin_object_size?");
4773 SDValue Arg = getValue(I.getCalledValue());
4774 EVT Ty = Arg.getValueType();
4777 Res = DAG.getConstant(-1ULL, Ty);
4779 Res = DAG.getConstant(0, Ty);
4784 case Intrinsic::var_annotation:
4785 // Discard annotate attributes
4788 case Intrinsic::init_trampoline: {
4789 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
4793 Ops[1] = getValue(I.getArgOperand(0));
4794 Ops[2] = getValue(I.getArgOperand(1));
4795 Ops[3] = getValue(I.getArgOperand(2));
4796 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
4797 Ops[5] = DAG.getSrcValue(F);
4799 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4800 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4804 DAG.setRoot(Res.getValue(1));
4807 case Intrinsic::gcroot:
4809 const Value *Alloca = I.getArgOperand(0);
4810 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
4812 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4813 GFI->addStackRoot(FI->getIndex(), TypeMap);
4816 case Intrinsic::gcread:
4817 case Intrinsic::gcwrite:
4818 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4820 case Intrinsic::flt_rounds:
4821 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4824 case Intrinsic::expect: {
4825 // Just replace __builtin_expect(exp, c) with EXP.
4826 setValue(&I, getValue(I.getArgOperand(0)));
4830 case Intrinsic::trap: {
4831 StringRef TrapFuncName = getTrapFunctionName();
4832 if (TrapFuncName.empty()) {
4833 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4836 TargetLowering::ArgListTy Args;
4837 std::pair<SDValue, SDValue> Result =
4838 TLI.LowerCallTo(getRoot(), I.getType(),
4839 false, false, false, false, 0, CallingConv::C,
4840 /*isTailCall=*/false, /*isReturnValueUsed=*/true,
4841 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
4842 Args, DAG, getCurDebugLoc());
4843 DAG.setRoot(Result.second);
4846 case Intrinsic::uadd_with_overflow:
4847 return implVisitAluOverflow(I, ISD::UADDO);
4848 case Intrinsic::sadd_with_overflow:
4849 return implVisitAluOverflow(I, ISD::SADDO);
4850 case Intrinsic::usub_with_overflow:
4851 return implVisitAluOverflow(I, ISD::USUBO);
4852 case Intrinsic::ssub_with_overflow:
4853 return implVisitAluOverflow(I, ISD::SSUBO);
4854 case Intrinsic::umul_with_overflow:
4855 return implVisitAluOverflow(I, ISD::UMULO);
4856 case Intrinsic::smul_with_overflow:
4857 return implVisitAluOverflow(I, ISD::SMULO);
4859 case Intrinsic::prefetch: {
4861 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4863 Ops[1] = getValue(I.getArgOperand(0));
4864 Ops[2] = getValue(I.getArgOperand(1));
4865 Ops[3] = getValue(I.getArgOperand(2));
4866 Ops[4] = getValue(I.getArgOperand(3));
4867 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl,
4868 DAG.getVTList(MVT::Other),
4870 EVT::getIntegerVT(*Context, 8),
4871 MachinePointerInfo(I.getArgOperand(0)),
4873 false, /* volatile */
4875 rw==1)); /* write */
4878 case Intrinsic::memory_barrier: {
4881 for (int x = 1; x < 6; ++x)
4882 Ops[x] = getValue(I.getArgOperand(x - 1));
4884 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4887 case Intrinsic::atomic_cmp_swap: {
4888 SDValue Root = getRoot();
4890 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4891 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
4893 getValue(I.getArgOperand(0)),
4894 getValue(I.getArgOperand(1)),
4895 getValue(I.getArgOperand(2)),
4896 MachinePointerInfo(I.getArgOperand(0)));
4898 DAG.setRoot(L.getValue(1));
4901 case Intrinsic::atomic_load_add:
4902 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4903 case Intrinsic::atomic_load_sub:
4904 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4905 case Intrinsic::atomic_load_or:
4906 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4907 case Intrinsic::atomic_load_xor:
4908 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4909 case Intrinsic::atomic_load_and:
4910 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4911 case Intrinsic::atomic_load_nand:
4912 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4913 case Intrinsic::atomic_load_max:
4914 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4915 case Intrinsic::atomic_load_min:
4916 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4917 case Intrinsic::atomic_load_umin:
4918 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4919 case Intrinsic::atomic_load_umax:
4920 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4921 case Intrinsic::atomic_swap:
4922 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4924 case Intrinsic::invariant_start:
4925 case Intrinsic::lifetime_start:
4926 // Discard region information.
4927 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4929 case Intrinsic::invariant_end:
4930 case Intrinsic::lifetime_end:
4931 // Discard region information.
4936 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
4938 MachineBasicBlock *LandingPad) {
4939 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4940 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4941 Type *RetTy = FTy->getReturnType();
4942 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4943 MCSymbol *BeginLabel = 0;
4945 TargetLowering::ArgListTy Args;
4946 TargetLowering::ArgListEntry Entry;
4947 Args.reserve(CS.arg_size());
4949 // Check whether the function can return without sret-demotion.
4950 SmallVector<ISD::OutputArg, 4> Outs;
4951 SmallVector<uint64_t, 4> Offsets;
4952 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4953 Outs, TLI, &Offsets);
4955 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4956 DAG.getMachineFunction(),
4957 FTy->isVarArg(), Outs,
4960 SDValue DemoteStackSlot;
4961 int DemoteStackIdx = -100;
4963 if (!CanLowerReturn) {
4964 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4965 FTy->getReturnType());
4966 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4967 FTy->getReturnType());
4968 MachineFunction &MF = DAG.getMachineFunction();
4969 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4970 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4972 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy());
4973 Entry.Node = DemoteStackSlot;
4974 Entry.Ty = StackSlotPtrType;
4975 Entry.isSExt = false;
4976 Entry.isZExt = false;
4977 Entry.isInReg = false;
4978 Entry.isSRet = true;
4979 Entry.isNest = false;
4980 Entry.isByVal = false;
4981 Entry.Alignment = Align;
4982 Args.push_back(Entry);
4983 RetTy = Type::getVoidTy(FTy->getContext());
4986 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4988 const Value *V = *i;
4991 if (V->getType()->isEmptyTy())
4994 SDValue ArgNode = getValue(V);
4995 Entry.Node = ArgNode; Entry.Ty = V->getType();
4997 unsigned attrInd = i - CS.arg_begin() + 1;
4998 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4999 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
5000 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
5001 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
5002 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
5003 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
5004 Entry.Alignment = CS.getParamAlignment(attrInd);
5005 Args.push_back(Entry);
5009 // Insert a label before the invoke call to mark the try range. This can be
5010 // used to detect deletion of the invoke via the MachineModuleInfo.
5011 BeginLabel = MMI.getContext().CreateTempSymbol();
5013 // For SjLj, keep track of which landing pads go with which invokes
5014 // so as to maintain the ordering of pads in the LSDA.
5015 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5016 if (CallSiteIndex) {
5017 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5018 // Now that the call site is handled, stop tracking it.
5019 MMI.setCurrentCallSite(0);
5022 // Both PendingLoads and PendingExports must be flushed here;
5023 // this call might not return.
5025 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
5028 // Check if target-independent constraints permit a tail call here.
5029 // Target-dependent constraints are checked within TLI.LowerCallTo.
5031 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
5034 // If there's a possibility that fast-isel has already selected some amount
5035 // of the current basic block, don't emit a tail call.
5036 if (isTailCall && EnableFastISel)
5039 std::pair<SDValue,SDValue> Result =
5040 TLI.LowerCallTo(getRoot(), RetTy,
5041 CS.paramHasAttr(0, Attribute::SExt),
5042 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
5043 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
5044 CS.getCallingConv(),
5046 !CS.getInstruction()->use_empty(),
5047 Callee, Args, DAG, getCurDebugLoc());
5048 assert((isTailCall || Result.second.getNode()) &&
5049 "Non-null chain expected with non-tail call!");
5050 assert((Result.second.getNode() || !Result.first.getNode()) &&
5051 "Null value expected with tail call!");
5052 if (Result.first.getNode()) {
5053 setValue(CS.getInstruction(), Result.first);
5054 } else if (!CanLowerReturn && Result.second.getNode()) {
5055 // The instruction result is the result of loading from the
5056 // hidden sret parameter.
5057 SmallVector<EVT, 1> PVTs;
5058 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
5060 ComputeValueVTs(TLI, PtrRetTy, PVTs);
5061 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5062 EVT PtrVT = PVTs[0];
5063 unsigned NumValues = Outs.size();
5064 SmallVector<SDValue, 4> Values(NumValues);
5065 SmallVector<SDValue, 4> Chains(NumValues);
5067 for (unsigned i = 0; i < NumValues; ++i) {
5068 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
5070 DAG.getConstant(Offsets[i], PtrVT));
5071 SDValue L = DAG.getLoad(Outs[i].VT, getCurDebugLoc(), Result.second,
5073 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
5076 Chains[i] = L.getValue(1);
5079 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
5080 MVT::Other, &Chains[0], NumValues);
5081 PendingLoads.push_back(Chain);
5083 // Collect the legal value parts into potentially illegal values
5084 // that correspond to the original function's return values.
5085 SmallVector<EVT, 4> RetTys;
5086 RetTy = FTy->getReturnType();
5087 ComputeValueVTs(TLI, RetTy, RetTys);
5088 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5089 SmallVector<SDValue, 4> ReturnValues;
5090 unsigned CurReg = 0;
5091 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5093 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
5094 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
5096 SDValue ReturnValue =
5097 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
5098 RegisterVT, VT, AssertOp);
5099 ReturnValues.push_back(ReturnValue);
5103 setValue(CS.getInstruction(),
5104 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
5105 DAG.getVTList(&RetTys[0], RetTys.size()),
5106 &ReturnValues[0], ReturnValues.size()));
5109 // Assign order to nodes here. If the call does not produce a result, it won't
5110 // be mapped to a SDNode and visit() will not assign it an order number.
5111 if (!Result.second.getNode()) {
5112 // As a special case, a null chain means that a tail call has been emitted and
5113 // the DAG root is already updated.
5116 AssignOrderingToNode(DAG.getRoot().getNode());
5118 DAG.setRoot(Result.second);
5120 AssignOrderingToNode(Result.second.getNode());
5124 // Insert a label at the end of the invoke call to mark the try range. This
5125 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5126 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5127 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
5129 // Inform MachineModuleInfo of range.
5130 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5134 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5135 /// value is equal or not-equal to zero.
5136 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5137 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
5139 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
5140 if (IC->isEquality())
5141 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5142 if (C->isNullValue())
5144 // Unknown instruction.
5150 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5152 SelectionDAGBuilder &Builder) {
5154 // Check to see if this load can be trivially constant folded, e.g. if the
5155 // input is from a string literal.
5156 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5157 // Cast pointer to the type we really want to load.
5158 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5159 PointerType::getUnqual(LoadTy));
5161 if (const Constant *LoadCst =
5162 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5164 return Builder.getValue(LoadCst);
5167 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5168 // still constant memory, the input chain can be the entry node.
5170 bool ConstantMemory = false;
5172 // Do not serialize (non-volatile) loads of constant memory with anything.
5173 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5174 Root = Builder.DAG.getEntryNode();
5175 ConstantMemory = true;
5177 // Do not serialize non-volatile loads against each other.
5178 Root = Builder.DAG.getRoot();
5181 SDValue Ptr = Builder.getValue(PtrVal);
5182 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
5183 Ptr, MachinePointerInfo(PtrVal),
5185 false /*nontemporal*/, 1 /* align=1 */);
5187 if (!ConstantMemory)
5188 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5193 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5194 /// If so, return true and lower it, otherwise return false and it will be
5195 /// lowered like a normal call.
5196 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5197 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5198 if (I.getNumArgOperands() != 3)
5201 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5202 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5203 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5204 !I.getType()->isIntegerTy())
5207 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
5209 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5210 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5211 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
5212 bool ActuallyDoIt = true;
5215 switch (Size->getZExtValue()) {
5217 LoadVT = MVT::Other;
5219 ActuallyDoIt = false;
5223 LoadTy = Type::getInt16Ty(Size->getContext());
5227 LoadTy = Type::getInt32Ty(Size->getContext());
5231 LoadTy = Type::getInt64Ty(Size->getContext());
5235 LoadVT = MVT::v4i32;
5236 LoadTy = Type::getInt32Ty(Size->getContext());
5237 LoadTy = VectorType::get(LoadTy, 4);
5242 // This turns into unaligned loads. We only do this if the target natively
5243 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5244 // we'll only produce a small number of byte loads.
5246 // Require that we can find a legal MVT, and only do this if the target
5247 // supports unaligned loads of that type. Expanding into byte loads would
5249 if (ActuallyDoIt && Size->getZExtValue() > 4) {
5250 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5251 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5252 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
5253 ActuallyDoIt = false;
5257 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5258 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5260 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
5262 EVT CallVT = TLI.getValueType(I.getType(), true);
5263 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
5273 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5274 // Handle inline assembly differently.
5275 if (isa<InlineAsm>(I.getCalledValue())) {
5280 // See if any floating point values are being passed to this function. This is
5281 // used to emit an undefined reference to fltused on Windows.
5283 cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
5284 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5285 if (FT->isVarArg() &&
5286 !MMI.callsExternalVAFunctionWithFloatingPointArguments()) {
5287 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
5288 Type* T = I.getArgOperand(i)->getType();
5289 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
5291 if (!i->isFloatingPointTy()) continue;
5292 MMI.setCallsExternalVAFunctionWithFloatingPointArguments(true);
5298 const char *RenameFn = 0;
5299 if (Function *F = I.getCalledFunction()) {
5300 if (F->isDeclaration()) {
5301 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5302 if (unsigned IID = II->getIntrinsicID(F)) {
5303 RenameFn = visitIntrinsicCall(I, IID);
5308 if (unsigned IID = F->getIntrinsicID()) {
5309 RenameFn = visitIntrinsicCall(I, IID);
5315 // Check for well-known libc/libm calls. If the function is internal, it
5316 // can't be a library call.
5317 if (!F->hasLocalLinkage() && F->hasName()) {
5318 StringRef Name = F->getName();
5319 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
5320 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5321 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5322 I.getType() == I.getArgOperand(0)->getType() &&
5323 I.getType() == I.getArgOperand(1)->getType()) {
5324 SDValue LHS = getValue(I.getArgOperand(0));
5325 SDValue RHS = getValue(I.getArgOperand(1));
5326 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5327 LHS.getValueType(), LHS, RHS));
5330 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
5331 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5332 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5333 I.getType() == I.getArgOperand(0)->getType()) {
5334 SDValue Tmp = getValue(I.getArgOperand(0));
5335 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
5336 Tmp.getValueType(), Tmp));
5339 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
5340 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5341 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5342 I.getType() == I.getArgOperand(0)->getType() &&
5343 I.onlyReadsMemory()) {
5344 SDValue Tmp = getValue(I.getArgOperand(0));
5345 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
5346 Tmp.getValueType(), Tmp));
5349 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
5350 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5351 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5352 I.getType() == I.getArgOperand(0)->getType() &&
5353 I.onlyReadsMemory()) {
5354 SDValue Tmp = getValue(I.getArgOperand(0));
5355 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
5356 Tmp.getValueType(), Tmp));
5359 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
5360 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5361 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5362 I.getType() == I.getArgOperand(0)->getType() &&
5363 I.onlyReadsMemory()) {
5364 SDValue Tmp = getValue(I.getArgOperand(0));
5365 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
5366 Tmp.getValueType(), Tmp));
5369 } else if (Name == "memcmp") {
5370 if (visitMemCmpCall(I))
5378 Callee = getValue(I.getCalledValue());
5380 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
5382 // Check if we can potentially perform a tail call. More detailed checking is
5383 // be done within LowerCallTo, after more information about the call is known.
5384 LowerCallTo(&I, Callee, I.isTailCall());
5389 /// AsmOperandInfo - This contains information for each constraint that we are
5391 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
5393 /// CallOperand - If this is the result output operand or a clobber
5394 /// this is null, otherwise it is the incoming operand to the CallInst.
5395 /// This gets modified as the asm is processed.
5396 SDValue CallOperand;
5398 /// AssignedRegs - If this is a register or register class operand, this
5399 /// contains the set of register corresponding to the operand.
5400 RegsForValue AssignedRegs;
5402 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
5403 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5406 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
5407 /// busy in OutputRegs/InputRegs.
5408 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
5409 std::set<unsigned> &OutputRegs,
5410 std::set<unsigned> &InputRegs,
5411 const TargetRegisterInfo &TRI) const {
5413 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5414 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
5417 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5418 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5422 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5423 /// corresponds to. If there is no Value* for this operand, it returns
5425 EVT getCallOperandValEVT(LLVMContext &Context,
5426 const TargetLowering &TLI,
5427 const TargetData *TD) const {
5428 if (CallOperandVal == 0) return MVT::Other;
5430 if (isa<BasicBlock>(CallOperandVal))
5431 return TLI.getPointerTy();
5433 llvm::Type *OpTy = CallOperandVal->getType();
5435 // FIXME: code duplicated from TargetLowering::ParseConstraints().
5436 // If this is an indirect operand, the operand is a pointer to the
5439 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5441 report_fatal_error("Indirect operand for inline asm not a pointer!");
5442 OpTy = PtrTy->getElementType();
5445 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5446 if (StructType *STy = dyn_cast<StructType>(OpTy))
5447 if (STy->getNumElements() == 1)
5448 OpTy = STy->getElementType(0);
5450 // If OpTy is not a single value, it may be a struct/union that we
5451 // can tile with integers.
5452 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5453 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5462 OpTy = IntegerType::get(Context, BitSize);
5467 return TLI.getValueType(OpTy, true);
5471 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5473 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5474 const TargetRegisterInfo &TRI) {
5475 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5477 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5478 for (; *Aliases; ++Aliases)
5479 Regs.insert(*Aliases);
5483 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5485 } // end anonymous namespace
5487 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5488 /// specified operand. We prefer to assign virtual registers, to allow the
5489 /// register allocator to handle the assignment process. However, if the asm
5490 /// uses features that we can't model on machineinstrs, we have SDISel do the
5491 /// allocation. This produces generally horrible, but correct, code.
5493 /// OpInfo describes the operand.
5494 /// Input and OutputRegs are the set of already allocated physical registers.
5496 static void GetRegistersForValue(SelectionDAG &DAG,
5497 const TargetLowering &TLI,
5499 SDISelAsmOperandInfo &OpInfo,
5500 std::set<unsigned> &OutputRegs,
5501 std::set<unsigned> &InputRegs) {
5502 LLVMContext &Context = *DAG.getContext();
5504 // Compute whether this value requires an input register, an output register,
5506 bool isOutReg = false;
5507 bool isInReg = false;
5508 switch (OpInfo.Type) {
5509 case InlineAsm::isOutput:
5512 // If there is an input constraint that matches this, we need to reserve
5513 // the input register so no other inputs allocate to it.
5514 isInReg = OpInfo.hasMatchingInput();
5516 case InlineAsm::isInput:
5520 case InlineAsm::isClobber:
5527 MachineFunction &MF = DAG.getMachineFunction();
5528 SmallVector<unsigned, 4> Regs;
5530 // If this is a constraint for a single physreg, or a constraint for a
5531 // register class, find it.
5532 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5533 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5534 OpInfo.ConstraintVT);
5536 unsigned NumRegs = 1;
5537 if (OpInfo.ConstraintVT != MVT::Other) {
5538 // If this is a FP input in an integer register (or visa versa) insert a bit
5539 // cast of the input value. More generally, handle any case where the input
5540 // value disagrees with the register class we plan to stick this in.
5541 if (OpInfo.Type == InlineAsm::isInput &&
5542 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5543 // Try to convert to the first EVT that the reg class contains. If the
5544 // types are identical size, use a bitcast to convert (e.g. two differing
5546 EVT RegVT = *PhysReg.second->vt_begin();
5547 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5548 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5549 RegVT, OpInfo.CallOperand);
5550 OpInfo.ConstraintVT = RegVT;
5551 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5552 // If the input is a FP value and we want it in FP registers, do a
5553 // bitcast to the corresponding integer type. This turns an f64 value
5554 // into i64, which can be passed with two i32 values on a 32-bit
5556 RegVT = EVT::getIntegerVT(Context,
5557 OpInfo.ConstraintVT.getSizeInBits());
5558 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5559 RegVT, OpInfo.CallOperand);
5560 OpInfo.ConstraintVT = RegVT;
5564 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5568 EVT ValueVT = OpInfo.ConstraintVT;
5570 // If this is a constraint for a specific physical register, like {r17},
5572 if (unsigned AssignedReg = PhysReg.first) {
5573 const TargetRegisterClass *RC = PhysReg.second;
5574 if (OpInfo.ConstraintVT == MVT::Other)
5575 ValueVT = *RC->vt_begin();
5577 // Get the actual register value type. This is important, because the user
5578 // may have asked for (e.g.) the AX register in i32 type. We need to
5579 // remember that AX is actually i16 to get the right extension.
5580 RegVT = *RC->vt_begin();
5582 // This is a explicit reference to a physical register.
5583 Regs.push_back(AssignedReg);
5585 // If this is an expanded reference, add the rest of the regs to Regs.
5587 TargetRegisterClass::iterator I = RC->begin();
5588 for (; *I != AssignedReg; ++I)
5589 assert(I != RC->end() && "Didn't find reg!");
5591 // Already added the first reg.
5593 for (; NumRegs; --NumRegs, ++I) {
5594 assert(I != RC->end() && "Ran out of registers to allocate!");
5599 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5600 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5601 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5605 // Otherwise, if this was a reference to an LLVM register class, create vregs
5606 // for this reference.
5607 if (const TargetRegisterClass *RC = PhysReg.second) {
5608 RegVT = *RC->vt_begin();
5609 if (OpInfo.ConstraintVT == MVT::Other)
5612 // Create the appropriate number of virtual registers.
5613 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5614 for (; NumRegs; --NumRegs)
5615 Regs.push_back(RegInfo.createVirtualRegister(RC));
5617 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5621 // Otherwise, we couldn't allocate enough registers for this.
5624 /// visitInlineAsm - Handle a call to an InlineAsm object.
5626 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5627 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5629 /// ConstraintOperands - Information about all of the constraints.
5630 SDISelAsmOperandInfoVector ConstraintOperands;
5632 std::set<unsigned> OutputRegs, InputRegs;
5634 TargetLowering::AsmOperandInfoVector
5635 TargetConstraints = TLI.ParseConstraints(CS);
5637 bool hasMemory = false;
5639 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5640 unsigned ResNo = 0; // ResNo - The result number of the next output.
5641 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5642 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
5643 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5645 EVT OpVT = MVT::Other;
5647 // Compute the value type for each operand.
5648 switch (OpInfo.Type) {
5649 case InlineAsm::isOutput:
5650 // Indirect outputs just consume an argument.
5651 if (OpInfo.isIndirect) {
5652 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5656 // The return value of the call is this value. As such, there is no
5657 // corresponding argument.
5658 assert(!CS.getType()->isVoidTy() &&
5660 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
5661 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5663 assert(ResNo == 0 && "Asm only has one result!");
5664 OpVT = TLI.getValueType(CS.getType());
5668 case InlineAsm::isInput:
5669 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5671 case InlineAsm::isClobber:
5676 // If this is an input or an indirect output, process the call argument.
5677 // BasicBlocks are labels, currently appearing only in asm's.
5678 if (OpInfo.CallOperandVal) {
5679 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5680 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5682 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5685 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5688 OpInfo.ConstraintVT = OpVT;
5690 // Indirect operand accesses access memory.
5691 if (OpInfo.isIndirect)
5694 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
5695 TargetLowering::ConstraintType
5696 CType = TLI.getConstraintType(OpInfo.Codes[j]);
5697 if (CType == TargetLowering::C_Memory) {
5705 SDValue Chain, Flag;
5707 // We won't need to flush pending loads if this asm doesn't touch
5708 // memory and is nonvolatile.
5709 if (hasMemory || IA->hasSideEffects())
5712 Chain = DAG.getRoot();
5714 // Second pass over the constraints: compute which constraint option to use
5715 // and assign registers to constraints that want a specific physreg.
5716 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5717 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5719 // If this is an output operand with a matching input operand, look up the
5720 // matching input. If their types mismatch, e.g. one is an integer, the
5721 // other is floating point, or their sizes are different, flag it as an
5723 if (OpInfo.hasMatchingInput()) {
5724 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5726 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5727 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
5728 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode, OpInfo.ConstraintVT);
5729 std::pair<unsigned, const TargetRegisterClass*> InputRC =
5730 TLI.getRegForInlineAsmConstraint(Input.ConstraintCode, Input.ConstraintVT);
5731 if ((OpInfo.ConstraintVT.isInteger() !=
5732 Input.ConstraintVT.isInteger()) ||
5733 (MatchRC.second != InputRC.second)) {
5734 report_fatal_error("Unsupported asm: input constraint"
5735 " with a matching output constraint of"
5736 " incompatible type!");
5738 Input.ConstraintVT = OpInfo.ConstraintVT;
5742 // Compute the constraint code and ConstraintType to use.
5743 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
5745 // If this is a memory input, and if the operand is not indirect, do what we
5746 // need to to provide an address for the memory input.
5747 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5748 !OpInfo.isIndirect) {
5749 assert((OpInfo.isMultipleAlternative ||
5750 (OpInfo.Type == InlineAsm::isInput)) &&
5751 "Can only indirectify direct input operands!");
5753 // Memory operands really want the address of the value. If we don't have
5754 // an indirect input, put it in the constpool if we can, otherwise spill
5755 // it to a stack slot.
5756 // TODO: This isn't quite right. We need to handle these according to
5757 // the addressing mode that the constraint wants. Also, this may take
5758 // an additional register for the computation and we don't want that
5761 // If the operand is a float, integer, or vector constant, spill to a
5762 // constant pool entry to get its address.
5763 const Value *OpVal = OpInfo.CallOperandVal;
5764 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5765 isa<ConstantVector>(OpVal)) {
5766 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5767 TLI.getPointerTy());
5769 // Otherwise, create a stack slot and emit a store to it before the
5771 Type *Ty = OpVal->getType();
5772 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5773 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5774 MachineFunction &MF = DAG.getMachineFunction();
5775 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5776 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5777 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5778 OpInfo.CallOperand, StackSlot,
5779 MachinePointerInfo::getFixedStack(SSFI),
5781 OpInfo.CallOperand = StackSlot;
5784 // There is no longer a Value* corresponding to this operand.
5785 OpInfo.CallOperandVal = 0;
5787 // It is now an indirect operand.
5788 OpInfo.isIndirect = true;
5791 // If this constraint is for a specific register, allocate it before
5793 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5794 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
5798 // Second pass - Loop over all of the operands, assigning virtual or physregs
5799 // to register class operands.
5800 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5801 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5803 // C_Register operands have already been allocated, Other/Memory don't need
5805 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5806 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
5810 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5811 std::vector<SDValue> AsmNodeOperands;
5812 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5813 AsmNodeOperands.push_back(
5814 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5815 TLI.getPointerTy()));
5817 // If we have a !srcloc metadata node associated with it, we want to attach
5818 // this to the ultimately generated inline asm machineinstr. To do this, we
5819 // pass in the third operand as this (potentially null) inline asm MDNode.
5820 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
5821 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
5823 // Remember the HasSideEffect and AlignStack bits as operand 3.
5824 unsigned ExtraInfo = 0;
5825 if (IA->hasSideEffects())
5826 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
5827 if (IA->isAlignStack())
5828 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
5829 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
5830 TLI.getPointerTy()));
5832 // Loop over all of the inputs, copying the operand values into the
5833 // appropriate registers and processing the output regs.
5834 RegsForValue RetValRegs;
5836 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5837 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5839 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5840 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5842 switch (OpInfo.Type) {
5843 case InlineAsm::isOutput: {
5844 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5845 OpInfo.ConstraintType != TargetLowering::C_Register) {
5846 // Memory output, or 'other' output (e.g. 'X' constraint).
5847 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5849 // Add information to the INLINEASM node to know about this output.
5850 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5851 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
5852 TLI.getPointerTy()));
5853 AsmNodeOperands.push_back(OpInfo.CallOperand);
5857 // Otherwise, this is a register or register class output.
5859 // Copy the output from the appropriate register. Find a register that
5861 if (OpInfo.AssignedRegs.Regs.empty())
5862 report_fatal_error("Couldn't allocate output reg for constraint '" +
5863 Twine(OpInfo.ConstraintCode) + "'!");
5865 // If this is an indirect operand, store through the pointer after the
5867 if (OpInfo.isIndirect) {
5868 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5869 OpInfo.CallOperandVal));
5871 // This is the result value of the call.
5872 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5873 // Concatenate this output onto the outputs list.
5874 RetValRegs.append(OpInfo.AssignedRegs);
5877 // Add information to the INLINEASM node to know that this register is
5879 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5880 InlineAsm::Kind_RegDefEarlyClobber :
5881 InlineAsm::Kind_RegDef,
5888 case InlineAsm::isInput: {
5889 SDValue InOperandVal = OpInfo.CallOperand;
5891 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5892 // If this is required to match an output register we have already set,
5893 // just use its register.
5894 unsigned OperandNo = OpInfo.getMatchedOperand();
5896 // Scan until we find the definition we already emitted of this operand.
5897 // When we find it, create a RegsForValue operand.
5898 unsigned CurOp = InlineAsm::Op_FirstOperand;
5899 for (; OperandNo; --OperandNo) {
5900 // Advance to the next operand.
5902 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5903 assert((InlineAsm::isRegDefKind(OpFlag) ||
5904 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
5905 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
5906 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5910 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5911 if (InlineAsm::isRegDefKind(OpFlag) ||
5912 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
5913 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5914 if (OpInfo.isIndirect) {
5915 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
5916 LLVMContext &Ctx = *DAG.getContext();
5917 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
5918 " don't know how to handle tied "
5919 "indirect register inputs");
5922 RegsForValue MatchedRegs;
5923 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5924 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5925 MatchedRegs.RegVTs.push_back(RegVT);
5926 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5927 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5929 MatchedRegs.Regs.push_back
5930 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5932 // Use the produced MatchedRegs object to
5933 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5935 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
5936 true, OpInfo.getMatchedOperand(),
5937 DAG, AsmNodeOperands);
5941 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
5942 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
5943 "Unexpected number of operands");
5944 // Add information to the INLINEASM node to know about this input.
5945 // See InlineAsm.h isUseOperandTiedToDef.
5946 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
5947 OpInfo.getMatchedOperand());
5948 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5949 TLI.getPointerTy()));
5950 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5954 // Treat indirect 'X' constraint as memory.
5955 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
5957 OpInfo.ConstraintType = TargetLowering::C_Memory;
5959 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5960 std::vector<SDValue> Ops;
5961 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
5964 report_fatal_error("Invalid operand for inline asm constraint '" +
5965 Twine(OpInfo.ConstraintCode) + "'!");
5967 // Add information to the INLINEASM node to know about this input.
5968 unsigned ResOpType =
5969 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
5970 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5971 TLI.getPointerTy()));
5972 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5976 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5977 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5978 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5979 "Memory operands expect pointer values");
5981 // Add information to the INLINEASM node to know about this input.
5982 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5983 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5984 TLI.getPointerTy()));
5985 AsmNodeOperands.push_back(InOperandVal);
5989 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5990 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5991 "Unknown constraint type!");
5992 assert(!OpInfo.isIndirect &&
5993 "Don't know how to handle indirect register inputs yet!");
5995 // Copy the input into the appropriate registers.
5996 if (OpInfo.AssignedRegs.Regs.empty())
5997 report_fatal_error("Couldn't allocate input reg for constraint '" +
5998 Twine(OpInfo.ConstraintCode) + "'!");
6000 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
6003 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6004 DAG, AsmNodeOperands);
6007 case InlineAsm::isClobber: {
6008 // Add the clobbered value to the operand list, so that the register
6009 // allocator is aware that the physreg got clobbered.
6010 if (!OpInfo.AssignedRegs.Regs.empty())
6011 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6019 // Finish up input operands. Set the input chain and add the flag last.
6020 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6021 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6023 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
6024 DAG.getVTList(MVT::Other, MVT::Glue),
6025 &AsmNodeOperands[0], AsmNodeOperands.size());
6026 Flag = Chain.getValue(1);
6028 // If this asm returns a register value, copy the result from that register
6029 // and set it as the value of the call.
6030 if (!RetValRegs.Regs.empty()) {
6031 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
6034 // FIXME: Why don't we do this for inline asms with MRVs?
6035 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6036 EVT ResultType = TLI.getValueType(CS.getType());
6038 // If any of the results of the inline asm is a vector, it may have the
6039 // wrong width/num elts. This can happen for register classes that can
6040 // contain multiple different value types. The preg or vreg allocated may
6041 // not have the same VT as was expected. Convert it to the right type
6042 // with bit_convert.
6043 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6044 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
6047 } else if (ResultType != Val.getValueType() &&
6048 ResultType.isInteger() && Val.getValueType().isInteger()) {
6049 // If a result value was tied to an input value, the computed result may
6050 // have a wider width than the expected result. Extract the relevant
6052 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
6055 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6058 setValue(CS.getInstruction(), Val);
6059 // Don't need to use this as a chain in this case.
6060 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6064 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6066 // Process indirect outputs, first output all of the flagged copies out of
6068 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6069 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6070 const Value *Ptr = IndirectStoresToEmit[i].second;
6071 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
6073 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6076 // Emit the non-flagged stores from the physregs.
6077 SmallVector<SDValue, 8> OutChains;
6078 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6079 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6080 StoresToEmit[i].first,
6081 getValue(StoresToEmit[i].second),
6082 MachinePointerInfo(StoresToEmit[i].second),
6084 OutChains.push_back(Val);
6087 if (!OutChains.empty())
6088 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
6089 &OutChains[0], OutChains.size());
6094 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6095 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6096 MVT::Other, getRoot(),
6097 getValue(I.getArgOperand(0)),
6098 DAG.getSrcValue(I.getArgOperand(0))));
6101 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6102 const TargetData &TD = *TLI.getTargetData();
6103 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6104 getRoot(), getValue(I.getOperand(0)),
6105 DAG.getSrcValue(I.getOperand(0)),
6106 TD.getABITypeAlignment(I.getType()));
6108 DAG.setRoot(V.getValue(1));
6111 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6112 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6113 MVT::Other, getRoot(),
6114 getValue(I.getArgOperand(0)),
6115 DAG.getSrcValue(I.getArgOperand(0))));
6118 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6119 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6120 MVT::Other, getRoot(),
6121 getValue(I.getArgOperand(0)),
6122 getValue(I.getArgOperand(1)),
6123 DAG.getSrcValue(I.getArgOperand(0)),
6124 DAG.getSrcValue(I.getArgOperand(1))));
6127 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6128 /// implementation, which just calls LowerCall.
6129 /// FIXME: When all targets are
6130 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6131 std::pair<SDValue, SDValue>
6132 TargetLowering::LowerCallTo(SDValue Chain, Type *RetTy,
6133 bool RetSExt, bool RetZExt, bool isVarArg,
6134 bool isInreg, unsigned NumFixedArgs,
6135 CallingConv::ID CallConv, bool isTailCall,
6136 bool isReturnValueUsed,
6138 ArgListTy &Args, SelectionDAG &DAG,
6139 DebugLoc dl) const {
6140 // Handle all of the outgoing arguments.
6141 SmallVector<ISD::OutputArg, 32> Outs;
6142 SmallVector<SDValue, 32> OutVals;
6143 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6144 SmallVector<EVT, 4> ValueVTs;
6145 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6146 for (unsigned Value = 0, NumValues = ValueVTs.size();
6147 Value != NumValues; ++Value) {
6148 EVT VT = ValueVTs[Value];
6149 Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
6150 SDValue Op = SDValue(Args[i].Node.getNode(),
6151 Args[i].Node.getResNo() + Value);
6152 ISD::ArgFlagsTy Flags;
6153 unsigned OriginalAlignment =
6154 getTargetData()->getABITypeAlignment(ArgTy);
6160 if (Args[i].isInReg)
6164 if (Args[i].isByVal) {
6166 PointerType *Ty = cast<PointerType>(Args[i].Ty);
6167 Type *ElementTy = Ty->getElementType();
6168 Flags.setByValSize(getTargetData()->getTypeAllocSize(ElementTy));
6169 // For ByVal, alignment should come from FE. BE will guess if this
6170 // info is not there but there are cases it cannot get right.
6171 unsigned FrameAlign;
6172 if (Args[i].Alignment)
6173 FrameAlign = Args[i].Alignment;
6175 FrameAlign = getByValTypeAlignment(ElementTy);
6176 Flags.setByValAlign(FrameAlign);
6180 Flags.setOrigAlign(OriginalAlignment);
6182 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
6183 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
6184 SmallVector<SDValue, 4> Parts(NumParts);
6185 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6188 ExtendKind = ISD::SIGN_EXTEND;
6189 else if (Args[i].isZExt)
6190 ExtendKind = ISD::ZERO_EXTEND;
6192 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
6193 PartVT, ExtendKind);
6195 for (unsigned j = 0; j != NumParts; ++j) {
6196 // if it isn't first piece, alignment must be 1
6197 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(),
6199 if (NumParts > 1 && j == 0)
6200 MyFlags.Flags.setSplit();
6202 MyFlags.Flags.setOrigAlign(1);
6204 Outs.push_back(MyFlags);
6205 OutVals.push_back(Parts[j]);
6210 // Handle the incoming return values from the call.
6211 SmallVector<ISD::InputArg, 32> Ins;
6212 SmallVector<EVT, 4> RetTys;
6213 ComputeValueVTs(*this, RetTy, RetTys);
6214 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6216 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6217 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6218 for (unsigned i = 0; i != NumRegs; ++i) {
6219 ISD::InputArg MyFlags;
6220 MyFlags.VT = RegisterVT.getSimpleVT();
6221 MyFlags.Used = isReturnValueUsed;
6223 MyFlags.Flags.setSExt();
6225 MyFlags.Flags.setZExt();
6227 MyFlags.Flags.setInReg();
6228 Ins.push_back(MyFlags);
6232 SmallVector<SDValue, 4> InVals;
6233 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
6234 Outs, OutVals, Ins, dl, DAG, InVals);
6236 // Verify that the target's LowerCall behaved as expected.
6237 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
6238 "LowerCall didn't return a valid chain!");
6239 assert((!isTailCall || InVals.empty()) &&
6240 "LowerCall emitted a return value for a tail call!");
6241 assert((isTailCall || InVals.size() == Ins.size()) &&
6242 "LowerCall didn't emit the correct number of values!");
6244 // For a tail call, the return value is merely live-out and there aren't
6245 // any nodes in the DAG representing it. Return a special value to
6246 // indicate that a tail call has been emitted and no more Instructions
6247 // should be processed in the current block.
6250 return std::make_pair(SDValue(), SDValue());
6253 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6254 assert(InVals[i].getNode() &&
6255 "LowerCall emitted a null value!");
6256 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6257 "LowerCall emitted a value with the wrong type!");
6260 // Collect the legal value parts into potentially illegal values
6261 // that correspond to the original function's return values.
6262 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6264 AssertOp = ISD::AssertSext;
6266 AssertOp = ISD::AssertZext;
6267 SmallVector<SDValue, 4> ReturnValues;
6268 unsigned CurReg = 0;
6269 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6271 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6272 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6274 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
6275 NumRegs, RegisterVT, VT,
6280 // For a function returning void, there is no return value. We can't create
6281 // such a node, so we just return a null return value in that case. In
6282 // that case, nothing will actually look at the value.
6283 if (ReturnValues.empty())
6284 return std::make_pair(SDValue(), Chain);
6286 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
6287 DAG.getVTList(&RetTys[0], RetTys.size()),
6288 &ReturnValues[0], ReturnValues.size());
6289 return std::make_pair(Res, Chain);
6292 void TargetLowering::LowerOperationWrapper(SDNode *N,
6293 SmallVectorImpl<SDValue> &Results,
6294 SelectionDAG &DAG) const {
6295 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6297 Results.push_back(Res);
6300 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6301 llvm_unreachable("LowerOperation not implemented for this target!");
6306 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
6307 SDValue Op = getNonRegisterValue(V);
6308 assert((Op.getOpcode() != ISD::CopyFromReg ||
6309 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6310 "Copy from a reg to the same reg!");
6311 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6313 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6314 SDValue Chain = DAG.getEntryNode();
6315 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
6316 PendingExports.push_back(Chain);
6319 #include "llvm/CodeGen/SelectionDAGISel.h"
6321 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
6322 /// entry block, return true. This includes arguments used by switches, since
6323 /// the switch may expand into multiple basic blocks.
6324 static bool isOnlyUsedInEntryBlock(const Argument *A) {
6325 // With FastISel active, we may be splitting blocks, so force creation
6326 // of virtual registers for all non-dead arguments.
6328 return A->use_empty();
6330 const BasicBlock *Entry = A->getParent()->begin();
6331 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
6333 const User *U = *UI;
6334 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
6335 return false; // Use not in entry block.
6340 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
6341 // If this is the entry block, emit arguments.
6342 const Function &F = *LLVMBB->getParent();
6343 SelectionDAG &DAG = SDB->DAG;
6344 DebugLoc dl = SDB->getCurDebugLoc();
6345 const TargetData *TD = TLI.getTargetData();
6346 SmallVector<ISD::InputArg, 16> Ins;
6348 // Check whether the function can return without sret-demotion.
6349 SmallVector<ISD::OutputArg, 4> Outs;
6350 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6353 if (!FuncInfo->CanLowerReturn) {
6354 // Put in an sret pointer parameter before all the other parameters.
6355 SmallVector<EVT, 1> ValueVTs;
6356 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6358 // NOTE: Assuming that a pointer will never break down to more than one VT
6360 ISD::ArgFlagsTy Flags;
6362 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
6363 ISD::InputArg RetArg(Flags, RegisterVT, true);
6364 Ins.push_back(RetArg);
6367 // Set up the incoming argument description vector.
6369 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
6370 I != E; ++I, ++Idx) {
6371 SmallVector<EVT, 4> ValueVTs;
6372 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6373 bool isArgValueUsed = !I->use_empty();
6374 for (unsigned Value = 0, NumValues = ValueVTs.size();
6375 Value != NumValues; ++Value) {
6376 EVT VT = ValueVTs[Value];
6377 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6378 ISD::ArgFlagsTy Flags;
6379 unsigned OriginalAlignment =
6380 TD->getABITypeAlignment(ArgTy);
6382 if (F.paramHasAttr(Idx, Attribute::ZExt))
6384 if (F.paramHasAttr(Idx, Attribute::SExt))
6386 if (F.paramHasAttr(Idx, Attribute::InReg))
6388 if (F.paramHasAttr(Idx, Attribute::StructRet))
6390 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6392 PointerType *Ty = cast<PointerType>(I->getType());
6393 Type *ElementTy = Ty->getElementType();
6394 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
6395 // For ByVal, alignment should be passed from FE. BE will guess if
6396 // this info is not there but there are cases it cannot get right.
6397 unsigned FrameAlign;
6398 if (F.getParamAlignment(Idx))
6399 FrameAlign = F.getParamAlignment(Idx);
6401 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
6402 Flags.setByValAlign(FrameAlign);
6404 if (F.paramHasAttr(Idx, Attribute::Nest))
6406 Flags.setOrigAlign(OriginalAlignment);
6408 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6409 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6410 for (unsigned i = 0; i != NumRegs; ++i) {
6411 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6412 if (NumRegs > 1 && i == 0)
6413 MyFlags.Flags.setSplit();
6414 // if it isn't first piece, alignment must be 1
6416 MyFlags.Flags.setOrigAlign(1);
6417 Ins.push_back(MyFlags);
6422 // Call the target to set up the argument values.
6423 SmallVector<SDValue, 8> InVals;
6424 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6428 // Verify that the target's LowerFormalArguments behaved as expected.
6429 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6430 "LowerFormalArguments didn't return a valid chain!");
6431 assert(InVals.size() == Ins.size() &&
6432 "LowerFormalArguments didn't emit the correct number of values!");
6434 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6435 assert(InVals[i].getNode() &&
6436 "LowerFormalArguments emitted a null value!");
6437 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6438 "LowerFormalArguments emitted a value with the wrong type!");
6442 // Update the DAG with the new chain value resulting from argument lowering.
6443 DAG.setRoot(NewRoot);
6445 // Set up the argument values.
6448 if (!FuncInfo->CanLowerReturn) {
6449 // Create a virtual register for the sret pointer, and put in a copy
6450 // from the sret argument into it.
6451 SmallVector<EVT, 1> ValueVTs;
6452 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6453 EVT VT = ValueVTs[0];
6454 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6455 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6456 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
6457 RegVT, VT, AssertOp);
6459 MachineFunction& MF = SDB->DAG.getMachineFunction();
6460 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6461 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6462 FuncInfo->DemoteRegister = SRetReg;
6463 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6465 DAG.setRoot(NewRoot);
6467 // i indexes lowered arguments. Bump it past the hidden sret argument.
6468 // Idx indexes LLVM arguments. Don't touch it.
6472 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6474 SmallVector<SDValue, 4> ArgValues;
6475 SmallVector<EVT, 4> ValueVTs;
6476 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6477 unsigned NumValues = ValueVTs.size();
6479 // If this argument is unused then remember its value. It is used to generate
6480 // debugging information.
6481 if (I->use_empty() && NumValues)
6482 SDB->setUnusedArgValue(I, InVals[i]);
6484 for (unsigned Val = 0; Val != NumValues; ++Val) {
6485 EVT VT = ValueVTs[Val];
6486 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6487 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6489 if (!I->use_empty()) {
6490 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6491 if (F.paramHasAttr(Idx, Attribute::SExt))
6492 AssertOp = ISD::AssertSext;
6493 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6494 AssertOp = ISD::AssertZext;
6496 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
6497 NumParts, PartVT, VT,
6504 // We don't need to do anything else for unused arguments.
6505 if (ArgValues.empty())
6508 // Note down frame index for byval arguments.
6509 if (I->hasByValAttr())
6510 if (FrameIndexSDNode *FI =
6511 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
6512 FuncInfo->setByValArgumentFrameIndex(I, FI->getIndex());
6514 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6515 SDB->getCurDebugLoc());
6516 SDB->setValue(I, Res);
6518 // If this argument is live outside of the entry block, insert a copy from
6519 // wherever we got it to the vreg that other BB's will reference it as.
6520 if (!EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
6521 // If we can, though, try to skip creating an unnecessary vreg.
6522 // FIXME: This isn't very clean... it would be nice to make this more
6523 // general. It's also subtly incompatible with the hacks FastISel
6525 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
6526 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
6527 FuncInfo->ValueMap[I] = Reg;
6531 if (!isOnlyUsedInEntryBlock(I)) {
6532 FuncInfo->InitializeRegForValue(I);
6533 SDB->CopyToExportRegsIfNeeded(I);
6537 assert(i == InVals.size() && "Argument register count mismatch!");
6539 // Finally, if the target has anything special to do, allow it to do so.
6540 // FIXME: this should insert code into the DAG!
6541 EmitFunctionEntryCode();
6544 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6545 /// ensure constants are generated when needed. Remember the virtual registers
6546 /// that need to be added to the Machine PHI nodes as input. We cannot just
6547 /// directly add them, because expansion might result in multiple MBB's for one
6548 /// BB. As such, the start of the BB might correspond to a different MBB than
6552 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
6553 const TerminatorInst *TI = LLVMBB->getTerminator();
6555 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6557 // Check successor nodes' PHI nodes that expect a constant to be available
6559 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6560 const BasicBlock *SuccBB = TI->getSuccessor(succ);
6561 if (!isa<PHINode>(SuccBB->begin())) continue;
6562 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
6564 // If this terminator has multiple identical successors (common for
6565 // switches), only handle each succ once.
6566 if (!SuccsHandled.insert(SuccMBB)) continue;
6568 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6570 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6571 // nodes and Machine PHI nodes, but the incoming operands have not been
6573 for (BasicBlock::const_iterator I = SuccBB->begin();
6574 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
6575 // Ignore dead phi's.
6576 if (PN->use_empty()) continue;
6579 if (PN->getType()->isEmptyTy())
6583 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6585 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
6586 unsigned &RegOut = ConstantsOut[C];
6588 RegOut = FuncInfo.CreateRegs(C->getType());
6589 CopyValueToVirtualRegister(C, RegOut);
6593 DenseMap<const Value *, unsigned>::iterator I =
6594 FuncInfo.ValueMap.find(PHIOp);
6595 if (I != FuncInfo.ValueMap.end())
6598 assert(isa<AllocaInst>(PHIOp) &&
6599 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6600 "Didn't codegen value into a register!??");
6601 Reg = FuncInfo.CreateRegs(PHIOp->getType());
6602 CopyValueToVirtualRegister(PHIOp, Reg);
6606 // Remember that this register needs to added to the machine PHI node as
6607 // the input for this MBB.
6608 SmallVector<EVT, 4> ValueVTs;
6609 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6610 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6611 EVT VT = ValueVTs[vti];
6612 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
6613 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6614 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6615 Reg += NumRegisters;
6619 ConstantsOut.clear();