1 //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuilder.h"
16 #include "SDNodeDbgValue.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GCMetadata.h"
28 #include "llvm/CodeGen/GCStrategy.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/StackMaps.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DebugInfo.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Intrinsics.h"
48 #include "llvm/IR/LLVMContext.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Target/TargetFrameLowering.h"
56 #include "llvm/Target/TargetInstrInfo.h"
57 #include "llvm/Target/TargetIntrinsicInfo.h"
58 #include "llvm/Target/TargetLibraryInfo.h"
59 #include "llvm/Target/TargetLowering.h"
60 #include "llvm/Target/TargetOptions.h"
61 #include "llvm/Target/TargetSelectionDAGInfo.h"
65 /// LimitFloatPrecision - Generate low-precision inline sequences for
66 /// some float libcalls (6, 8 or 12 bits).
67 static unsigned LimitFloatPrecision;
69 static cl::opt<unsigned, true>
70 LimitFPPrecision("limit-float-precision",
71 cl::desc("Generate low-precision inline sequences "
72 "for some float libcalls"),
73 cl::location(LimitFloatPrecision),
76 // Limit the width of DAG chains. This is important in general to prevent
77 // prevent DAG-based analysis from blowing up. For example, alias analysis and
78 // load clustering may not complete in reasonable time. It is difficult to
79 // recognize and avoid this situation within each individual analysis, and
80 // future analyses are likely to have the same behavior. Limiting DAG width is
81 // the safe approach, and will be especially important with global DAGs.
83 // MaxParallelChains default is arbitrarily high to avoid affecting
84 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
85 // sequence over this should have been converted to llvm.memcpy by the
86 // frontend. It easy to induce this behavior with .ll code such as:
87 // %buffer = alloca [4096 x i8]
88 // %data = load [4096 x i8]* %argPtr
89 // store [4096 x i8] %data, [4096 x i8]* %buffer
90 static const unsigned MaxParallelChains = 64;
92 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
93 const SDValue *Parts, unsigned NumParts,
94 MVT PartVT, EVT ValueVT, const Value *V);
96 /// getCopyFromParts - Create a value that contains the specified legal parts
97 /// combined into the value they represent. If the parts combine to a type
98 /// larger then ValueVT then AssertOp can be used to specify whether the extra
99 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
100 /// (ISD::AssertSext).
101 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
102 const SDValue *Parts,
103 unsigned NumParts, MVT PartVT, EVT ValueVT,
105 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
106 if (ValueVT.isVector())
107 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
110 assert(NumParts > 0 && "No parts to assemble!");
111 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
112 SDValue Val = Parts[0];
115 // Assemble the value from multiple parts.
116 if (ValueVT.isInteger()) {
117 unsigned PartBits = PartVT.getSizeInBits();
118 unsigned ValueBits = ValueVT.getSizeInBits();
120 // Assemble the power of 2 part.
121 unsigned RoundParts = NumParts & (NumParts - 1) ?
122 1 << Log2_32(NumParts) : NumParts;
123 unsigned RoundBits = PartBits * RoundParts;
124 EVT RoundVT = RoundBits == ValueBits ?
125 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
128 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
130 if (RoundParts > 2) {
131 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
133 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
134 RoundParts / 2, PartVT, HalfVT, V);
136 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
137 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
140 if (TLI.isBigEndian())
143 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
145 if (RoundParts < NumParts) {
146 // Assemble the trailing non-power-of-2 part.
147 unsigned OddParts = NumParts - RoundParts;
148 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
149 Hi = getCopyFromParts(DAG, DL,
150 Parts + RoundParts, OddParts, PartVT, OddVT, V);
152 // Combine the round and odd parts.
154 if (TLI.isBigEndian())
156 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
157 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
158 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
159 DAG.getConstant(Lo.getValueType().getSizeInBits(),
160 TLI.getPointerTy()));
161 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
162 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
164 } else if (PartVT.isFloatingPoint()) {
165 // FP split into multiple FP parts (for ppcf128)
166 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
169 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
170 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
171 if (TLI.isBigEndian())
173 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
175 // FP split into integer parts (soft fp)
176 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
177 !PartVT.isVector() && "Unexpected split");
178 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
179 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
183 // There is now one part, held in Val. Correct it to match ValueVT.
184 EVT PartEVT = Val.getValueType();
186 if (PartEVT == ValueVT)
189 if (PartEVT.isInteger() && ValueVT.isInteger()) {
190 if (ValueVT.bitsLT(PartEVT)) {
191 // For a truncate, see if we have any information to
192 // indicate whether the truncated bits will always be
193 // zero or sign-extension.
194 if (AssertOp != ISD::DELETED_NODE)
195 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
196 DAG.getValueType(ValueVT));
197 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
199 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
202 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
203 // FP_ROUND's are always exact here.
204 if (ValueVT.bitsLT(Val.getValueType()))
205 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
206 DAG.getTargetConstant(1, TLI.getPointerTy()));
208 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
211 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
212 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
214 llvm_unreachable("Unknown mismatch!");
217 /// getCopyFromPartsVector - Create a value that contains the specified legal
218 /// parts combined into the value they represent. If the parts combine to a
219 /// type larger then ValueVT then AssertOp can be used to specify whether the
220 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
221 /// ValueVT (ISD::AssertSext).
222 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
223 const SDValue *Parts, unsigned NumParts,
224 MVT PartVT, EVT ValueVT, const Value *V) {
225 assert(ValueVT.isVector() && "Not a vector value");
226 assert(NumParts > 0 && "No parts to assemble!");
227 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
228 SDValue Val = Parts[0];
230 // Handle a multi-element vector.
234 unsigned NumIntermediates;
236 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
237 NumIntermediates, RegisterVT);
238 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
239 NumParts = NumRegs; // Silence a compiler warning.
240 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
241 assert(RegisterVT == Parts[0].getSimpleValueType() &&
242 "Part type doesn't match part!");
244 // Assemble the parts into intermediate operands.
245 SmallVector<SDValue, 8> Ops(NumIntermediates);
246 if (NumIntermediates == NumParts) {
247 // If the register was not expanded, truncate or copy the value,
249 for (unsigned i = 0; i != NumParts; ++i)
250 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
251 PartVT, IntermediateVT, V);
252 } else if (NumParts > 0) {
253 // If the intermediate type was expanded, build the intermediate
254 // operands from the parts.
255 assert(NumParts % NumIntermediates == 0 &&
256 "Must expand into a divisible number of parts!");
257 unsigned Factor = NumParts / NumIntermediates;
258 for (unsigned i = 0; i != NumIntermediates; ++i)
259 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
260 PartVT, IntermediateVT, V);
263 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
264 // intermediate operands.
265 Val = DAG.getNode(IntermediateVT.isVector() ?
266 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
267 ValueVT, &Ops[0], NumIntermediates);
270 // There is now one part, held in Val. Correct it to match ValueVT.
271 EVT PartEVT = Val.getValueType();
273 if (PartEVT == ValueVT)
276 if (PartEVT.isVector()) {
277 // If the element type of the source/dest vectors are the same, but the
278 // parts vector has more elements than the value vector, then we have a
279 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
281 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
282 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
283 "Cannot narrow, it would be a lossy transformation");
284 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
285 DAG.getConstant(0, TLI.getVectorIdxTy()));
288 // Vector/Vector bitcast.
289 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
290 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
292 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
293 "Cannot handle this kind of promotion");
294 // Promoted vector extract
295 bool Smaller = ValueVT.bitsLE(PartEVT);
296 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
301 // Trivial bitcast if the types are the same size and the destination
302 // vector type is legal.
303 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
304 TLI.isTypeLegal(ValueVT))
305 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
307 // Handle cases such as i8 -> <1 x i1>
308 if (ValueVT.getVectorNumElements() != 1) {
309 LLVMContext &Ctx = *DAG.getContext();
310 Twine ErrMsg("non-trivial scalar-to-vector conversion");
311 if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) {
312 if (const CallInst *CI = dyn_cast<CallInst>(I))
313 if (isa<InlineAsm>(CI->getCalledValue()))
314 ErrMsg = ErrMsg + ", possible invalid constraint for vector type";
315 Ctx.emitError(I, ErrMsg);
317 Ctx.emitError(ErrMsg);
319 return DAG.getUNDEF(ValueVT);
322 if (ValueVT.getVectorNumElements() == 1 &&
323 ValueVT.getVectorElementType() != PartEVT) {
324 bool Smaller = ValueVT.bitsLE(PartEVT);
325 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
326 DL, ValueVT.getScalarType(), Val);
329 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
332 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
333 SDValue Val, SDValue *Parts, unsigned NumParts,
334 MVT PartVT, const Value *V);
336 /// getCopyToParts - Create a series of nodes that contain the specified value
337 /// split into legal parts. If the parts contain more bits than Val, then, for
338 /// integers, ExtendKind can be used to specify how to generate the extra bits.
339 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
340 SDValue Val, SDValue *Parts, unsigned NumParts,
341 MVT PartVT, const Value *V,
342 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
343 EVT ValueVT = Val.getValueType();
345 // Handle the vector case separately.
346 if (ValueVT.isVector())
347 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
349 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
350 unsigned PartBits = PartVT.getSizeInBits();
351 unsigned OrigNumParts = NumParts;
352 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
357 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
358 EVT PartEVT = PartVT;
359 if (PartEVT == ValueVT) {
360 assert(NumParts == 1 && "No-op copy with multiple parts!");
365 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
366 // If the parts cover more bits than the value has, promote the value.
367 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
368 assert(NumParts == 1 && "Do not know what to promote to!");
369 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
371 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
372 ValueVT.isInteger() &&
373 "Unknown mismatch!");
374 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
375 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
376 if (PartVT == MVT::x86mmx)
377 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
379 } else if (PartBits == ValueVT.getSizeInBits()) {
380 // Different types of the same size.
381 assert(NumParts == 1 && PartEVT != ValueVT);
382 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
383 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
384 // If the parts cover less bits than value has, truncate the value.
385 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
386 ValueVT.isInteger() &&
387 "Unknown mismatch!");
388 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
389 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
390 if (PartVT == MVT::x86mmx)
391 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
394 // The value may have changed - recompute ValueVT.
395 ValueVT = Val.getValueType();
396 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
397 "Failed to tile the value with PartVT!");
400 if (PartEVT != ValueVT) {
401 LLVMContext &Ctx = *DAG.getContext();
402 Twine ErrMsg("scalar-to-vector conversion failed");
403 if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) {
404 if (const CallInst *CI = dyn_cast<CallInst>(I))
405 if (isa<InlineAsm>(CI->getCalledValue()))
406 ErrMsg = ErrMsg + ", possible invalid constraint for vector type";
407 Ctx.emitError(I, ErrMsg);
409 Ctx.emitError(ErrMsg);
417 // Expand the value into multiple parts.
418 if (NumParts & (NumParts - 1)) {
419 // The number of parts is not a power of 2. Split off and copy the tail.
420 assert(PartVT.isInteger() && ValueVT.isInteger() &&
421 "Do not know what to expand to!");
422 unsigned RoundParts = 1 << Log2_32(NumParts);
423 unsigned RoundBits = RoundParts * PartBits;
424 unsigned OddParts = NumParts - RoundParts;
425 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
426 DAG.getIntPtrConstant(RoundBits));
427 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
429 if (TLI.isBigEndian())
430 // The odd parts were reversed by getCopyToParts - unreverse them.
431 std::reverse(Parts + RoundParts, Parts + NumParts);
433 NumParts = RoundParts;
434 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
435 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
438 // The number of parts is a power of 2. Repeatedly bisect the value using
440 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
441 EVT::getIntegerVT(*DAG.getContext(),
442 ValueVT.getSizeInBits()),
445 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
446 for (unsigned i = 0; i < NumParts; i += StepSize) {
447 unsigned ThisBits = StepSize * PartBits / 2;
448 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
449 SDValue &Part0 = Parts[i];
450 SDValue &Part1 = Parts[i+StepSize/2];
452 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
453 ThisVT, Part0, DAG.getIntPtrConstant(1));
454 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
455 ThisVT, Part0, DAG.getIntPtrConstant(0));
457 if (ThisBits == PartBits && ThisVT != PartVT) {
458 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
459 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
464 if (TLI.isBigEndian())
465 std::reverse(Parts, Parts + OrigNumParts);
469 /// getCopyToPartsVector - Create a series of nodes that contain the specified
470 /// value split into legal parts.
471 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
472 SDValue Val, SDValue *Parts, unsigned NumParts,
473 MVT PartVT, const Value *V) {
474 EVT ValueVT = Val.getValueType();
475 assert(ValueVT.isVector() && "Not a vector");
476 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
479 EVT PartEVT = PartVT;
480 if (PartEVT == ValueVT) {
482 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
483 // Bitconvert vector->vector case.
484 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
485 } else if (PartVT.isVector() &&
486 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
487 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
488 EVT ElementVT = PartVT.getVectorElementType();
489 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
491 SmallVector<SDValue, 16> Ops;
492 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
493 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
494 ElementVT, Val, DAG.getConstant(i,
495 TLI.getVectorIdxTy())));
497 for (unsigned i = ValueVT.getVectorNumElements(),
498 e = PartVT.getVectorNumElements(); i != e; ++i)
499 Ops.push_back(DAG.getUNDEF(ElementVT));
501 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
503 // FIXME: Use CONCAT for 2x -> 4x.
505 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
506 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
507 } else if (PartVT.isVector() &&
508 PartEVT.getVectorElementType().bitsGE(
509 ValueVT.getVectorElementType()) &&
510 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
512 // Promoted vector extract
513 bool Smaller = PartEVT.bitsLE(ValueVT);
514 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
517 // Vector -> scalar conversion.
518 assert(ValueVT.getVectorNumElements() == 1 &&
519 "Only trivial vector-to-scalar conversions should get here!");
520 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
521 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
523 bool Smaller = ValueVT.bitsLE(PartVT);
524 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
532 // Handle a multi-element vector.
535 unsigned NumIntermediates;
536 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
538 NumIntermediates, RegisterVT);
539 unsigned NumElements = ValueVT.getVectorNumElements();
541 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
542 NumParts = NumRegs; // Silence a compiler warning.
543 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
545 // Split the vector into intermediate operands.
546 SmallVector<SDValue, 8> Ops(NumIntermediates);
547 for (unsigned i = 0; i != NumIntermediates; ++i) {
548 if (IntermediateVT.isVector())
549 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
551 DAG.getConstant(i * (NumElements / NumIntermediates),
552 TLI.getVectorIdxTy()));
554 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
556 DAG.getConstant(i, TLI.getVectorIdxTy()));
559 // Split the intermediate operands into legal parts.
560 if (NumParts == NumIntermediates) {
561 // If the register was not expanded, promote or copy the value,
563 for (unsigned i = 0; i != NumParts; ++i)
564 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
565 } else if (NumParts > 0) {
566 // If the intermediate type was expanded, split each the value into
568 assert(NumParts % NumIntermediates == 0 &&
569 "Must expand into a divisible number of parts!");
570 unsigned Factor = NumParts / NumIntermediates;
571 for (unsigned i = 0; i != NumIntermediates; ++i)
572 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
577 /// RegsForValue - This struct represents the registers (physical or virtual)
578 /// that a particular set of values is assigned, and the type information
579 /// about the value. The most common situation is to represent one value at a
580 /// time, but struct or array values are handled element-wise as multiple
581 /// values. The splitting of aggregates is performed recursively, so that we
582 /// never have aggregate-typed registers. The values at this point do not
583 /// necessarily have legal types, so each value may require one or more
584 /// registers of some legal type.
586 struct RegsForValue {
587 /// ValueVTs - The value types of the values, which may not be legal, and
588 /// may need be promoted or synthesized from one or more registers.
590 SmallVector<EVT, 4> ValueVTs;
592 /// RegVTs - The value types of the registers. This is the same size as
593 /// ValueVTs and it records, for each value, what the type of the assigned
594 /// register or registers are. (Individual values are never synthesized
595 /// from more than one type of register.)
597 /// With virtual registers, the contents of RegVTs is redundant with TLI's
598 /// getRegisterType member function, however when with physical registers
599 /// it is necessary to have a separate record of the types.
601 SmallVector<MVT, 4> RegVTs;
603 /// Regs - This list holds the registers assigned to the values.
604 /// Each legal or promoted value requires one register, and each
605 /// expanded value requires multiple registers.
607 SmallVector<unsigned, 4> Regs;
611 RegsForValue(const SmallVector<unsigned, 4> ®s,
612 MVT regvt, EVT valuevt)
613 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
615 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
616 unsigned Reg, Type *Ty) {
617 ComputeValueVTs(tli, Ty, ValueVTs);
619 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
620 EVT ValueVT = ValueVTs[Value];
621 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
622 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
623 for (unsigned i = 0; i != NumRegs; ++i)
624 Regs.push_back(Reg + i);
625 RegVTs.push_back(RegisterVT);
630 /// append - Add the specified values to this one.
631 void append(const RegsForValue &RHS) {
632 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
633 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
634 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
637 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
638 /// this value and returns the result as a ValueVTs 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 getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
643 SDValue &Chain, SDValue *Flag,
644 const Value *V = 0) const;
646 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
647 /// specified value into the registers specified by this object. This uses
648 /// Chain/Flag as the input and updates them for the output Chain/Flag.
649 /// If the Flag pointer is NULL, no flag is used.
650 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
651 SDValue &Chain, SDValue *Flag, const Value *V) const;
653 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
654 /// operand list. This adds the code marker, matching input operand index
655 /// (if applicable), and includes the number of values added into it.
656 void AddInlineAsmOperands(unsigned Kind,
657 bool HasMatching, unsigned MatchingIdx,
659 std::vector<SDValue> &Ops) const;
663 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
664 /// this value and returns the result as a ValueVT value. This uses
665 /// Chain/Flag as the input and updates them for the output Chain/Flag.
666 /// If the Flag pointer is NULL, no flag is used.
667 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
668 FunctionLoweringInfo &FuncInfo,
670 SDValue &Chain, SDValue *Flag,
671 const Value *V) const {
672 // A Value with type {} or [0 x %t] needs no registers.
673 if (ValueVTs.empty())
676 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
678 // Assemble the legal parts into the final values.
679 SmallVector<SDValue, 4> Values(ValueVTs.size());
680 SmallVector<SDValue, 8> Parts;
681 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
682 // Copy the legal parts from the registers.
683 EVT ValueVT = ValueVTs[Value];
684 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
685 MVT RegisterVT = RegVTs[Value];
687 Parts.resize(NumRegs);
688 for (unsigned i = 0; i != NumRegs; ++i) {
691 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
693 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
694 *Flag = P.getValue(2);
697 Chain = P.getValue(1);
700 // If the source register was virtual and if we know something about it,
701 // add an assert node.
702 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
703 !RegisterVT.isInteger() || RegisterVT.isVector())
706 const FunctionLoweringInfo::LiveOutInfo *LOI =
707 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
711 unsigned RegSize = RegisterVT.getSizeInBits();
712 unsigned NumSignBits = LOI->NumSignBits;
713 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
715 if (NumZeroBits == RegSize) {
716 // The current value is a zero.
717 // Explicitly express that as it would be easier for
718 // optimizations to kick in.
719 Parts[i] = DAG.getConstant(0, RegisterVT);
723 // FIXME: We capture more information than the dag can represent. For
724 // now, just use the tightest assertzext/assertsext possible.
726 EVT FromVT(MVT::Other);
727 if (NumSignBits == RegSize)
728 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
729 else if (NumZeroBits >= RegSize-1)
730 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
731 else if (NumSignBits > RegSize-8)
732 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
733 else if (NumZeroBits >= RegSize-8)
734 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
735 else if (NumSignBits > RegSize-16)
736 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
737 else if (NumZeroBits >= RegSize-16)
738 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
739 else if (NumSignBits > RegSize-32)
740 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
741 else if (NumZeroBits >= RegSize-32)
742 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
746 // Add an assertion node.
747 assert(FromVT != MVT::Other);
748 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
749 RegisterVT, P, DAG.getValueType(FromVT));
752 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
753 NumRegs, RegisterVT, ValueVT, V);
758 return DAG.getNode(ISD::MERGE_VALUES, dl,
759 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
760 &Values[0], ValueVTs.size());
763 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
764 /// specified value into the registers specified by this object. This uses
765 /// Chain/Flag as the input and updates them for the output Chain/Flag.
766 /// If the Flag pointer is NULL, no flag is used.
767 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
768 SDValue &Chain, SDValue *Flag,
769 const Value *V) const {
770 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
772 // Get the list of the values's legal parts.
773 unsigned NumRegs = Regs.size();
774 SmallVector<SDValue, 8> Parts(NumRegs);
775 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
776 EVT ValueVT = ValueVTs[Value];
777 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
778 MVT RegisterVT = RegVTs[Value];
779 ISD::NodeType ExtendKind =
780 TLI.isZExtFree(Val, RegisterVT)? ISD::ZERO_EXTEND: ISD::ANY_EXTEND;
782 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
783 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
787 // Copy the parts into the registers.
788 SmallVector<SDValue, 8> Chains(NumRegs);
789 for (unsigned i = 0; i != NumRegs; ++i) {
792 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
794 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
795 *Flag = Part.getValue(1);
798 Chains[i] = Part.getValue(0);
801 if (NumRegs == 1 || Flag)
802 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
803 // flagged to it. That is the CopyToReg nodes and the user are considered
804 // a single scheduling unit. If we create a TokenFactor and return it as
805 // chain, then the TokenFactor is both a predecessor (operand) of the
806 // user as well as a successor (the TF operands are flagged to the user).
807 // c1, f1 = CopyToReg
808 // c2, f2 = CopyToReg
809 // c3 = TokenFactor c1, c2
812 Chain = Chains[NumRegs-1];
814 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
817 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
818 /// operand list. This adds the code marker and includes the number of
819 /// values added into it.
820 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
821 unsigned MatchingIdx,
823 std::vector<SDValue> &Ops) const {
824 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
826 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
828 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
829 else if (!Regs.empty() &&
830 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
831 // Put the register class of the virtual registers in the flag word. That
832 // way, later passes can recompute register class constraints for inline
833 // assembly as well as normal instructions.
834 // Don't do this for tied operands that can use the regclass information
836 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
837 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
838 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
841 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
844 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
845 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
846 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
847 MVT RegisterVT = RegVTs[Value];
848 for (unsigned i = 0; i != NumRegs; ++i) {
849 assert(Reg < Regs.size() && "Mismatch in # registers expected");
850 unsigned TheReg = Regs[Reg++];
851 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
853 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
854 // If we clobbered the stack pointer, MFI should know about it.
855 assert(DAG.getMachineFunction().getFrameInfo()->
856 hasInlineAsmWithSPAdjust());
862 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
863 const TargetLibraryInfo *li) {
867 DL = DAG.getTarget().getDataLayout();
868 Context = DAG.getContext();
869 LPadToCallSiteMap.clear();
872 /// clear - Clear out the current SelectionDAG and the associated
873 /// state and prepare this SelectionDAGBuilder object to be used
874 /// for a new block. This doesn't clear out information about
875 /// additional blocks that are needed to complete switch lowering
876 /// or PHI node updating; that information is cleared out as it is
878 void SelectionDAGBuilder::clear() {
880 UnusedArgNodeMap.clear();
881 PendingLoads.clear();
882 PendingExports.clear();
885 SDNodeOrder = LowestSDNodeOrder;
888 /// clearDanglingDebugInfo - Clear the dangling debug information
889 /// map. This function is separated from the clear so that debug
890 /// information that is dangling in a basic block can be properly
891 /// resolved in a different basic block. This allows the
892 /// SelectionDAG to resolve dangling debug information attached
894 void SelectionDAGBuilder::clearDanglingDebugInfo() {
895 DanglingDebugInfoMap.clear();
898 /// getRoot - Return the current virtual root of the Selection DAG,
899 /// flushing any PendingLoad items. This must be done before emitting
900 /// a store or any other node that may need to be ordered after any
901 /// prior load instructions.
903 SDValue SelectionDAGBuilder::getRoot() {
904 if (PendingLoads.empty())
905 return DAG.getRoot();
907 if (PendingLoads.size() == 1) {
908 SDValue Root = PendingLoads[0];
910 PendingLoads.clear();
914 // Otherwise, we have to make a token factor node.
915 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
916 &PendingLoads[0], PendingLoads.size());
917 PendingLoads.clear();
922 /// getControlRoot - Similar to getRoot, but instead of flushing all the
923 /// PendingLoad items, flush all the PendingExports items. It is necessary
924 /// to do this before emitting a terminator instruction.
926 SDValue SelectionDAGBuilder::getControlRoot() {
927 SDValue Root = DAG.getRoot();
929 if (PendingExports.empty())
932 // Turn all of the CopyToReg chains into one factored node.
933 if (Root.getOpcode() != ISD::EntryToken) {
934 unsigned i = 0, e = PendingExports.size();
935 for (; i != e; ++i) {
936 assert(PendingExports[i].getNode()->getNumOperands() > 1);
937 if (PendingExports[i].getNode()->getOperand(0) == Root)
938 break; // Don't add the root if we already indirectly depend on it.
942 PendingExports.push_back(Root);
945 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
947 PendingExports.size());
948 PendingExports.clear();
953 void SelectionDAGBuilder::visit(const Instruction &I) {
954 // Set up outgoing PHI node register values before emitting the terminator.
955 if (isa<TerminatorInst>(&I))
956 HandlePHINodesInSuccessorBlocks(I.getParent());
962 visit(I.getOpcode(), I);
964 if (!isa<TerminatorInst>(&I) && !HasTailCall)
965 CopyToExportRegsIfNeeded(&I);
970 void SelectionDAGBuilder::visitPHI(const PHINode &) {
971 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
974 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
975 // Note: this doesn't use InstVisitor, because it has to work with
976 // ConstantExpr's in addition to instructions.
978 default: llvm_unreachable("Unknown instruction type encountered!");
979 // Build the switch statement using the Instruction.def file.
980 #define HANDLE_INST(NUM, OPCODE, CLASS) \
981 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
982 #include "llvm/IR/Instruction.def"
986 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
987 // generate the debug data structures now that we've seen its definition.
988 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
990 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
992 const DbgValueInst *DI = DDI.getDI();
993 DebugLoc dl = DDI.getdl();
994 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
995 MDNode *Variable = DI->getVariable();
996 uint64_t Offset = DI->getOffset();
999 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
1000 SDV = DAG.getDbgValue(Variable, Val.getNode(),
1001 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
1002 DAG.AddDbgValue(SDV, Val.getNode(), false);
1005 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1006 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1010 /// getValue - Return an SDValue for the given Value.
1011 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1012 // If we already have an SDValue for this value, use it. It's important
1013 // to do this first, so that we don't create a CopyFromReg if we already
1014 // have a regular SDValue.
1015 SDValue &N = NodeMap[V];
1016 if (N.getNode()) return N;
1018 // If there's a virtual register allocated and initialized for this
1020 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1021 if (It != FuncInfo.ValueMap.end()) {
1022 unsigned InReg = It->second;
1023 RegsForValue RFV(*DAG.getContext(), *TM.getTargetLowering(),
1024 InReg, V->getType());
1025 SDValue Chain = DAG.getEntryNode();
1026 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
1027 resolveDanglingDebugInfo(V, N);
1031 // Otherwise create a new SDValue and remember it.
1032 SDValue Val = getValueImpl(V);
1034 resolveDanglingDebugInfo(V, Val);
1038 /// getNonRegisterValue - Return an SDValue for the given Value, but
1039 /// don't look in FuncInfo.ValueMap for a virtual register.
1040 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1041 // If we already have an SDValue for this value, use it.
1042 SDValue &N = NodeMap[V];
1043 if (N.getNode()) return N;
1045 // Otherwise create a new SDValue and remember it.
1046 SDValue Val = getValueImpl(V);
1048 resolveDanglingDebugInfo(V, Val);
1052 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1053 /// Create an SDValue for the given value.
1054 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1055 const TargetLowering *TLI = TM.getTargetLowering();
1057 if (const Constant *C = dyn_cast<Constant>(V)) {
1058 EVT VT = TLI->getValueType(V->getType(), true);
1060 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1061 return DAG.getConstant(*CI, VT);
1063 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1064 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1066 if (isa<ConstantPointerNull>(C)) {
1067 unsigned AS = V->getType()->getPointerAddressSpace();
1068 return DAG.getConstant(0, TLI->getPointerTy(AS));
1071 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1072 return DAG.getConstantFP(*CFP, VT);
1074 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1075 return DAG.getUNDEF(VT);
1077 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1078 visit(CE->getOpcode(), *CE);
1079 SDValue N1 = NodeMap[V];
1080 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1084 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1085 SmallVector<SDValue, 4> Constants;
1086 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1088 SDNode *Val = getValue(*OI).getNode();
1089 // If the operand is an empty aggregate, there are no values.
1091 // Add each leaf value from the operand to the Constants list
1092 // to form a flattened list of all the values.
1093 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1094 Constants.push_back(SDValue(Val, i));
1097 return DAG.getMergeValues(&Constants[0], Constants.size(),
1101 if (const ConstantDataSequential *CDS =
1102 dyn_cast<ConstantDataSequential>(C)) {
1103 SmallVector<SDValue, 4> Ops;
1104 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1105 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1106 // Add each leaf value from the operand to the Constants list
1107 // to form a flattened list of all the values.
1108 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1109 Ops.push_back(SDValue(Val, i));
1112 if (isa<ArrayType>(CDS->getType()))
1113 return DAG.getMergeValues(&Ops[0], Ops.size(), getCurSDLoc());
1114 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1115 VT, &Ops[0], Ops.size());
1118 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1119 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1120 "Unknown struct or array constant!");
1122 SmallVector<EVT, 4> ValueVTs;
1123 ComputeValueVTs(*TLI, C->getType(), ValueVTs);
1124 unsigned NumElts = ValueVTs.size();
1126 return SDValue(); // empty struct
1127 SmallVector<SDValue, 4> Constants(NumElts);
1128 for (unsigned i = 0; i != NumElts; ++i) {
1129 EVT EltVT = ValueVTs[i];
1130 if (isa<UndefValue>(C))
1131 Constants[i] = DAG.getUNDEF(EltVT);
1132 else if (EltVT.isFloatingPoint())
1133 Constants[i] = DAG.getConstantFP(0, EltVT);
1135 Constants[i] = DAG.getConstant(0, EltVT);
1138 return DAG.getMergeValues(&Constants[0], NumElts,
1142 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1143 return DAG.getBlockAddress(BA, VT);
1145 VectorType *VecTy = cast<VectorType>(V->getType());
1146 unsigned NumElements = VecTy->getNumElements();
1148 // Now that we know the number and type of the elements, get that number of
1149 // elements into the Ops array based on what kind of constant it is.
1150 SmallVector<SDValue, 16> Ops;
1151 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1152 for (unsigned i = 0; i != NumElements; ++i)
1153 Ops.push_back(getValue(CV->getOperand(i)));
1155 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1156 EVT EltVT = TLI->getValueType(VecTy->getElementType());
1159 if (EltVT.isFloatingPoint())
1160 Op = DAG.getConstantFP(0, EltVT);
1162 Op = DAG.getConstant(0, EltVT);
1163 Ops.assign(NumElements, Op);
1166 // Create a BUILD_VECTOR node.
1167 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1168 VT, &Ops[0], Ops.size());
1171 // If this is a static alloca, generate it as the frameindex instead of
1173 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1174 DenseMap<const AllocaInst*, int>::iterator SI =
1175 FuncInfo.StaticAllocaMap.find(AI);
1176 if (SI != FuncInfo.StaticAllocaMap.end())
1177 return DAG.getFrameIndex(SI->second, TLI->getPointerTy());
1180 // If this is an instruction which fast-isel has deferred, select it now.
1181 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1182 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1183 RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType());
1184 SDValue Chain = DAG.getEntryNode();
1185 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
1188 llvm_unreachable("Can't get register for value!");
1191 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1192 const TargetLowering *TLI = TM.getTargetLowering();
1193 SDValue Chain = getControlRoot();
1194 SmallVector<ISD::OutputArg, 8> Outs;
1195 SmallVector<SDValue, 8> OutVals;
1197 if (!FuncInfo.CanLowerReturn) {
1198 unsigned DemoteReg = FuncInfo.DemoteRegister;
1199 const Function *F = I.getParent()->getParent();
1201 // Emit a store of the return value through the virtual register.
1202 // Leave Outs empty so that LowerReturn won't try to load return
1203 // registers the usual way.
1204 SmallVector<EVT, 1> PtrValueVTs;
1205 ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()),
1208 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1209 SDValue RetOp = getValue(I.getOperand(0));
1211 SmallVector<EVT, 4> ValueVTs;
1212 SmallVector<uint64_t, 4> Offsets;
1213 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1214 unsigned NumValues = ValueVTs.size();
1216 SmallVector<SDValue, 4> Chains(NumValues);
1217 for (unsigned i = 0; i != NumValues; ++i) {
1218 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1219 RetPtr.getValueType(), RetPtr,
1220 DAG.getIntPtrConstant(Offsets[i]));
1222 DAG.getStore(Chain, getCurSDLoc(),
1223 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1224 // FIXME: better loc info would be nice.
1225 Add, MachinePointerInfo(), false, false, 0);
1228 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1229 MVT::Other, &Chains[0], NumValues);
1230 } else if (I.getNumOperands() != 0) {
1231 SmallVector<EVT, 4> ValueVTs;
1232 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs);
1233 unsigned NumValues = ValueVTs.size();
1235 SDValue RetOp = getValue(I.getOperand(0));
1236 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1237 EVT VT = ValueVTs[j];
1239 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1241 const Function *F = I.getParent()->getParent();
1242 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1244 ExtendKind = ISD::SIGN_EXTEND;
1245 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1247 ExtendKind = ISD::ZERO_EXTEND;
1249 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1250 VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind);
1252 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT);
1253 MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT);
1254 SmallVector<SDValue, 4> Parts(NumParts);
1255 getCopyToParts(DAG, getCurSDLoc(),
1256 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1257 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1259 // 'inreg' on function refers to return value
1260 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1261 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1265 // Propagate extension type if any
1266 if (ExtendKind == ISD::SIGN_EXTEND)
1268 else if (ExtendKind == ISD::ZERO_EXTEND)
1271 for (unsigned i = 0; i < NumParts; ++i) {
1272 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1273 VT, /*isfixed=*/true, 0, 0));
1274 OutVals.push_back(Parts[i]);
1280 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1281 CallingConv::ID CallConv =
1282 DAG.getMachineFunction().getFunction()->getCallingConv();
1283 Chain = TM.getTargetLowering()->LowerReturn(Chain, CallConv, isVarArg,
1284 Outs, OutVals, getCurSDLoc(),
1287 // Verify that the target's LowerReturn behaved as expected.
1288 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1289 "LowerReturn didn't return a valid chain!");
1291 // Update the DAG with the new chain value resulting from return lowering.
1295 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1296 /// created for it, emit nodes to copy the value into the virtual
1298 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1300 if (V->getType()->isEmptyTy())
1303 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1304 if (VMI != FuncInfo.ValueMap.end()) {
1305 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1306 CopyValueToVirtualRegister(V, VMI->second);
1310 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1311 /// the current basic block, add it to ValueMap now so that we'll get a
1313 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1314 // No need to export constants.
1315 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1317 // Already exported?
1318 if (FuncInfo.isExportedInst(V)) return;
1320 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1321 CopyValueToVirtualRegister(V, Reg);
1324 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1325 const BasicBlock *FromBB) {
1326 // The operands of the setcc have to be in this block. We don't know
1327 // how to export them from some other block.
1328 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1329 // Can export from current BB.
1330 if (VI->getParent() == FromBB)
1333 // Is already exported, noop.
1334 return FuncInfo.isExportedInst(V);
1337 // If this is an argument, we can export it if the BB is the entry block or
1338 // if it is already exported.
1339 if (isa<Argument>(V)) {
1340 if (FromBB == &FromBB->getParent()->getEntryBlock())
1343 // Otherwise, can only export this if it is already exported.
1344 return FuncInfo.isExportedInst(V);
1347 // Otherwise, constants can always be exported.
1351 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1352 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1353 const MachineBasicBlock *Dst) const {
1354 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1357 const BasicBlock *SrcBB = Src->getBasicBlock();
1358 const BasicBlock *DstBB = Dst->getBasicBlock();
1359 return BPI->getEdgeWeight(SrcBB, DstBB);
1362 void SelectionDAGBuilder::
1363 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1364 uint32_t Weight /* = 0 */) {
1366 Weight = getEdgeWeight(Src, Dst);
1367 Src->addSuccessor(Dst, Weight);
1371 static bool InBlock(const Value *V, const BasicBlock *BB) {
1372 if (const Instruction *I = dyn_cast<Instruction>(V))
1373 return I->getParent() == BB;
1377 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1378 /// This function emits a branch and is used at the leaves of an OR or an
1379 /// AND operator tree.
1382 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1383 MachineBasicBlock *TBB,
1384 MachineBasicBlock *FBB,
1385 MachineBasicBlock *CurBB,
1386 MachineBasicBlock *SwitchBB,
1389 const BasicBlock *BB = CurBB->getBasicBlock();
1391 // If the leaf of the tree is a comparison, merge the condition into
1393 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1394 // The operands of the cmp have to be in this block. We don't know
1395 // how to export them from some other block. If this is the first block
1396 // of the sequence, no exporting is needed.
1397 if (CurBB == SwitchBB ||
1398 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1399 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1400 ISD::CondCode Condition;
1401 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1402 Condition = getICmpCondCode(IC->getPredicate());
1403 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1404 Condition = getFCmpCondCode(FC->getPredicate());
1405 if (TM.Options.NoNaNsFPMath)
1406 Condition = getFCmpCodeWithoutNaN(Condition);
1408 Condition = ISD::SETEQ; // silence warning.
1409 llvm_unreachable("Unknown compare instruction");
1412 CaseBlock CB(Condition, BOp->getOperand(0),
1413 BOp->getOperand(1), NULL, TBB, FBB, CurBB, TWeight, FWeight);
1414 SwitchCases.push_back(CB);
1419 // Create a CaseBlock record representing this branch.
1420 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1421 NULL, TBB, FBB, CurBB, TWeight, FWeight);
1422 SwitchCases.push_back(CB);
1425 /// Scale down both weights to fit into uint32_t.
1426 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1427 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1428 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1429 NewTrue = NewTrue / Scale;
1430 NewFalse = NewFalse / Scale;
1433 /// FindMergedConditions - If Cond is an expression like
1434 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1435 MachineBasicBlock *TBB,
1436 MachineBasicBlock *FBB,
1437 MachineBasicBlock *CurBB,
1438 MachineBasicBlock *SwitchBB,
1439 unsigned Opc, uint32_t TWeight,
1441 // If this node is not part of the or/and tree, emit it as a branch.
1442 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1443 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1444 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1445 BOp->getParent() != CurBB->getBasicBlock() ||
1446 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1447 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1448 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1453 // Create TmpBB after CurBB.
1454 MachineFunction::iterator BBI = CurBB;
1455 MachineFunction &MF = DAG.getMachineFunction();
1456 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1457 CurBB->getParent()->insert(++BBI, TmpBB);
1459 if (Opc == Instruction::Or) {
1460 // Codegen X | Y as:
1469 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1470 // The requirement is that
1471 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1472 // = TrueProb for orignal BB.
1473 // Assuming the orignal weights are A and B, one choice is to set BB1's
1474 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1476 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1477 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1478 // TmpBB, but the math is more complicated.
1480 uint64_t NewTrueWeight = TWeight;
1481 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1482 ScaleWeights(NewTrueWeight, NewFalseWeight);
1483 // Emit the LHS condition.
1484 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1485 NewTrueWeight, NewFalseWeight);
1487 NewTrueWeight = TWeight;
1488 NewFalseWeight = 2 * (uint64_t)FWeight;
1489 ScaleWeights(NewTrueWeight, NewFalseWeight);
1490 // Emit the RHS condition into TmpBB.
1491 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1492 NewTrueWeight, NewFalseWeight);
1494 assert(Opc == Instruction::And && "Unknown merge op!");
1495 // Codegen X & Y as:
1503 // This requires creation of TmpBB after CurBB.
1505 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1506 // The requirement is that
1507 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1508 // = FalseProb for orignal BB.
1509 // Assuming the orignal weights are A and B, one choice is to set BB1's
1510 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1512 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1514 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1515 uint64_t NewFalseWeight = FWeight;
1516 ScaleWeights(NewTrueWeight, NewFalseWeight);
1517 // Emit the LHS condition.
1518 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1519 NewTrueWeight, NewFalseWeight);
1521 NewTrueWeight = 2 * (uint64_t)TWeight;
1522 NewFalseWeight = FWeight;
1523 ScaleWeights(NewTrueWeight, NewFalseWeight);
1524 // Emit the RHS condition into TmpBB.
1525 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1526 NewTrueWeight, NewFalseWeight);
1530 /// If the set of cases should be emitted as a series of branches, return true.
1531 /// If we should emit this as a bunch of and/or'd together conditions, return
1534 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1535 if (Cases.size() != 2) return true;
1537 // If this is two comparisons of the same values or'd or and'd together, they
1538 // will get folded into a single comparison, so don't emit two blocks.
1539 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1540 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1541 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1542 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1546 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1547 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1548 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1549 Cases[0].CC == Cases[1].CC &&
1550 isa<Constant>(Cases[0].CmpRHS) &&
1551 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1552 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1554 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1561 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1562 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1564 // Update machine-CFG edges.
1565 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1567 // Figure out which block is immediately after the current one.
1568 MachineBasicBlock *NextBlock = 0;
1569 MachineFunction::iterator BBI = BrMBB;
1570 if (++BBI != FuncInfo.MF->end())
1573 if (I.isUnconditional()) {
1574 // Update machine-CFG edges.
1575 BrMBB->addSuccessor(Succ0MBB);
1577 // If this is not a fall-through branch, emit the branch.
1578 if (Succ0MBB != NextBlock)
1579 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1580 MVT::Other, getControlRoot(),
1581 DAG.getBasicBlock(Succ0MBB)));
1586 // If this condition is one of the special cases we handle, do special stuff
1588 const Value *CondVal = I.getCondition();
1589 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1591 // If this is a series of conditions that are or'd or and'd together, emit
1592 // this as a sequence of branches instead of setcc's with and/or operations.
1593 // As long as jumps are not expensive, this should improve performance.
1594 // For example, instead of something like:
1607 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1608 if (!TM.getTargetLowering()->isJumpExpensive() &&
1610 (BOp->getOpcode() == Instruction::And ||
1611 BOp->getOpcode() == Instruction::Or)) {
1612 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1613 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1614 getEdgeWeight(BrMBB, Succ1MBB));
1615 // If the compares in later blocks need to use values not currently
1616 // exported from this block, export them now. This block should always
1617 // be the first entry.
1618 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1620 // Allow some cases to be rejected.
1621 if (ShouldEmitAsBranches(SwitchCases)) {
1622 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1623 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1624 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1627 // Emit the branch for this block.
1628 visitSwitchCase(SwitchCases[0], BrMBB);
1629 SwitchCases.erase(SwitchCases.begin());
1633 // Okay, we decided not to do this, remove any inserted MBB's and clear
1635 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1636 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1638 SwitchCases.clear();
1642 // Create a CaseBlock record representing this branch.
1643 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1644 NULL, Succ0MBB, Succ1MBB, BrMBB);
1646 // Use visitSwitchCase to actually insert the fast branch sequence for this
1648 visitSwitchCase(CB, BrMBB);
1651 /// visitSwitchCase - Emits the necessary code to represent a single node in
1652 /// the binary search tree resulting from lowering a switch instruction.
1653 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1654 MachineBasicBlock *SwitchBB) {
1656 SDValue CondLHS = getValue(CB.CmpLHS);
1657 SDLoc dl = getCurSDLoc();
1659 // Build the setcc now.
1660 if (CB.CmpMHS == NULL) {
1661 // Fold "(X == true)" to X and "(X == false)" to !X to
1662 // handle common cases produced by branch lowering.
1663 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1664 CB.CC == ISD::SETEQ)
1666 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1667 CB.CC == ISD::SETEQ) {
1668 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1669 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1671 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1673 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1675 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1676 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1678 SDValue CmpOp = getValue(CB.CmpMHS);
1679 EVT VT = CmpOp.getValueType();
1681 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1682 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1685 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1686 VT, CmpOp, DAG.getConstant(Low, VT));
1687 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1688 DAG.getConstant(High-Low, VT), ISD::SETULE);
1692 // Update successor info
1693 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1694 // TrueBB and FalseBB are always different unless the incoming IR is
1695 // degenerate. This only happens when running llc on weird IR.
1696 if (CB.TrueBB != CB.FalseBB)
1697 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1699 // Set NextBlock to be the MBB immediately after the current one, if any.
1700 // This is used to avoid emitting unnecessary branches to the next block.
1701 MachineBasicBlock *NextBlock = 0;
1702 MachineFunction::iterator BBI = SwitchBB;
1703 if (++BBI != FuncInfo.MF->end())
1706 // If the lhs block is the next block, invert the condition so that we can
1707 // fall through to the lhs instead of the rhs block.
1708 if (CB.TrueBB == NextBlock) {
1709 std::swap(CB.TrueBB, CB.FalseBB);
1710 SDValue True = DAG.getConstant(1, Cond.getValueType());
1711 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1714 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1715 MVT::Other, getControlRoot(), Cond,
1716 DAG.getBasicBlock(CB.TrueBB));
1718 // Insert the false branch. Do this even if it's a fall through branch,
1719 // this makes it easier to do DAG optimizations which require inverting
1720 // the branch condition.
1721 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1722 DAG.getBasicBlock(CB.FalseBB));
1724 DAG.setRoot(BrCond);
1727 /// visitJumpTable - Emit JumpTable node in the current MBB
1728 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1729 // Emit the code for the jump table
1730 assert(JT.Reg != -1U && "Should lower JT Header first!");
1731 EVT PTy = TM.getTargetLowering()->getPointerTy();
1732 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1734 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1735 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1736 MVT::Other, Index.getValue(1),
1738 DAG.setRoot(BrJumpTable);
1741 /// visitJumpTableHeader - This function emits necessary code to produce index
1742 /// in the JumpTable from switch case.
1743 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1744 JumpTableHeader &JTH,
1745 MachineBasicBlock *SwitchBB) {
1746 // Subtract the lowest switch case value from the value being switched on and
1747 // conditional branch to default mbb if the result is greater than the
1748 // difference between smallest and largest cases.
1749 SDValue SwitchOp = getValue(JTH.SValue);
1750 EVT VT = SwitchOp.getValueType();
1751 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1752 DAG.getConstant(JTH.First, VT));
1754 // The SDNode we just created, which holds the value being switched on minus
1755 // the smallest case value, needs to be copied to a virtual register so it
1756 // can be used as an index into the jump table in a subsequent basic block.
1757 // This value may be smaller or larger than the target's pointer type, and
1758 // therefore require extension or truncating.
1759 const TargetLowering *TLI = TM.getTargetLowering();
1760 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy());
1762 unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy());
1763 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1764 JumpTableReg, SwitchOp);
1765 JT.Reg = JumpTableReg;
1767 // Emit the range check for the jump table, and branch to the default block
1768 // for the switch statement if the value being switched on exceeds the largest
1769 // case in the switch.
1770 SDValue CMP = DAG.getSetCC(getCurSDLoc(),
1771 TLI->getSetCCResultType(*DAG.getContext(),
1772 Sub.getValueType()),
1774 DAG.getConstant(JTH.Last - JTH.First,VT),
1777 // Set NextBlock to be the MBB immediately after the current one, if any.
1778 // This is used to avoid emitting unnecessary branches to the next block.
1779 MachineBasicBlock *NextBlock = 0;
1780 MachineFunction::iterator BBI = SwitchBB;
1782 if (++BBI != FuncInfo.MF->end())
1785 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1786 MVT::Other, CopyTo, CMP,
1787 DAG.getBasicBlock(JT.Default));
1789 if (JT.MBB != NextBlock)
1790 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1791 DAG.getBasicBlock(JT.MBB));
1793 DAG.setRoot(BrCond);
1796 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1797 /// tail spliced into a stack protector check success bb.
1799 /// For a high level explanation of how this fits into the stack protector
1800 /// generation see the comment on the declaration of class
1801 /// StackProtectorDescriptor.
1802 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1803 MachineBasicBlock *ParentBB) {
1805 // First create the loads to the guard/stack slot for the comparison.
1806 const TargetLowering *TLI = TM.getTargetLowering();
1807 EVT PtrTy = TLI->getPointerTy();
1809 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1810 int FI = MFI->getStackProtectorIndex();
1812 const Value *IRGuard = SPD.getGuard();
1813 SDValue GuardPtr = getValue(IRGuard);
1814 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1817 TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1818 SDValue Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1819 GuardPtr, MachinePointerInfo(IRGuard, 0),
1820 true, false, false, Align);
1822 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1824 MachinePointerInfo::getFixedStack(FI),
1825 true, false, false, Align);
1827 // Perform the comparison via a subtract/getsetcc.
1828 EVT VT = Guard.getValueType();
1829 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1831 SDValue Cmp = DAG.getSetCC(getCurSDLoc(),
1832 TLI->getSetCCResultType(*DAG.getContext(),
1833 Sub.getValueType()),
1834 Sub, DAG.getConstant(0, VT),
1837 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1838 // branch to failure MBB.
1839 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1840 MVT::Other, StackSlot.getOperand(0),
1841 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1842 // Otherwise branch to success MBB.
1843 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1845 DAG.getBasicBlock(SPD.getSuccessMBB()));
1850 /// Codegen the failure basic block for a stack protector check.
1852 /// A failure stack protector machine basic block consists simply of a call to
1853 /// __stack_chk_fail().
1855 /// For a high level explanation of how this fits into the stack protector
1856 /// generation see the comment on the declaration of class
1857 /// StackProtectorDescriptor.
1859 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1860 const TargetLowering *TLI = TM.getTargetLowering();
1861 SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
1862 MVT::isVoid, 0, 0, false, getCurSDLoc(),
1863 false, false).second;
1867 /// visitBitTestHeader - This function emits necessary code to produce value
1868 /// suitable for "bit tests"
1869 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1870 MachineBasicBlock *SwitchBB) {
1871 // Subtract the minimum value
1872 SDValue SwitchOp = getValue(B.SValue);
1873 EVT VT = SwitchOp.getValueType();
1874 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1875 DAG.getConstant(B.First, VT));
1878 const TargetLowering *TLI = TM.getTargetLowering();
1879 SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(),
1880 TLI->getSetCCResultType(*DAG.getContext(),
1881 Sub.getValueType()),
1882 Sub, DAG.getConstant(B.Range, VT),
1885 // Determine the type of the test operands.
1886 bool UsePtrType = false;
1887 if (!TLI->isTypeLegal(VT))
1890 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1891 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1892 // Switch table case range are encoded into series of masks.
1893 // Just use pointer type, it's guaranteed to fit.
1899 VT = TLI->getPointerTy();
1900 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1903 B.RegVT = VT.getSimpleVT();
1904 B.Reg = FuncInfo.CreateReg(B.RegVT);
1905 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1908 // Set NextBlock to be the MBB immediately after the current one, if any.
1909 // This is used to avoid emitting unnecessary branches to the next block.
1910 MachineBasicBlock *NextBlock = 0;
1911 MachineFunction::iterator BBI = SwitchBB;
1912 if (++BBI != FuncInfo.MF->end())
1915 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1917 addSuccessorWithWeight(SwitchBB, B.Default);
1918 addSuccessorWithWeight(SwitchBB, MBB);
1920 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1921 MVT::Other, CopyTo, RangeCmp,
1922 DAG.getBasicBlock(B.Default));
1924 if (MBB != NextBlock)
1925 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1926 DAG.getBasicBlock(MBB));
1928 DAG.setRoot(BrRange);
1931 /// visitBitTestCase - this function produces one "bit test"
1932 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1933 MachineBasicBlock* NextMBB,
1934 uint32_t BranchWeightToNext,
1937 MachineBasicBlock *SwitchBB) {
1939 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1942 unsigned PopCount = CountPopulation_64(B.Mask);
1943 const TargetLowering *TLI = TM.getTargetLowering();
1944 if (PopCount == 1) {
1945 // Testing for a single bit; just compare the shift count with what it
1946 // would need to be to shift a 1 bit in that position.
1947 Cmp = DAG.getSetCC(getCurSDLoc(),
1948 TLI->getSetCCResultType(*DAG.getContext(), VT),
1950 DAG.getConstant(countTrailingZeros(B.Mask), VT),
1952 } else if (PopCount == BB.Range) {
1953 // There is only one zero bit in the range, test for it directly.
1954 Cmp = DAG.getSetCC(getCurSDLoc(),
1955 TLI->getSetCCResultType(*DAG.getContext(), VT),
1957 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1960 // Make desired shift
1961 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1962 DAG.getConstant(1, VT), ShiftOp);
1964 // Emit bit tests and jumps
1965 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1966 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1967 Cmp = DAG.getSetCC(getCurSDLoc(),
1968 TLI->getSetCCResultType(*DAG.getContext(), VT),
1969 AndOp, DAG.getConstant(0, VT),
1973 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1974 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1975 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1976 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1978 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1979 MVT::Other, getControlRoot(),
1980 Cmp, DAG.getBasicBlock(B.TargetBB));
1982 // Set NextBlock to be the MBB immediately after the current one, if any.
1983 // This is used to avoid emitting unnecessary branches to the next block.
1984 MachineBasicBlock *NextBlock = 0;
1985 MachineFunction::iterator BBI = SwitchBB;
1986 if (++BBI != FuncInfo.MF->end())
1989 if (NextMBB != NextBlock)
1990 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
1991 DAG.getBasicBlock(NextMBB));
1996 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1997 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1999 // Retrieve successors.
2000 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2001 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2003 const Value *Callee(I.getCalledValue());
2004 const Function *Fn = dyn_cast<Function>(Callee);
2005 if (isa<InlineAsm>(Callee))
2007 else if (Fn && Fn->isIntrinsic()) {
2008 assert(Fn->getIntrinsicID() == Intrinsic::donothing);
2009 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2011 LowerCallTo(&I, getValue(Callee), false, LandingPad);
2013 // If the value of the invoke is used outside of its defining block, make it
2014 // available as a virtual register.
2015 CopyToExportRegsIfNeeded(&I);
2017 // Update successor info
2018 addSuccessorWithWeight(InvokeMBB, Return);
2019 addSuccessorWithWeight(InvokeMBB, LandingPad);
2021 // Drop into normal successor.
2022 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2023 MVT::Other, getControlRoot(),
2024 DAG.getBasicBlock(Return)));
2027 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2028 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2031 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2032 assert(FuncInfo.MBB->isLandingPad() &&
2033 "Call to landingpad not in landing pad!");
2035 MachineBasicBlock *MBB = FuncInfo.MBB;
2036 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2037 AddLandingPadInfo(LP, MMI, MBB);
2039 // If there aren't registers to copy the values into (e.g., during SjLj
2040 // exceptions), then don't bother to create these DAG nodes.
2041 const TargetLowering *TLI = TM.getTargetLowering();
2042 if (TLI->getExceptionPointerRegister() == 0 &&
2043 TLI->getExceptionSelectorRegister() == 0)
2046 SmallVector<EVT, 2> ValueVTs;
2047 ComputeValueVTs(*TLI, LP.getType(), ValueVTs);
2048 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2050 // Get the two live-in registers as SDValues. The physregs have already been
2051 // copied into virtual registers.
2053 Ops[0] = DAG.getZExtOrTrunc(
2054 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2055 FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()),
2056 getCurSDLoc(), ValueVTs[0]);
2057 Ops[1] = DAG.getZExtOrTrunc(
2058 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2059 FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()),
2060 getCurSDLoc(), ValueVTs[1]);
2063 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2064 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
2069 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2070 /// small case ranges).
2071 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2072 CaseRecVector& WorkList,
2074 MachineBasicBlock *Default,
2075 MachineBasicBlock *SwitchBB) {
2076 // Size is the number of Cases represented by this range.
2077 size_t Size = CR.Range.second - CR.Range.first;
2081 // Get the MachineFunction which holds the current MBB. This is used when
2082 // inserting any additional MBBs necessary to represent the switch.
2083 MachineFunction *CurMF = FuncInfo.MF;
2085 // Figure out which block is immediately after the current one.
2086 MachineBasicBlock *NextBlock = 0;
2087 MachineFunction::iterator BBI = CR.CaseBB;
2089 if (++BBI != FuncInfo.MF->end())
2092 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2093 // If any two of the cases has the same destination, and if one value
2094 // is the same as the other, but has one bit unset that the other has set,
2095 // use bit manipulation to do two compares at once. For example:
2096 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2097 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2098 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2099 if (Size == 2 && CR.CaseBB == SwitchBB) {
2100 Case &Small = *CR.Range.first;
2101 Case &Big = *(CR.Range.second-1);
2103 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2104 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2105 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2107 // Check that there is only one bit different.
2108 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2109 (SmallValue | BigValue) == BigValue) {
2110 // Isolate the common bit.
2111 APInt CommonBit = BigValue & ~SmallValue;
2112 assert((SmallValue | CommonBit) == BigValue &&
2113 CommonBit.countPopulation() == 1 && "Not a common bit?");
2115 SDValue CondLHS = getValue(SV);
2116 EVT VT = CondLHS.getValueType();
2117 SDLoc DL = getCurSDLoc();
2119 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2120 DAG.getConstant(CommonBit, VT));
2121 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2122 Or, DAG.getConstant(BigValue, VT),
2125 // Update successor info.
2126 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2127 addSuccessorWithWeight(SwitchBB, Small.BB,
2128 Small.ExtraWeight + Big.ExtraWeight);
2129 addSuccessorWithWeight(SwitchBB, Default,
2130 // The default destination is the first successor in IR.
2131 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2133 // Insert the true branch.
2134 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2135 getControlRoot(), Cond,
2136 DAG.getBasicBlock(Small.BB));
2138 // Insert the false branch.
2139 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2140 DAG.getBasicBlock(Default));
2142 DAG.setRoot(BrCond);
2148 // Order cases by weight so the most likely case will be checked first.
2149 uint32_t UnhandledWeights = 0;
2151 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2152 uint32_t IWeight = I->ExtraWeight;
2153 UnhandledWeights += IWeight;
2154 for (CaseItr J = CR.Range.first; J < I; ++J) {
2155 uint32_t JWeight = J->ExtraWeight;
2156 if (IWeight > JWeight)
2161 // Rearrange the case blocks so that the last one falls through if possible.
2162 Case &BackCase = *(CR.Range.second-1);
2164 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2165 // The last case block won't fall through into 'NextBlock' if we emit the
2166 // branches in this order. See if rearranging a case value would help.
2167 // We start at the bottom as it's the case with the least weight.
2168 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2169 if (I->BB == NextBlock) {
2170 std::swap(*I, BackCase);
2175 // Create a CaseBlock record representing a conditional branch to
2176 // the Case's target mbb if the value being switched on SV is equal
2178 MachineBasicBlock *CurBlock = CR.CaseBB;
2179 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2180 MachineBasicBlock *FallThrough;
2182 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2183 CurMF->insert(BBI, FallThrough);
2185 // Put SV in a virtual register to make it available from the new blocks.
2186 ExportFromCurrentBlock(SV);
2188 // If the last case doesn't match, go to the default block.
2189 FallThrough = Default;
2192 const Value *RHS, *LHS, *MHS;
2194 if (I->High == I->Low) {
2195 // This is just small small case range :) containing exactly 1 case
2197 LHS = SV; RHS = I->High; MHS = NULL;
2200 LHS = I->Low; MHS = SV; RHS = I->High;
2203 // The false weight should be sum of all un-handled cases.
2204 UnhandledWeights -= I->ExtraWeight;
2205 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2207 /* trueweight */ I->ExtraWeight,
2208 /* falseweight */ UnhandledWeights);
2210 // If emitting the first comparison, just call visitSwitchCase to emit the
2211 // code into the current block. Otherwise, push the CaseBlock onto the
2212 // vector to be later processed by SDISel, and insert the node's MBB
2213 // before the next MBB.
2214 if (CurBlock == SwitchBB)
2215 visitSwitchCase(CB, SwitchBB);
2217 SwitchCases.push_back(CB);
2219 CurBlock = FallThrough;
2225 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2226 return TLI.supportJumpTables() &&
2227 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2228 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
2231 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2232 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2233 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2234 return (LastExt - FirstExt + 1ULL);
2237 /// handleJTSwitchCase - Emit jumptable for current switch case range
2238 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2239 CaseRecVector &WorkList,
2241 MachineBasicBlock *Default,
2242 MachineBasicBlock *SwitchBB) {
2243 Case& FrontCase = *CR.Range.first;
2244 Case& BackCase = *(CR.Range.second-1);
2246 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2247 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2249 APInt TSize(First.getBitWidth(), 0);
2250 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2253 const TargetLowering *TLI = TM.getTargetLowering();
2254 if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries()))
2257 APInt Range = ComputeRange(First, Last);
2258 // The density is TSize / Range. Require at least 40%.
2259 // It should not be possible for IntTSize to saturate for sane code, but make
2260 // sure we handle Range saturation correctly.
2261 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2262 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2263 if (IntTSize * 10 < IntRange * 4)
2266 DEBUG(dbgs() << "Lowering jump table\n"
2267 << "First entry: " << First << ". Last entry: " << Last << '\n'
2268 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2270 // Get the MachineFunction which holds the current MBB. This is used when
2271 // inserting any additional MBBs necessary to represent the switch.
2272 MachineFunction *CurMF = FuncInfo.MF;
2274 // Figure out which block is immediately after the current one.
2275 MachineFunction::iterator BBI = CR.CaseBB;
2278 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2280 // Create a new basic block to hold the code for loading the address
2281 // of the jump table, and jumping to it. Update successor information;
2282 // we will either branch to the default case for the switch, or the jump
2284 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2285 CurMF->insert(BBI, JumpTableBB);
2287 addSuccessorWithWeight(CR.CaseBB, Default);
2288 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2290 // Build a vector of destination BBs, corresponding to each target
2291 // of the jump table. If the value of the jump table slot corresponds to
2292 // a case statement, push the case's BB onto the vector, otherwise, push
2294 std::vector<MachineBasicBlock*> DestBBs;
2296 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2297 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2298 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2300 if (Low.sle(TEI) && TEI.sle(High)) {
2301 DestBBs.push_back(I->BB);
2305 DestBBs.push_back(Default);
2309 // Calculate weight for each unique destination in CR.
2310 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2312 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2313 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2314 DestWeights.find(I->BB);
2315 if (Itr != DestWeights.end())
2316 Itr->second += I->ExtraWeight;
2318 DestWeights[I->BB] = I->ExtraWeight;
2321 // Update successor info. Add one edge to each unique successor.
2322 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2323 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2324 E = DestBBs.end(); I != E; ++I) {
2325 if (!SuccsHandled[(*I)->getNumber()]) {
2326 SuccsHandled[(*I)->getNumber()] = true;
2327 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2328 DestWeights.find(*I);
2329 addSuccessorWithWeight(JumpTableBB, *I,
2330 Itr != DestWeights.end() ? Itr->second : 0);
2334 // Create a jump table index for this jump table.
2335 unsigned JTEncoding = TLI->getJumpTableEncoding();
2336 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2337 ->createJumpTableIndex(DestBBs);
2339 // Set the jump table information so that we can codegen it as a second
2340 // MachineBasicBlock
2341 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2342 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2343 if (CR.CaseBB == SwitchBB)
2344 visitJumpTableHeader(JT, JTH, SwitchBB);
2346 JTCases.push_back(JumpTableBlock(JTH, JT));
2350 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2352 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2353 CaseRecVector& WorkList,
2355 MachineBasicBlock* Default,
2356 MachineBasicBlock* SwitchBB) {
2357 // Get the MachineFunction which holds the current MBB. This is used when
2358 // inserting any additional MBBs necessary to represent the switch.
2359 MachineFunction *CurMF = FuncInfo.MF;
2361 // Figure out which block is immediately after the current one.
2362 MachineFunction::iterator BBI = CR.CaseBB;
2365 Case& FrontCase = *CR.Range.first;
2366 Case& BackCase = *(CR.Range.second-1);
2367 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2369 // Size is the number of Cases represented by this range.
2370 unsigned Size = CR.Range.second - CR.Range.first;
2372 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2373 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2375 CaseItr Pivot = CR.Range.first + Size/2;
2377 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2378 // (heuristically) allow us to emit JumpTable's later.
2379 APInt TSize(First.getBitWidth(), 0);
2380 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2384 APInt LSize = FrontCase.size();
2385 APInt RSize = TSize-LSize;
2386 DEBUG(dbgs() << "Selecting best pivot: \n"
2387 << "First: " << First << ", Last: " << Last <<'\n'
2388 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2389 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2391 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2392 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2393 APInt Range = ComputeRange(LEnd, RBegin);
2394 assert((Range - 2ULL).isNonNegative() &&
2395 "Invalid case distance");
2396 // Use volatile double here to avoid excess precision issues on some hosts,
2397 // e.g. that use 80-bit X87 registers.
2398 volatile double LDensity =
2399 (double)LSize.roundToDouble() /
2400 (LEnd - First + 1ULL).roundToDouble();
2401 volatile double RDensity =
2402 (double)RSize.roundToDouble() /
2403 (Last - RBegin + 1ULL).roundToDouble();
2404 volatile double Metric = Range.logBase2()*(LDensity+RDensity);
2405 // Should always split in some non-trivial place
2406 DEBUG(dbgs() <<"=>Step\n"
2407 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2408 << "LDensity: " << LDensity
2409 << ", RDensity: " << RDensity << '\n'
2410 << "Metric: " << Metric << '\n');
2411 if (FMetric < Metric) {
2414 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2421 const TargetLowering *TLI = TM.getTargetLowering();
2422 if (areJTsAllowed(*TLI)) {
2423 // If our case is dense we *really* should handle it earlier!
2424 assert((FMetric > 0) && "Should handle dense range earlier!");
2426 Pivot = CR.Range.first + Size/2;
2429 CaseRange LHSR(CR.Range.first, Pivot);
2430 CaseRange RHSR(Pivot, CR.Range.second);
2431 const Constant *C = Pivot->Low;
2432 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2434 // We know that we branch to the LHS if the Value being switched on is
2435 // less than the Pivot value, C. We use this to optimize our binary
2436 // tree a bit, by recognizing that if SV is greater than or equal to the
2437 // LHS's Case Value, and that Case Value is exactly one less than the
2438 // Pivot's Value, then we can branch directly to the LHS's Target,
2439 // rather than creating a leaf node for it.
2440 if ((LHSR.second - LHSR.first) == 1 &&
2441 LHSR.first->High == CR.GE &&
2442 cast<ConstantInt>(C)->getValue() ==
2443 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2444 TrueBB = LHSR.first->BB;
2446 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2447 CurMF->insert(BBI, TrueBB);
2448 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2450 // Put SV in a virtual register to make it available from the new blocks.
2451 ExportFromCurrentBlock(SV);
2454 // Similar to the optimization above, if the Value being switched on is
2455 // known to be less than the Constant CR.LT, and the current Case Value
2456 // is CR.LT - 1, then we can branch directly to the target block for
2457 // the current Case Value, rather than emitting a RHS leaf node for it.
2458 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2459 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2460 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2461 FalseBB = RHSR.first->BB;
2463 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2464 CurMF->insert(BBI, FalseBB);
2465 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2467 // Put SV in a virtual register to make it available from the new blocks.
2468 ExportFromCurrentBlock(SV);
2471 // Create a CaseBlock record representing a conditional branch to
2472 // the LHS node if the value being switched on SV is less than C.
2473 // Otherwise, branch to LHS.
2474 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2476 if (CR.CaseBB == SwitchBB)
2477 visitSwitchCase(CB, SwitchBB);
2479 SwitchCases.push_back(CB);
2484 /// handleBitTestsSwitchCase - if current case range has few destination and
2485 /// range span less, than machine word bitwidth, encode case range into series
2486 /// of masks and emit bit tests with these masks.
2487 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2488 CaseRecVector& WorkList,
2490 MachineBasicBlock* Default,
2491 MachineBasicBlock* SwitchBB) {
2492 const TargetLowering *TLI = TM.getTargetLowering();
2493 EVT PTy = TLI->getPointerTy();
2494 unsigned IntPtrBits = PTy.getSizeInBits();
2496 Case& FrontCase = *CR.Range.first;
2497 Case& BackCase = *(CR.Range.second-1);
2499 // Get the MachineFunction which holds the current MBB. This is used when
2500 // inserting any additional MBBs necessary to represent the switch.
2501 MachineFunction *CurMF = FuncInfo.MF;
2503 // If target does not have legal shift left, do not emit bit tests at all.
2504 if (!TLI->isOperationLegal(ISD::SHL, PTy))
2508 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2510 // Single case counts one, case range - two.
2511 numCmps += (I->Low == I->High ? 1 : 2);
2514 // Count unique destinations
2515 SmallSet<MachineBasicBlock*, 4> Dests;
2516 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2517 Dests.insert(I->BB);
2518 if (Dests.size() > 3)
2519 // Don't bother the code below, if there are too much unique destinations
2522 DEBUG(dbgs() << "Total number of unique destinations: "
2523 << Dests.size() << '\n'
2524 << "Total number of comparisons: " << numCmps << '\n');
2526 // Compute span of values.
2527 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2528 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2529 APInt cmpRange = maxValue - minValue;
2531 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2532 << "Low bound: " << minValue << '\n'
2533 << "High bound: " << maxValue << '\n');
2535 if (cmpRange.uge(IntPtrBits) ||
2536 (!(Dests.size() == 1 && numCmps >= 3) &&
2537 !(Dests.size() == 2 && numCmps >= 5) &&
2538 !(Dests.size() >= 3 && numCmps >= 6)))
2541 DEBUG(dbgs() << "Emitting bit tests\n");
2542 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2544 // Optimize the case where all the case values fit in a
2545 // word without having to subtract minValue. In this case,
2546 // we can optimize away the subtraction.
2547 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2548 cmpRange = maxValue;
2550 lowBound = minValue;
2553 CaseBitsVector CasesBits;
2554 unsigned i, count = 0;
2556 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2557 MachineBasicBlock* Dest = I->BB;
2558 for (i = 0; i < count; ++i)
2559 if (Dest == CasesBits[i].BB)
2563 assert((count < 3) && "Too much destinations to test!");
2564 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2568 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2569 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2571 uint64_t lo = (lowValue - lowBound).getZExtValue();
2572 uint64_t hi = (highValue - lowBound).getZExtValue();
2573 CasesBits[i].ExtraWeight += I->ExtraWeight;
2575 for (uint64_t j = lo; j <= hi; j++) {
2576 CasesBits[i].Mask |= 1ULL << j;
2577 CasesBits[i].Bits++;
2581 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2585 // Figure out which block is immediately after the current one.
2586 MachineFunction::iterator BBI = CR.CaseBB;
2589 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2591 DEBUG(dbgs() << "Cases:\n");
2592 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2593 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2594 << ", Bits: " << CasesBits[i].Bits
2595 << ", BB: " << CasesBits[i].BB << '\n');
2597 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2598 CurMF->insert(BBI, CaseBB);
2599 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2601 CasesBits[i].BB, CasesBits[i].ExtraWeight));
2603 // Put SV in a virtual register to make it available from the new blocks.
2604 ExportFromCurrentBlock(SV);
2607 BitTestBlock BTB(lowBound, cmpRange, SV,
2608 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2609 CR.CaseBB, Default, BTC);
2611 if (CR.CaseBB == SwitchBB)
2612 visitBitTestHeader(BTB, SwitchBB);
2614 BitTestCases.push_back(BTB);
2619 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2620 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2621 const SwitchInst& SI) {
2624 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2625 // Start with "simple" cases
2626 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2628 const BasicBlock *SuccBB = i.getCaseSuccessor();
2629 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2631 uint32_t ExtraWeight =
2632 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2634 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2635 SMBB, ExtraWeight));
2637 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2639 // Merge case into clusters
2640 if (Cases.size() >= 2)
2641 // Must recompute end() each iteration because it may be
2642 // invalidated by erase if we hold on to it
2643 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
2644 J != Cases.end(); ) {
2645 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2646 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2647 MachineBasicBlock* nextBB = J->BB;
2648 MachineBasicBlock* currentBB = I->BB;
2650 // If the two neighboring cases go to the same destination, merge them
2651 // into a single case.
2652 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2654 I->ExtraWeight += J->ExtraWeight;
2661 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2662 if (I->Low != I->High)
2663 // A range counts double, since it requires two compares.
2670 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2671 MachineBasicBlock *Last) {
2673 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2674 if (JTCases[i].first.HeaderBB == First)
2675 JTCases[i].first.HeaderBB = Last;
2677 // Update BitTestCases.
2678 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2679 if (BitTestCases[i].Parent == First)
2680 BitTestCases[i].Parent = Last;
2683 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2684 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2686 // Figure out which block is immediately after the current one.
2687 MachineBasicBlock *NextBlock = 0;
2688 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2690 // If there is only the default destination, branch to it if it is not the
2691 // next basic block. Otherwise, just fall through.
2692 if (!SI.getNumCases()) {
2693 // Update machine-CFG edges.
2695 // If this is not a fall-through branch, emit the branch.
2696 SwitchMBB->addSuccessor(Default);
2697 if (Default != NextBlock)
2698 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2699 MVT::Other, getControlRoot(),
2700 DAG.getBasicBlock(Default)));
2705 // If there are any non-default case statements, create a vector of Cases
2706 // representing each one, and sort the vector so that we can efficiently
2707 // create a binary search tree from them.
2709 size_t numCmps = Clusterify(Cases, SI);
2710 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2711 << ". Total compares: " << numCmps << '\n');
2714 // Get the Value to be switched on and default basic blocks, which will be
2715 // inserted into CaseBlock records, representing basic blocks in the binary
2717 const Value *SV = SI.getCondition();
2719 // Push the initial CaseRec onto the worklist
2720 CaseRecVector WorkList;
2721 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2722 CaseRange(Cases.begin(),Cases.end())));
2724 while (!WorkList.empty()) {
2725 // Grab a record representing a case range to process off the worklist
2726 CaseRec CR = WorkList.back();
2727 WorkList.pop_back();
2729 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2732 // If the range has few cases (two or less) emit a series of specific
2734 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2737 // If the switch has more than N blocks, and is at least 40% dense, and the
2738 // target supports indirect branches, then emit a jump table rather than
2739 // lowering the switch to a binary tree of conditional branches.
2740 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2741 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2744 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2745 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2746 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2750 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2751 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2753 // Update machine-CFG edges with unique successors.
2754 SmallSet<BasicBlock*, 32> Done;
2755 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2756 BasicBlock *BB = I.getSuccessor(i);
2757 bool Inserted = Done.insert(BB);
2761 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2762 addSuccessorWithWeight(IndirectBrMBB, Succ);
2765 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2766 MVT::Other, getControlRoot(),
2767 getValue(I.getAddress())));
2770 void SelectionDAGBuilder::visitFSub(const User &I) {
2771 // -0.0 - X --> fneg
2772 Type *Ty = I.getType();
2773 if (isa<Constant>(I.getOperand(0)) &&
2774 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2775 SDValue Op2 = getValue(I.getOperand(1));
2776 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2777 Op2.getValueType(), Op2));
2781 visitBinary(I, ISD::FSUB);
2784 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2785 SDValue Op1 = getValue(I.getOperand(0));
2786 SDValue Op2 = getValue(I.getOperand(1));
2787 setValue(&I, DAG.getNode(OpCode, getCurSDLoc(),
2788 Op1.getValueType(), Op1, Op2));
2791 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2792 SDValue Op1 = getValue(I.getOperand(0));
2793 SDValue Op2 = getValue(I.getOperand(1));
2795 EVT ShiftTy = TM.getTargetLowering()->getShiftAmountTy(Op2.getValueType());
2797 // Coerce the shift amount to the right type if we can.
2798 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2799 unsigned ShiftSize = ShiftTy.getSizeInBits();
2800 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2801 SDLoc DL = getCurSDLoc();
2803 // If the operand is smaller than the shift count type, promote it.
2804 if (ShiftSize > Op2Size)
2805 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2807 // If the operand is larger than the shift count type but the shift
2808 // count type has enough bits to represent any shift value, truncate
2809 // it now. This is a common case and it exposes the truncate to
2810 // optimization early.
2811 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2812 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2813 // Otherwise we'll need to temporarily settle for some other convenient
2814 // type. Type legalization will make adjustments once the shiftee is split.
2816 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2819 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(),
2820 Op1.getValueType(), Op1, Op2));
2823 void SelectionDAGBuilder::visitSDiv(const User &I) {
2824 SDValue Op1 = getValue(I.getOperand(0));
2825 SDValue Op2 = getValue(I.getOperand(1));
2827 // Turn exact SDivs into multiplications.
2828 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2830 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2831 !isa<ConstantSDNode>(Op1) &&
2832 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2833 setValue(&I, TM.getTargetLowering()->BuildExactSDIV(Op1, Op2,
2834 getCurSDLoc(), DAG));
2836 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2840 void SelectionDAGBuilder::visitICmp(const User &I) {
2841 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2842 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2843 predicate = IC->getPredicate();
2844 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2845 predicate = ICmpInst::Predicate(IC->getPredicate());
2846 SDValue Op1 = getValue(I.getOperand(0));
2847 SDValue Op2 = getValue(I.getOperand(1));
2848 ISD::CondCode Opcode = getICmpCondCode(predicate);
2850 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2851 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2854 void SelectionDAGBuilder::visitFCmp(const User &I) {
2855 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2856 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2857 predicate = FC->getPredicate();
2858 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2859 predicate = FCmpInst::Predicate(FC->getPredicate());
2860 SDValue Op1 = getValue(I.getOperand(0));
2861 SDValue Op2 = getValue(I.getOperand(1));
2862 ISD::CondCode Condition = getFCmpCondCode(predicate);
2863 if (TM.Options.NoNaNsFPMath)
2864 Condition = getFCmpCodeWithoutNaN(Condition);
2865 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2866 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2869 void SelectionDAGBuilder::visitSelect(const User &I) {
2870 SmallVector<EVT, 4> ValueVTs;
2871 ComputeValueVTs(*TM.getTargetLowering(), I.getType(), ValueVTs);
2872 unsigned NumValues = ValueVTs.size();
2873 if (NumValues == 0) return;
2875 SmallVector<SDValue, 4> Values(NumValues);
2876 SDValue Cond = getValue(I.getOperand(0));
2877 SDValue TrueVal = getValue(I.getOperand(1));
2878 SDValue FalseVal = getValue(I.getOperand(2));
2879 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2880 ISD::VSELECT : ISD::SELECT;
2882 for (unsigned i = 0; i != NumValues; ++i)
2883 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2884 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2886 SDValue(TrueVal.getNode(),
2887 TrueVal.getResNo() + i),
2888 SDValue(FalseVal.getNode(),
2889 FalseVal.getResNo() + i));
2891 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2892 DAG.getVTList(&ValueVTs[0], NumValues),
2893 &Values[0], NumValues));
2896 void SelectionDAGBuilder::visitTrunc(const User &I) {
2897 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2898 SDValue N = getValue(I.getOperand(0));
2899 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2900 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2903 void SelectionDAGBuilder::visitZExt(const User &I) {
2904 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2905 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2906 SDValue N = getValue(I.getOperand(0));
2907 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2908 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2911 void SelectionDAGBuilder::visitSExt(const User &I) {
2912 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2913 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2914 SDValue N = getValue(I.getOperand(0));
2915 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2916 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2919 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2920 // FPTrunc is never a no-op cast, no need to check
2921 SDValue N = getValue(I.getOperand(0));
2922 const TargetLowering *TLI = TM.getTargetLowering();
2923 EVT DestVT = TLI->getValueType(I.getType());
2924 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(),
2926 DAG.getTargetConstant(0, TLI->getPointerTy())));
2929 void SelectionDAGBuilder::visitFPExt(const User &I) {
2930 // FPExt is never a no-op cast, no need to check
2931 SDValue N = getValue(I.getOperand(0));
2932 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2933 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2936 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2937 // FPToUI is never a no-op cast, no need to check
2938 SDValue N = getValue(I.getOperand(0));
2939 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2940 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2943 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2944 // FPToSI is never a no-op cast, no need to check
2945 SDValue N = getValue(I.getOperand(0));
2946 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2947 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2950 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2951 // UIToFP is never a no-op cast, no need to check
2952 SDValue N = getValue(I.getOperand(0));
2953 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2954 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2957 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2958 // SIToFP is never a no-op cast, no need to check
2959 SDValue N = getValue(I.getOperand(0));
2960 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2961 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2964 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2965 // What to do depends on the size of the integer and the size of the pointer.
2966 // We can either truncate, zero extend, or no-op, accordingly.
2967 SDValue N = getValue(I.getOperand(0));
2968 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2969 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2972 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2973 // What to do depends on the size of the integer and the size of the pointer.
2974 // We can either truncate, zero extend, or no-op, accordingly.
2975 SDValue N = getValue(I.getOperand(0));
2976 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2977 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2980 void SelectionDAGBuilder::visitBitCast(const User &I) {
2981 SDValue N = getValue(I.getOperand(0));
2982 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2984 // BitCast assures us that source and destination are the same size so this is
2985 // either a BITCAST or a no-op.
2986 if (DestVT != N.getValueType())
2987 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
2988 DestVT, N)); // convert types.
2989 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
2990 // might fold any kind of constant expression to an integer constant and that
2991 // is not what we are looking for. Only regcognize a bitcast of a genuine
2992 // constant integer as an opaque constant.
2993 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
2994 setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
2997 setValue(&I, N); // noop cast.
3000 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3001 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3002 const Value *SV = I.getOperand(0);
3003 SDValue N = getValue(SV);
3004 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
3006 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3007 unsigned DestAS = I.getType()->getPointerAddressSpace();
3009 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3010 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3015 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3016 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3017 SDValue InVec = getValue(I.getOperand(0));
3018 SDValue InVal = getValue(I.getOperand(1));
3019 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3020 getCurSDLoc(), TLI.getVectorIdxTy());
3021 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3022 TM.getTargetLowering()->getValueType(I.getType()),
3023 InVec, InVal, InIdx));
3026 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3027 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3028 SDValue InVec = getValue(I.getOperand(0));
3029 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3030 getCurSDLoc(), TLI.getVectorIdxTy());
3031 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3032 TM.getTargetLowering()->getValueType(I.getType()),
3036 // Utility for visitShuffleVector - Return true if every element in Mask,
3037 // beginning from position Pos and ending in Pos+Size, falls within the
3038 // specified sequential range [L, L+Pos). or is undef.
3039 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
3040 unsigned Pos, unsigned Size, int Low) {
3041 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3042 if (Mask[i] >= 0 && Mask[i] != Low)
3047 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3048 SDValue Src1 = getValue(I.getOperand(0));
3049 SDValue Src2 = getValue(I.getOperand(1));
3051 SmallVector<int, 8> Mask;
3052 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3053 unsigned MaskNumElts = Mask.size();
3055 const TargetLowering *TLI = TM.getTargetLowering();
3056 EVT VT = TLI->getValueType(I.getType());
3057 EVT SrcVT = Src1.getValueType();
3058 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3060 if (SrcNumElts == MaskNumElts) {
3061 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3066 // Normalize the shuffle vector since mask and vector length don't match.
3067 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3068 // Mask is longer than the source vectors and is a multiple of the source
3069 // vectors. We can use concatenate vector to make the mask and vectors
3071 if (SrcNumElts*2 == MaskNumElts) {
3072 // First check for Src1 in low and Src2 in high
3073 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3074 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3075 // The shuffle is concatenating two vectors together.
3076 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3080 // Then check for Src2 in low and Src1 in high
3081 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3082 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3083 // The shuffle is concatenating two vectors together.
3084 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3090 // Pad both vectors with undefs to make them the same length as the mask.
3091 unsigned NumConcat = MaskNumElts / SrcNumElts;
3092 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3093 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
3094 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3096 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3097 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3101 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3103 &MOps1[0], NumConcat);
3104 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3106 &MOps2[0], NumConcat);
3108 // Readjust mask for new input vector length.
3109 SmallVector<int, 8> MappedOps;
3110 for (unsigned i = 0; i != MaskNumElts; ++i) {
3112 if (Idx >= (int)SrcNumElts)
3113 Idx -= SrcNumElts - MaskNumElts;
3114 MappedOps.push_back(Idx);
3117 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3122 if (SrcNumElts > MaskNumElts) {
3123 // Analyze the access pattern of the vector to see if we can extract
3124 // two subvectors and do the shuffle. The analysis is done by calculating
3125 // the range of elements the mask access on both vectors.
3126 int MinRange[2] = { static_cast<int>(SrcNumElts),
3127 static_cast<int>(SrcNumElts)};
3128 int MaxRange[2] = {-1, -1};
3130 for (unsigned i = 0; i != MaskNumElts; ++i) {
3136 if (Idx >= (int)SrcNumElts) {
3140 if (Idx > MaxRange[Input])
3141 MaxRange[Input] = Idx;
3142 if (Idx < MinRange[Input])
3143 MinRange[Input] = Idx;
3146 // Check if the access is smaller than the vector size and can we find
3147 // a reasonable extract index.
3148 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3150 int StartIdx[2]; // StartIdx to extract from
3151 for (unsigned Input = 0; Input < 2; ++Input) {
3152 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
3153 RangeUse[Input] = 0; // Unused
3154 StartIdx[Input] = 0;
3158 // Find a good start index that is a multiple of the mask length. Then
3159 // see if the rest of the elements are in range.
3160 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3161 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3162 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3163 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3166 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3167 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3170 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3171 // Extract appropriate subvector and generate a vector shuffle
3172 for (unsigned Input = 0; Input < 2; ++Input) {
3173 SDValue &Src = Input == 0 ? Src1 : Src2;
3174 if (RangeUse[Input] == 0)
3175 Src = DAG.getUNDEF(VT);
3177 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT,
3178 Src, DAG.getConstant(StartIdx[Input],
3179 TLI->getVectorIdxTy()));
3182 // Calculate new mask.
3183 SmallVector<int, 8> MappedOps;
3184 for (unsigned i = 0; i != MaskNumElts; ++i) {
3187 if (Idx < (int)SrcNumElts)
3190 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3192 MappedOps.push_back(Idx);
3195 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3201 // We can't use either concat vectors or extract subvectors so fall back to
3202 // replacing the shuffle with extract and build vector.
3203 // to insert and build vector.
3204 EVT EltVT = VT.getVectorElementType();
3205 EVT IdxVT = TLI->getVectorIdxTy();
3206 SmallVector<SDValue,8> Ops;
3207 for (unsigned i = 0; i != MaskNumElts; ++i) {
3212 Res = DAG.getUNDEF(EltVT);
3214 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3215 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3217 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3218 EltVT, Src, DAG.getConstant(Idx, IdxVT));
3224 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
3225 VT, &Ops[0], Ops.size()));
3228 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3229 const Value *Op0 = I.getOperand(0);
3230 const Value *Op1 = I.getOperand(1);
3231 Type *AggTy = I.getType();
3232 Type *ValTy = Op1->getType();
3233 bool IntoUndef = isa<UndefValue>(Op0);
3234 bool FromUndef = isa<UndefValue>(Op1);
3236 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3238 const TargetLowering *TLI = TM.getTargetLowering();
3239 SmallVector<EVT, 4> AggValueVTs;
3240 ComputeValueVTs(*TLI, AggTy, AggValueVTs);
3241 SmallVector<EVT, 4> ValValueVTs;
3242 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
3244 unsigned NumAggValues = AggValueVTs.size();
3245 unsigned NumValValues = ValValueVTs.size();
3246 SmallVector<SDValue, 4> Values(NumAggValues);
3248 SDValue Agg = getValue(Op0);
3250 // Copy the beginning value(s) from the original aggregate.
3251 for (; i != LinearIndex; ++i)
3252 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3253 SDValue(Agg.getNode(), Agg.getResNo() + i);
3254 // Copy values from the inserted value(s).
3256 SDValue Val = getValue(Op1);
3257 for (; i != LinearIndex + NumValValues; ++i)
3258 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3259 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3261 // Copy remaining value(s) from the original aggregate.
3262 for (; i != NumAggValues; ++i)
3263 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3264 SDValue(Agg.getNode(), Agg.getResNo() + i);
3266 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3267 DAG.getVTList(&AggValueVTs[0], NumAggValues),
3268 &Values[0], NumAggValues));
3271 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3272 const Value *Op0 = I.getOperand(0);
3273 Type *AggTy = Op0->getType();
3274 Type *ValTy = I.getType();
3275 bool OutOfUndef = isa<UndefValue>(Op0);
3277 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3279 const TargetLowering *TLI = TM.getTargetLowering();
3280 SmallVector<EVT, 4> ValValueVTs;
3281 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
3283 unsigned NumValValues = ValValueVTs.size();
3285 // Ignore a extractvalue that produces an empty object
3286 if (!NumValValues) {
3287 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3291 SmallVector<SDValue, 4> Values(NumValValues);
3293 SDValue Agg = getValue(Op0);
3294 // Copy out the selected value(s).
3295 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3296 Values[i - LinearIndex] =
3298 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3299 SDValue(Agg.getNode(), Agg.getResNo() + i);
3301 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3302 DAG.getVTList(&ValValueVTs[0], NumValValues),
3303 &Values[0], NumValValues));
3306 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3307 Value *Op0 = I.getOperand(0);
3308 // Note that the pointer operand may be a vector of pointers. Take the scalar
3309 // element which holds a pointer.
3310 Type *Ty = Op0->getType()->getScalarType();
3311 unsigned AS = Ty->getPointerAddressSpace();
3312 SDValue N = getValue(Op0);
3314 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3316 const Value *Idx = *OI;
3317 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3318 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3321 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3322 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3323 DAG.getConstant(Offset, N.getValueType()));
3326 Ty = StTy->getElementType(Field);
3328 Ty = cast<SequentialType>(Ty)->getElementType();
3330 // If this is a constant subscript, handle it quickly.
3331 const TargetLowering *TLI = TM.getTargetLowering();
3332 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3333 if (CI->isZero()) continue;
3335 DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3337 EVT PTy = TLI->getPointerTy(AS);
3338 unsigned PtrBits = PTy.getSizeInBits();
3340 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
3341 DAG.getConstant(Offs, MVT::i64));
3343 OffsVal = DAG.getConstant(Offs, PTy);
3345 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3350 // N = N + Idx * ElementSize;
3351 APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS),
3352 DL->getTypeAllocSize(Ty));
3353 SDValue IdxN = getValue(Idx);
3355 // If the index is smaller or larger than intptr_t, truncate or extend
3357 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
3359 // If this is a multiply by a power of two, turn it into a shl
3360 // immediately. This is a very common case.
3361 if (ElementSize != 1) {
3362 if (ElementSize.isPowerOf2()) {
3363 unsigned Amt = ElementSize.logBase2();
3364 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
3365 N.getValueType(), IdxN,
3366 DAG.getConstant(Amt, IdxN.getValueType()));
3368 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
3369 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
3370 N.getValueType(), IdxN, Scale);
3374 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
3375 N.getValueType(), N, IdxN);
3382 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3383 // If this is a fixed sized alloca in the entry block of the function,
3384 // allocate it statically on the stack.
3385 if (FuncInfo.StaticAllocaMap.count(&I))
3386 return; // getValue will auto-populate this.
3388 Type *Ty = I.getAllocatedType();
3389 const TargetLowering *TLI = TM.getTargetLowering();
3390 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
3392 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
3395 SDValue AllocSize = getValue(I.getArraySize());
3397 EVT IntPtr = TLI->getPointerTy();
3398 if (AllocSize.getValueType() != IntPtr)
3399 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
3401 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
3403 DAG.getConstant(TySize, IntPtr));
3405 // Handle alignment. If the requested alignment is less than or equal to
3406 // the stack alignment, ignore it. If the size is greater than or equal to
3407 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3408 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
3409 if (Align <= StackAlign)
3412 // Round the size of the allocation up to the stack alignment size
3413 // by add SA-1 to the size.
3414 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
3415 AllocSize.getValueType(), AllocSize,
3416 DAG.getIntPtrConstant(StackAlign-1));
3418 // Mask out the low bits for alignment purposes.
3419 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
3420 AllocSize.getValueType(), AllocSize,
3421 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3423 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3424 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3425 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(),
3428 DAG.setRoot(DSA.getValue(1));
3430 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
3433 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3435 return visitAtomicLoad(I);
3437 const Value *SV = I.getOperand(0);
3438 SDValue Ptr = getValue(SV);
3440 Type *Ty = I.getType();
3442 bool isVolatile = I.isVolatile();
3443 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3444 bool isInvariant = I.getMetadata("invariant.load") != 0;
3445 unsigned Alignment = I.getAlignment();
3446 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3447 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3449 SmallVector<EVT, 4> ValueVTs;
3450 SmallVector<uint64_t, 4> Offsets;
3451 ComputeValueVTs(*TM.getTargetLowering(), Ty, ValueVTs, &Offsets);
3452 unsigned NumValues = ValueVTs.size();
3457 bool ConstantMemory = false;
3458 if (isVolatile || NumValues > MaxParallelChains)
3459 // Serialize volatile loads with other side effects.
3461 else if (AA->pointsToConstantMemory(
3462 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
3463 // Do not serialize (non-volatile) loads of constant memory with anything.
3464 Root = DAG.getEntryNode();
3465 ConstantMemory = true;
3467 // Do not serialize non-volatile loads against each other.
3468 Root = DAG.getRoot();
3471 const TargetLowering *TLI = TM.getTargetLowering();
3473 Root = TLI->prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
3475 SmallVector<SDValue, 4> Values(NumValues);
3476 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3478 EVT PtrVT = Ptr.getValueType();
3479 unsigned ChainI = 0;
3480 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3481 // Serializing loads here may result in excessive register pressure, and
3482 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3483 // could recover a bit by hoisting nodes upward in the chain by recognizing
3484 // they are side-effect free or do not alias. The optimizer should really
3485 // avoid this case by converting large object/array copies to llvm.memcpy
3486 // (MaxParallelChains should always remain as failsafe).
3487 if (ChainI == MaxParallelChains) {
3488 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3489 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3490 MVT::Other, &Chains[0], ChainI);
3494 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
3496 DAG.getConstant(Offsets[i], PtrVT));
3497 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
3498 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3499 isNonTemporal, isInvariant, Alignment, TBAAInfo,
3503 Chains[ChainI] = L.getValue(1);
3506 if (!ConstantMemory) {
3507 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3508 MVT::Other, &Chains[0], ChainI);
3512 PendingLoads.push_back(Chain);
3515 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3516 DAG.getVTList(&ValueVTs[0], NumValues),
3517 &Values[0], NumValues));
3520 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3522 return visitAtomicStore(I);
3524 const Value *SrcV = I.getOperand(0);
3525 const Value *PtrV = I.getOperand(1);
3527 SmallVector<EVT, 4> ValueVTs;
3528 SmallVector<uint64_t, 4> Offsets;
3529 ComputeValueVTs(*TM.getTargetLowering(), SrcV->getType(), ValueVTs, &Offsets);
3530 unsigned NumValues = ValueVTs.size();
3534 // Get the lowered operands. Note that we do this after
3535 // checking if NumResults is zero, because with zero results
3536 // the operands won't have values in the map.
3537 SDValue Src = getValue(SrcV);
3538 SDValue Ptr = getValue(PtrV);
3540 SDValue Root = getRoot();
3541 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3543 EVT PtrVT = Ptr.getValueType();
3544 bool isVolatile = I.isVolatile();
3545 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3546 unsigned Alignment = I.getAlignment();
3547 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3549 unsigned ChainI = 0;
3550 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3551 // See visitLoad comments.
3552 if (ChainI == MaxParallelChains) {
3553 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3554 MVT::Other, &Chains[0], ChainI);
3558 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
3559 DAG.getConstant(Offsets[i], PtrVT));
3560 SDValue St = DAG.getStore(Root, getCurSDLoc(),
3561 SDValue(Src.getNode(), Src.getResNo() + i),
3562 Add, MachinePointerInfo(PtrV, Offsets[i]),
3563 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3564 Chains[ChainI] = St;
3567 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3568 MVT::Other, &Chains[0], ChainI);
3569 DAG.setRoot(StoreNode);
3572 static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
3573 SynchronizationScope Scope,
3574 bool Before, SDLoc dl,
3576 const TargetLowering &TLI) {
3577 // Fence, if necessary
3579 if (Order == AcquireRelease || Order == SequentiallyConsistent)
3581 else if (Order == Acquire || Order == Monotonic)
3584 if (Order == AcquireRelease)
3586 else if (Order == Release || Order == Monotonic)
3591 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3592 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
3593 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
3596 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3597 SDLoc dl = getCurSDLoc();
3598 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3599 AtomicOrdering FailureOrder = I.getFailureOrdering();
3600 SynchronizationScope Scope = I.getSynchScope();
3602 SDValue InChain = getRoot();
3604 const TargetLowering *TLI = TM.getTargetLowering();
3605 if (TLI->getInsertFencesForAtomic())
3606 InChain = InsertFenceForAtomic(InChain, SuccessOrder, Scope, true, dl,
3610 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
3611 getValue(I.getCompareOperand()).getSimpleValueType(),
3613 getValue(I.getPointerOperand()),
3614 getValue(I.getCompareOperand()),
3615 getValue(I.getNewValOperand()),
3616 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
3617 TLI->getInsertFencesForAtomic() ? Monotonic : SuccessOrder,
3618 TLI->getInsertFencesForAtomic() ? Monotonic : FailureOrder,
3621 SDValue OutChain = L.getValue(1);
3623 if (TLI->getInsertFencesForAtomic())
3624 OutChain = InsertFenceForAtomic(OutChain, SuccessOrder, Scope, false, dl,
3628 DAG.setRoot(OutChain);
3631 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3632 SDLoc dl = getCurSDLoc();
3634 switch (I.getOperation()) {
3635 default: llvm_unreachable("Unknown atomicrmw operation");
3636 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3637 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3638 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3639 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3640 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3641 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3642 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3643 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3644 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3645 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3646 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3648 AtomicOrdering Order = I.getOrdering();
3649 SynchronizationScope Scope = I.getSynchScope();
3651 SDValue InChain = getRoot();
3653 const TargetLowering *TLI = TM.getTargetLowering();
3654 if (TLI->getInsertFencesForAtomic())
3655 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3659 DAG.getAtomic(NT, dl,
3660 getValue(I.getValOperand()).getSimpleValueType(),
3662 getValue(I.getPointerOperand()),
3663 getValue(I.getValOperand()),
3664 I.getPointerOperand(), 0 /* Alignment */,
3665 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3668 SDValue OutChain = L.getValue(1);
3670 if (TLI->getInsertFencesForAtomic())
3671 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3675 DAG.setRoot(OutChain);
3678 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3679 SDLoc dl = getCurSDLoc();
3680 const TargetLowering *TLI = TM.getTargetLowering();
3683 Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy());
3684 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy());
3685 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
3688 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3689 SDLoc dl = getCurSDLoc();
3690 AtomicOrdering Order = I.getOrdering();
3691 SynchronizationScope Scope = I.getSynchScope();
3693 SDValue InChain = getRoot();
3695 const TargetLowering *TLI = TM.getTargetLowering();
3696 EVT VT = TLI->getValueType(I.getType());
3698 if (I.getAlignment() < VT.getSizeInBits() / 8)
3699 report_fatal_error("Cannot generate unaligned atomic load");
3701 InChain = TLI->prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3703 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3704 getValue(I.getPointerOperand()),
3705 I.getPointerOperand(), I.getAlignment(),
3706 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3709 SDValue OutChain = L.getValue(1);
3711 if (TLI->getInsertFencesForAtomic())
3712 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3716 DAG.setRoot(OutChain);
3719 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3720 SDLoc dl = getCurSDLoc();
3722 AtomicOrdering Order = I.getOrdering();
3723 SynchronizationScope Scope = I.getSynchScope();
3725 SDValue InChain = getRoot();
3727 const TargetLowering *TLI = TM.getTargetLowering();
3728 EVT VT = TLI->getValueType(I.getValueOperand()->getType());
3730 if (I.getAlignment() < VT.getSizeInBits() / 8)
3731 report_fatal_error("Cannot generate unaligned atomic store");
3733 if (TLI->getInsertFencesForAtomic())
3734 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3738 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3740 getValue(I.getPointerOperand()),
3741 getValue(I.getValueOperand()),
3742 I.getPointerOperand(), I.getAlignment(),
3743 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3746 if (TLI->getInsertFencesForAtomic())
3747 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3750 DAG.setRoot(OutChain);
3753 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3755 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3756 unsigned Intrinsic) {
3757 bool HasChain = !I.doesNotAccessMemory();
3758 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3760 // Build the operand list.
3761 SmallVector<SDValue, 8> Ops;
3762 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3764 // We don't need to serialize loads against other loads.
3765 Ops.push_back(DAG.getRoot());
3767 Ops.push_back(getRoot());
3771 // Info is set by getTgtMemInstrinsic
3772 TargetLowering::IntrinsicInfo Info;
3773 const TargetLowering *TLI = TM.getTargetLowering();
3774 bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic);
3776 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3777 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3778 Info.opc == ISD::INTRINSIC_W_CHAIN)
3779 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy()));
3781 // Add all operands of the call to the operand list.
3782 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3783 SDValue Op = getValue(I.getArgOperand(i));
3787 SmallVector<EVT, 4> ValueVTs;
3788 ComputeValueVTs(*TLI, I.getType(), ValueVTs);
3791 ValueVTs.push_back(MVT::Other);
3793 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3797 if (IsTgtIntrinsic) {
3798 // This is target intrinsic that touches memory
3799 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3800 VTs, &Ops[0], Ops.size(),
3802 MachinePointerInfo(Info.ptrVal, Info.offset),
3803 Info.align, Info.vol,
3804 Info.readMem, Info.writeMem);
3805 } else if (!HasChain) {
3806 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(),
3807 VTs, &Ops[0], Ops.size());
3808 } else if (!I.getType()->isVoidTy()) {
3809 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(),
3810 VTs, &Ops[0], Ops.size());
3812 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(),
3813 VTs, &Ops[0], Ops.size());
3817 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3819 PendingLoads.push_back(Chain);
3824 if (!I.getType()->isVoidTy()) {
3825 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3826 EVT VT = TLI->getValueType(PTy);
3827 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3830 setValue(&I, Result);
3834 /// GetSignificand - Get the significand and build it into a floating-point
3835 /// number with exponent of 1:
3837 /// Op = (Op & 0x007fffff) | 0x3f800000;
3839 /// where Op is the hexadecimal representation of floating point value.
3841 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3842 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3843 DAG.getConstant(0x007fffff, MVT::i32));
3844 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3845 DAG.getConstant(0x3f800000, MVT::i32));
3846 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3849 /// GetExponent - Get the exponent:
3851 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3853 /// where Op is the hexadecimal representation of floating point value.
3855 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3857 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3858 DAG.getConstant(0x7f800000, MVT::i32));
3859 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3860 DAG.getConstant(23, TLI.getPointerTy()));
3861 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3862 DAG.getConstant(127, MVT::i32));
3863 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3866 /// getF32Constant - Get 32-bit floating point constant.
3868 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3869 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3873 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
3874 /// limited-precision mode.
3875 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3876 const TargetLowering &TLI) {
3877 if (Op.getValueType() == MVT::f32 &&
3878 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3880 // Put the exponent in the right bit position for later addition to the
3883 // #define LOG2OFe 1.4426950f
3884 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3885 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3886 getF32Constant(DAG, 0x3fb8aa3b));
3887 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3889 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3890 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3891 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3893 // IntegerPartOfX <<= 23;
3894 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3895 DAG.getConstant(23, TLI.getPointerTy()));
3897 SDValue TwoToFracPartOfX;
3898 if (LimitFloatPrecision <= 6) {
3899 // For floating-point precision of 6:
3901 // TwoToFractionalPartOfX =
3903 // (0.735607626f + 0.252464424f * x) * x;
3905 // error 0.0144103317, which is 6 bits
3906 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3907 getF32Constant(DAG, 0x3e814304));
3908 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3909 getF32Constant(DAG, 0x3f3c50c8));
3910 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3911 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3912 getF32Constant(DAG, 0x3f7f5e7e));
3913 } else if (LimitFloatPrecision <= 12) {
3914 // For floating-point precision of 12:
3916 // TwoToFractionalPartOfX =
3919 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3921 // 0.000107046256 error, which is 13 to 14 bits
3922 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3923 getF32Constant(DAG, 0x3da235e3));
3924 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3925 getF32Constant(DAG, 0x3e65b8f3));
3926 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3927 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3928 getF32Constant(DAG, 0x3f324b07));
3929 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3930 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3931 getF32Constant(DAG, 0x3f7ff8fd));
3932 } else { // LimitFloatPrecision <= 18
3933 // For floating-point precision of 18:
3935 // TwoToFractionalPartOfX =
3939 // (0.554906021e-1f +
3940 // (0.961591928e-2f +
3941 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3943 // error 2.47208000*10^(-7), which is better than 18 bits
3944 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3945 getF32Constant(DAG, 0x3924b03e));
3946 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3947 getF32Constant(DAG, 0x3ab24b87));
3948 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3949 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3950 getF32Constant(DAG, 0x3c1d8c17));
3951 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3952 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3953 getF32Constant(DAG, 0x3d634a1d));
3954 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3955 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3956 getF32Constant(DAG, 0x3e75fe14));
3957 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3958 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3959 getF32Constant(DAG, 0x3f317234));
3960 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3961 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3962 getF32Constant(DAG, 0x3f800000));
3965 // Add the exponent into the result in integer domain.
3966 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
3967 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3968 DAG.getNode(ISD::ADD, dl, MVT::i32,
3969 t13, IntegerPartOfX));
3972 // No special expansion.
3973 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
3976 /// expandLog - Lower a log intrinsic. Handles the special sequences for
3977 /// limited-precision mode.
3978 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3979 const TargetLowering &TLI) {
3980 if (Op.getValueType() == MVT::f32 &&
3981 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3982 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3984 // Scale the exponent by log(2) [0.69314718f].
3985 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3986 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3987 getF32Constant(DAG, 0x3f317218));
3989 // Get the significand and build it into a floating-point number with
3991 SDValue X = GetSignificand(DAG, Op1, dl);
3993 SDValue LogOfMantissa;
3994 if (LimitFloatPrecision <= 6) {
3995 // For floating-point precision of 6:
3999 // (1.4034025f - 0.23903021f * x) * x;
4001 // error 0.0034276066, which is better than 8 bits
4002 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4003 getF32Constant(DAG, 0xbe74c456));
4004 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4005 getF32Constant(DAG, 0x3fb3a2b1));
4006 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4007 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4008 getF32Constant(DAG, 0x3f949a29));
4009 } else if (LimitFloatPrecision <= 12) {
4010 // For floating-point precision of 12:
4016 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4018 // error 0.000061011436, which is 14 bits
4019 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4020 getF32Constant(DAG, 0xbd67b6d6));
4021 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4022 getF32Constant(DAG, 0x3ee4f4b8));
4023 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4024 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4025 getF32Constant(DAG, 0x3fbc278b));
4026 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4027 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4028 getF32Constant(DAG, 0x40348e95));
4029 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4030 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4031 getF32Constant(DAG, 0x3fdef31a));
4032 } else { // LimitFloatPrecision <= 18
4033 // For floating-point precision of 18:
4041 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4043 // error 0.0000023660568, which is better than 18 bits
4044 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4045 getF32Constant(DAG, 0xbc91e5ac));
4046 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4047 getF32Constant(DAG, 0x3e4350aa));
4048 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4049 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4050 getF32Constant(DAG, 0x3f60d3e3));
4051 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4052 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4053 getF32Constant(DAG, 0x4011cdf0));
4054 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4055 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4056 getF32Constant(DAG, 0x406cfd1c));
4057 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4058 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4059 getF32Constant(DAG, 0x408797cb));
4060 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4061 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4062 getF32Constant(DAG, 0x4006dcab));
4065 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4068 // No special expansion.
4069 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4072 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4073 /// limited-precision mode.
4074 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4075 const TargetLowering &TLI) {
4076 if (Op.getValueType() == MVT::f32 &&
4077 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4078 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4080 // Get the exponent.
4081 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4083 // Get the significand and build it into a floating-point number with
4085 SDValue X = GetSignificand(DAG, Op1, dl);
4087 // Different possible minimax approximations of significand in
4088 // floating-point for various degrees of accuracy over [1,2].
4089 SDValue Log2ofMantissa;
4090 if (LimitFloatPrecision <= 6) {
4091 // For floating-point precision of 6:
4093 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4095 // error 0.0049451742, which is more than 7 bits
4096 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4097 getF32Constant(DAG, 0xbeb08fe0));
4098 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4099 getF32Constant(DAG, 0x40019463));
4100 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4101 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4102 getF32Constant(DAG, 0x3fd6633d));
4103 } else if (LimitFloatPrecision <= 12) {
4104 // For floating-point precision of 12:
4110 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4112 // error 0.0000876136000, which is better than 13 bits
4113 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4114 getF32Constant(DAG, 0xbda7262e));
4115 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4116 getF32Constant(DAG, 0x3f25280b));
4117 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4118 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4119 getF32Constant(DAG, 0x4007b923));
4120 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4121 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4122 getF32Constant(DAG, 0x40823e2f));
4123 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4124 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4125 getF32Constant(DAG, 0x4020d29c));
4126 } else { // LimitFloatPrecision <= 18
4127 // For floating-point precision of 18:
4136 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4138 // error 0.0000018516, which is better than 18 bits
4139 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4140 getF32Constant(DAG, 0xbcd2769e));
4141 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4142 getF32Constant(DAG, 0x3e8ce0b9));
4143 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4144 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4145 getF32Constant(DAG, 0x3fa22ae7));
4146 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4147 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4148 getF32Constant(DAG, 0x40525723));
4149 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4150 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4151 getF32Constant(DAG, 0x40aaf200));
4152 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4153 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4154 getF32Constant(DAG, 0x40c39dad));
4155 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4156 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4157 getF32Constant(DAG, 0x4042902c));
4160 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4163 // No special expansion.
4164 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4167 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4168 /// limited-precision mode.
4169 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4170 const TargetLowering &TLI) {
4171 if (Op.getValueType() == MVT::f32 &&
4172 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4173 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4175 // Scale the exponent by log10(2) [0.30102999f].
4176 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4177 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4178 getF32Constant(DAG, 0x3e9a209a));
4180 // Get the significand and build it into a floating-point number with
4182 SDValue X = GetSignificand(DAG, Op1, dl);
4184 SDValue Log10ofMantissa;
4185 if (LimitFloatPrecision <= 6) {
4186 // For floating-point precision of 6:
4188 // Log10ofMantissa =
4190 // (0.60948995f - 0.10380950f * x) * x;
4192 // error 0.0014886165, which is 6 bits
4193 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4194 getF32Constant(DAG, 0xbdd49a13));
4195 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4196 getF32Constant(DAG, 0x3f1c0789));
4197 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4198 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4199 getF32Constant(DAG, 0x3f011300));
4200 } else if (LimitFloatPrecision <= 12) {
4201 // For floating-point precision of 12:
4203 // Log10ofMantissa =
4206 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4208 // error 0.00019228036, which is better than 12 bits
4209 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4210 getF32Constant(DAG, 0x3d431f31));
4211 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4212 getF32Constant(DAG, 0x3ea21fb2));
4213 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4214 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4215 getF32Constant(DAG, 0x3f6ae232));
4216 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4217 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4218 getF32Constant(DAG, 0x3f25f7c3));
4219 } else { // LimitFloatPrecision <= 18
4220 // For floating-point precision of 18:
4222 // Log10ofMantissa =
4227 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4229 // error 0.0000037995730, which is better than 18 bits
4230 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4231 getF32Constant(DAG, 0x3c5d51ce));
4232 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4233 getF32Constant(DAG, 0x3e00685a));
4234 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4235 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4236 getF32Constant(DAG, 0x3efb6798));
4237 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4238 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4239 getF32Constant(DAG, 0x3f88d192));
4240 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4241 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4242 getF32Constant(DAG, 0x3fc4316c));
4243 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4244 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4245 getF32Constant(DAG, 0x3f57ce70));
4248 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4251 // No special expansion.
4252 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4255 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4256 /// limited-precision mode.
4257 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4258 const TargetLowering &TLI) {
4259 if (Op.getValueType() == MVT::f32 &&
4260 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4261 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
4263 // FractionalPartOfX = x - (float)IntegerPartOfX;
4264 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4265 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
4267 // IntegerPartOfX <<= 23;
4268 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4269 DAG.getConstant(23, TLI.getPointerTy()));
4271 SDValue TwoToFractionalPartOfX;
4272 if (LimitFloatPrecision <= 6) {
4273 // For floating-point precision of 6:
4275 // TwoToFractionalPartOfX =
4277 // (0.735607626f + 0.252464424f * x) * x;
4279 // error 0.0144103317, which is 6 bits
4280 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4281 getF32Constant(DAG, 0x3e814304));
4282 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4283 getF32Constant(DAG, 0x3f3c50c8));
4284 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4285 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4286 getF32Constant(DAG, 0x3f7f5e7e));
4287 } else if (LimitFloatPrecision <= 12) {
4288 // For floating-point precision of 12:
4290 // TwoToFractionalPartOfX =
4293 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4295 // error 0.000107046256, which is 13 to 14 bits
4296 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4297 getF32Constant(DAG, 0x3da235e3));
4298 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4299 getF32Constant(DAG, 0x3e65b8f3));
4300 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4301 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4302 getF32Constant(DAG, 0x3f324b07));
4303 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4304 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4305 getF32Constant(DAG, 0x3f7ff8fd));
4306 } else { // LimitFloatPrecision <= 18
4307 // For floating-point precision of 18:
4309 // TwoToFractionalPartOfX =
4313 // (0.554906021e-1f +
4314 // (0.961591928e-2f +
4315 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4316 // error 2.47208000*10^(-7), which is better than 18 bits
4317 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4318 getF32Constant(DAG, 0x3924b03e));
4319 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4320 getF32Constant(DAG, 0x3ab24b87));
4321 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4322 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4323 getF32Constant(DAG, 0x3c1d8c17));
4324 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4325 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4326 getF32Constant(DAG, 0x3d634a1d));
4327 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4328 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4329 getF32Constant(DAG, 0x3e75fe14));
4330 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4331 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4332 getF32Constant(DAG, 0x3f317234));
4333 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4334 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4335 getF32Constant(DAG, 0x3f800000));
4338 // Add the exponent into the result in integer domain.
4339 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4340 TwoToFractionalPartOfX);
4341 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4342 DAG.getNode(ISD::ADD, dl, MVT::i32,
4343 t13, IntegerPartOfX));
4346 // No special expansion.
4347 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4350 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4351 /// limited-precision mode with x == 10.0f.
4352 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4353 SelectionDAG &DAG, const TargetLowering &TLI) {
4354 bool IsExp10 = false;
4355 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4356 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4357 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4359 IsExp10 = LHSC->isExactlyValue(Ten);
4364 // Put the exponent in the right bit position for later addition to the
4367 // #define LOG2OF10 3.3219281f
4368 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4369 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4370 getF32Constant(DAG, 0x40549a78));
4371 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4373 // FractionalPartOfX = x - (float)IntegerPartOfX;
4374 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4375 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4377 // IntegerPartOfX <<= 23;
4378 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4379 DAG.getConstant(23, TLI.getPointerTy()));
4381 SDValue TwoToFractionalPartOfX;
4382 if (LimitFloatPrecision <= 6) {
4383 // For floating-point precision of 6:
4385 // twoToFractionalPartOfX =
4387 // (0.735607626f + 0.252464424f * x) * x;
4389 // error 0.0144103317, which is 6 bits
4390 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4391 getF32Constant(DAG, 0x3e814304));
4392 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4393 getF32Constant(DAG, 0x3f3c50c8));
4394 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4395 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4396 getF32Constant(DAG, 0x3f7f5e7e));
4397 } else if (LimitFloatPrecision <= 12) {
4398 // For floating-point precision of 12:
4400 // TwoToFractionalPartOfX =
4403 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4405 // error 0.000107046256, which is 13 to 14 bits
4406 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4407 getF32Constant(DAG, 0x3da235e3));
4408 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4409 getF32Constant(DAG, 0x3e65b8f3));
4410 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4411 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4412 getF32Constant(DAG, 0x3f324b07));
4413 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4414 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4415 getF32Constant(DAG, 0x3f7ff8fd));
4416 } else { // LimitFloatPrecision <= 18
4417 // For floating-point precision of 18:
4419 // TwoToFractionalPartOfX =
4423 // (0.554906021e-1f +
4424 // (0.961591928e-2f +
4425 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4426 // error 2.47208000*10^(-7), which is better than 18 bits
4427 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4428 getF32Constant(DAG, 0x3924b03e));
4429 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4430 getF32Constant(DAG, 0x3ab24b87));
4431 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4432 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4433 getF32Constant(DAG, 0x3c1d8c17));
4434 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4435 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4436 getF32Constant(DAG, 0x3d634a1d));
4437 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4438 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4439 getF32Constant(DAG, 0x3e75fe14));
4440 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4441 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4442 getF32Constant(DAG, 0x3f317234));
4443 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4444 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4445 getF32Constant(DAG, 0x3f800000));
4448 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
4449 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4450 DAG.getNode(ISD::ADD, dl, MVT::i32,
4451 t13, IntegerPartOfX));
4454 // No special expansion.
4455 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4459 /// ExpandPowI - Expand a llvm.powi intrinsic.
4460 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4461 SelectionDAG &DAG) {
4462 // If RHS is a constant, we can expand this out to a multiplication tree,
4463 // otherwise we end up lowering to a call to __powidf2 (for example). When
4464 // optimizing for size, we only want to do this if the expansion would produce
4465 // a small number of multiplies, otherwise we do the full expansion.
4466 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4467 // Get the exponent as a positive value.
4468 unsigned Val = RHSC->getSExtValue();
4469 if ((int)Val < 0) Val = -Val;
4471 // powi(x, 0) -> 1.0
4473 return DAG.getConstantFP(1.0, LHS.getValueType());
4475 const Function *F = DAG.getMachineFunction().getFunction();
4476 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4477 Attribute::OptimizeForSize) ||
4478 // If optimizing for size, don't insert too many multiplies. This
4479 // inserts up to 5 multiplies.
4480 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4481 // We use the simple binary decomposition method to generate the multiply
4482 // sequence. There are more optimal ways to do this (for example,
4483 // powi(x,15) generates one more multiply than it should), but this has
4484 // the benefit of being both really simple and much better than a libcall.
4485 SDValue Res; // Logically starts equal to 1.0
4486 SDValue CurSquare = LHS;
4490 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4492 Res = CurSquare; // 1.0*CurSquare.
4495 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4496 CurSquare, CurSquare);
4500 // If the original was negative, invert the result, producing 1/(x*x*x).
4501 if (RHSC->getSExtValue() < 0)
4502 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4503 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4508 // Otherwise, expand to a libcall.
4509 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4512 // getTruncatedArgReg - Find underlying register used for an truncated
4514 static unsigned getTruncatedArgReg(const SDValue &N) {
4515 if (N.getOpcode() != ISD::TRUNCATE)
4518 const SDValue &Ext = N.getOperand(0);
4519 if (Ext.getOpcode() == ISD::AssertZext ||
4520 Ext.getOpcode() == ISD::AssertSext) {
4521 const SDValue &CFR = Ext.getOperand(0);
4522 if (CFR.getOpcode() == ISD::CopyFromReg)
4523 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4524 if (CFR.getOpcode() == ISD::TRUNCATE)
4525 return getTruncatedArgReg(CFR);
4530 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4531 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4532 /// At the end of instruction selection, they will be inserted to the entry BB.
4534 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
4537 const Argument *Arg = dyn_cast<Argument>(V);
4541 MachineFunction &MF = DAG.getMachineFunction();
4542 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4544 // Ignore inlined function arguments here.
4545 DIVariable DV(Variable);
4546 if (DV.isInlinedFnArgument(MF.getFunction()))
4549 Optional<MachineOperand> Op;
4550 // Some arguments' frame index is recorded during argument lowering.
4551 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4552 Op = MachineOperand::CreateFI(FI);
4554 if (!Op && N.getNode()) {
4556 if (N.getOpcode() == ISD::CopyFromReg)
4557 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4559 Reg = getTruncatedArgReg(N);
4560 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4561 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4562 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4567 Op = MachineOperand::CreateReg(Reg, false);
4571 // Check if ValueMap has reg number.
4572 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4573 if (VMI != FuncInfo.ValueMap.end())
4574 Op = MachineOperand::CreateReg(VMI->second, false);
4577 if (!Op && N.getNode())
4578 // Check if frame index is available.
4579 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4580 if (FrameIndexSDNode *FINode =
4581 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4582 Op = MachineOperand::CreateFI(FINode->getIndex());
4587 // FIXME: This does not handle register-indirect values at offset 0.
4588 bool IsIndirect = Offset != 0;
4590 FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(),
4591 TII->get(TargetOpcode::DBG_VALUE),
4593 Op->getReg(), Offset, Variable));
4595 FuncInfo.ArgDbgValues.push_back(
4596 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4597 .addOperand(*Op).addImm(Offset).addMetadata(Variable));
4602 // VisualStudio defines setjmp as _setjmp
4603 #if defined(_MSC_VER) && defined(setjmp) && \
4604 !defined(setjmp_undefined_for_msvc)
4605 # pragma push_macro("setjmp")
4607 # define setjmp_undefined_for_msvc
4610 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4611 /// we want to emit this as a call to a named external function, return the name
4612 /// otherwise lower it and return null.
4614 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4615 const TargetLowering *TLI = TM.getTargetLowering();
4616 SDLoc sdl = getCurSDLoc();
4617 DebugLoc dl = getCurDebugLoc();
4620 switch (Intrinsic) {
4622 // By default, turn this into a target intrinsic node.
4623 visitTargetIntrinsic(I, Intrinsic);
4625 case Intrinsic::vastart: visitVAStart(I); return 0;
4626 case Intrinsic::vaend: visitVAEnd(I); return 0;
4627 case Intrinsic::vacopy: visitVACopy(I); return 0;
4628 case Intrinsic::returnaddress:
4629 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(),
4630 getValue(I.getArgOperand(0))));
4632 case Intrinsic::frameaddress:
4633 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(),
4634 getValue(I.getArgOperand(0))));
4636 case Intrinsic::setjmp:
4637 return &"_setjmp"[!TLI->usesUnderscoreSetJmp()];
4638 case Intrinsic::longjmp:
4639 return &"_longjmp"[!TLI->usesUnderscoreLongJmp()];
4640 case Intrinsic::memcpy: {
4641 // Assert for address < 256 since we support only user defined address
4643 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4645 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4647 "Unknown address space");
4648 SDValue Op1 = getValue(I.getArgOperand(0));
4649 SDValue Op2 = getValue(I.getArgOperand(1));
4650 SDValue Op3 = getValue(I.getArgOperand(2));
4651 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4653 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4654 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4655 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
4656 MachinePointerInfo(I.getArgOperand(0)),
4657 MachinePointerInfo(I.getArgOperand(1))));
4660 case Intrinsic::memset: {
4661 // Assert for address < 256 since we support only user defined address
4663 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4665 "Unknown address space");
4666 SDValue Op1 = getValue(I.getArgOperand(0));
4667 SDValue Op2 = getValue(I.getArgOperand(1));
4668 SDValue Op3 = getValue(I.getArgOperand(2));
4669 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4671 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4672 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4673 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4674 MachinePointerInfo(I.getArgOperand(0))));
4677 case Intrinsic::memmove: {
4678 // Assert for address < 256 since we support only user defined address
4680 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4682 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4684 "Unknown address space");
4685 SDValue Op1 = getValue(I.getArgOperand(0));
4686 SDValue Op2 = getValue(I.getArgOperand(1));
4687 SDValue Op3 = getValue(I.getArgOperand(2));
4688 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4690 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4691 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4692 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4693 MachinePointerInfo(I.getArgOperand(0)),
4694 MachinePointerInfo(I.getArgOperand(1))));
4697 case Intrinsic::dbg_declare: {
4698 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4699 MDNode *Variable = DI.getVariable();
4700 const Value *Address = DI.getAddress();
4701 DIVariable DIVar(Variable);
4702 assert((!DIVar || DIVar.isVariable()) &&
4703 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4704 if (!Address || !DIVar) {
4705 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4709 // Check if address has undef value.
4710 if (isa<UndefValue>(Address) ||
4711 (Address->use_empty() && !isa<Argument>(Address))) {
4712 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4716 SDValue &N = NodeMap[Address];
4717 if (!N.getNode() && isa<Argument>(Address))
4718 // Check unused arguments map.
4719 N = UnusedArgNodeMap[Address];
4722 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4723 Address = BCI->getOperand(0);
4724 // Parameters are handled specially.
4726 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4727 isa<Argument>(Address));
4729 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4731 if (isParameter && !AI) {
4732 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4734 // Byval parameter. We have a frame index at this point.
4735 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4736 0, dl, SDNodeOrder);
4738 // Address is an argument, so try to emit its dbg value using
4739 // virtual register info from the FuncInfo.ValueMap.
4740 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
4744 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4745 0, dl, SDNodeOrder);
4747 // Can't do anything with other non-AI cases yet.
4748 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4749 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4750 DEBUG(Address->dump());
4753 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4755 // If Address is an argument then try to emit its dbg value using
4756 // virtual register info from the FuncInfo.ValueMap.
4757 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
4758 // If variable is pinned by a alloca in dominating bb then
4759 // use StaticAllocaMap.
4760 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4761 if (AI->getParent() != DI.getParent()) {
4762 DenseMap<const AllocaInst*, int>::iterator SI =
4763 FuncInfo.StaticAllocaMap.find(AI);
4764 if (SI != FuncInfo.StaticAllocaMap.end()) {
4765 SDV = DAG.getDbgValue(Variable, SI->second,
4766 0, dl, SDNodeOrder);
4767 DAG.AddDbgValue(SDV, 0, false);
4772 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4777 case Intrinsic::dbg_value: {
4778 const DbgValueInst &DI = cast<DbgValueInst>(I);
4779 DIVariable DIVar(DI.getVariable());
4780 assert((!DIVar || DIVar.isVariable()) &&
4781 "Variable in DbgValueInst should be either null or a DIVariable.");
4785 MDNode *Variable = DI.getVariable();
4786 uint64_t Offset = DI.getOffset();
4787 const Value *V = DI.getValue();
4792 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4793 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4794 DAG.AddDbgValue(SDV, 0, false);
4796 // Do not use getValue() in here; we don't want to generate code at
4797 // this point if it hasn't been done yet.
4798 SDValue N = NodeMap[V];
4799 if (!N.getNode() && isa<Argument>(V))
4800 // Check unused arguments map.
4801 N = UnusedArgNodeMap[V];
4803 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
4804 SDV = DAG.getDbgValue(Variable, N.getNode(),
4805 N.getResNo(), Offset, dl, SDNodeOrder);
4806 DAG.AddDbgValue(SDV, N.getNode(), false);
4808 } else if (!V->use_empty() ) {
4809 // Do not call getValue(V) yet, as we don't want to generate code.
4810 // Remember it for later.
4811 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4812 DanglingDebugInfoMap[V] = DDI;
4814 // We may expand this to cover more cases. One case where we have no
4815 // data available is an unreferenced parameter.
4816 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4820 // Build a debug info table entry.
4821 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4822 V = BCI->getOperand(0);
4823 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4824 // Don't handle byval struct arguments or VLAs, for example.
4826 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4827 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
4830 DenseMap<const AllocaInst*, int>::iterator SI =
4831 FuncInfo.StaticAllocaMap.find(AI);
4832 if (SI == FuncInfo.StaticAllocaMap.end())
4834 int FI = SI->second;
4836 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4837 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4838 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4842 case Intrinsic::eh_typeid_for: {
4843 // Find the type id for the given typeinfo.
4844 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4845 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4846 Res = DAG.getConstant(TypeID, MVT::i32);
4851 case Intrinsic::eh_return_i32:
4852 case Intrinsic::eh_return_i64:
4853 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4854 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4857 getValue(I.getArgOperand(0)),
4858 getValue(I.getArgOperand(1))));
4860 case Intrinsic::eh_unwind_init:
4861 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4863 case Intrinsic::eh_dwarf_cfa: {
4864 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4865 TLI->getPointerTy());
4866 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4867 CfaArg.getValueType(),
4868 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4869 CfaArg.getValueType()),
4871 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl,
4872 TLI->getPointerTy(),
4873 DAG.getConstant(0, TLI->getPointerTy()));
4874 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4878 case Intrinsic::eh_sjlj_callsite: {
4879 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4880 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4881 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4882 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4884 MMI.setCurrentCallSite(CI->getZExtValue());
4887 case Intrinsic::eh_sjlj_functioncontext: {
4888 // Get and store the index of the function context.
4889 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4891 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4892 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4893 MFI->setFunctionContextIndex(FI);
4896 case Intrinsic::eh_sjlj_setjmp: {
4899 Ops[1] = getValue(I.getArgOperand(0));
4900 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4901 DAG.getVTList(MVT::i32, MVT::Other),
4903 setValue(&I, Op.getValue(0));
4904 DAG.setRoot(Op.getValue(1));
4907 case Intrinsic::eh_sjlj_longjmp: {
4908 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4909 getRoot(), getValue(I.getArgOperand(0))));
4913 case Intrinsic::x86_mmx_pslli_w:
4914 case Intrinsic::x86_mmx_pslli_d:
4915 case Intrinsic::x86_mmx_pslli_q:
4916 case Intrinsic::x86_mmx_psrli_w:
4917 case Intrinsic::x86_mmx_psrli_d:
4918 case Intrinsic::x86_mmx_psrli_q:
4919 case Intrinsic::x86_mmx_psrai_w:
4920 case Intrinsic::x86_mmx_psrai_d: {
4921 SDValue ShAmt = getValue(I.getArgOperand(1));
4922 if (isa<ConstantSDNode>(ShAmt)) {
4923 visitTargetIntrinsic(I, Intrinsic);
4926 unsigned NewIntrinsic = 0;
4927 EVT ShAmtVT = MVT::v2i32;
4928 switch (Intrinsic) {
4929 case Intrinsic::x86_mmx_pslli_w:
4930 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4932 case Intrinsic::x86_mmx_pslli_d:
4933 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4935 case Intrinsic::x86_mmx_pslli_q:
4936 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4938 case Intrinsic::x86_mmx_psrli_w:
4939 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4941 case Intrinsic::x86_mmx_psrli_d:
4942 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4944 case Intrinsic::x86_mmx_psrli_q:
4945 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4947 case Intrinsic::x86_mmx_psrai_w:
4948 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4950 case Intrinsic::x86_mmx_psrai_d:
4951 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4953 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4956 // The vector shift intrinsics with scalars uses 32b shift amounts but
4957 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4959 // We must do this early because v2i32 is not a legal type.
4962 ShOps[1] = DAG.getConstant(0, MVT::i32);
4963 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, &ShOps[0], 2);
4964 EVT DestVT = TLI->getValueType(I.getType());
4965 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4966 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4967 DAG.getConstant(NewIntrinsic, MVT::i32),
4968 getValue(I.getArgOperand(0)), ShAmt);
4972 case Intrinsic::x86_avx_vinsertf128_pd_256:
4973 case Intrinsic::x86_avx_vinsertf128_ps_256:
4974 case Intrinsic::x86_avx_vinsertf128_si_256:
4975 case Intrinsic::x86_avx2_vinserti128: {
4976 EVT DestVT = TLI->getValueType(I.getType());
4977 EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType());
4978 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4979 ElVT.getVectorNumElements();
4980 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
4981 getValue(I.getArgOperand(0)),
4982 getValue(I.getArgOperand(1)),
4983 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
4987 case Intrinsic::x86_avx_vextractf128_pd_256:
4988 case Intrinsic::x86_avx_vextractf128_ps_256:
4989 case Intrinsic::x86_avx_vextractf128_si_256:
4990 case Intrinsic::x86_avx2_vextracti128: {
4991 EVT DestVT = TLI->getValueType(I.getType());
4992 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
4993 DestVT.getVectorNumElements();
4994 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
4995 getValue(I.getArgOperand(0)),
4996 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
5000 case Intrinsic::convertff:
5001 case Intrinsic::convertfsi:
5002 case Intrinsic::convertfui:
5003 case Intrinsic::convertsif:
5004 case Intrinsic::convertuif:
5005 case Intrinsic::convertss:
5006 case Intrinsic::convertsu:
5007 case Intrinsic::convertus:
5008 case Intrinsic::convertuu: {
5009 ISD::CvtCode Code = ISD::CVT_INVALID;
5010 switch (Intrinsic) {
5011 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5012 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
5013 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
5014 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
5015 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
5016 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
5017 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
5018 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
5019 case Intrinsic::convertus: Code = ISD::CVT_US; break;
5020 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
5022 EVT DestVT = TLI->getValueType(I.getType());
5023 const Value *Op1 = I.getArgOperand(0);
5024 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
5025 DAG.getValueType(DestVT),
5026 DAG.getValueType(getValue(Op1).getValueType()),
5027 getValue(I.getArgOperand(1)),
5028 getValue(I.getArgOperand(2)),
5033 case Intrinsic::powi:
5034 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5035 getValue(I.getArgOperand(1)), DAG));
5037 case Intrinsic::log:
5038 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
5040 case Intrinsic::log2:
5041 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
5043 case Intrinsic::log10:
5044 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
5046 case Intrinsic::exp:
5047 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
5049 case Intrinsic::exp2:
5050 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
5052 case Intrinsic::pow:
5053 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5054 getValue(I.getArgOperand(1)), DAG, *TLI));
5056 case Intrinsic::sqrt:
5057 case Intrinsic::fabs:
5058 case Intrinsic::sin:
5059 case Intrinsic::cos:
5060 case Intrinsic::floor:
5061 case Intrinsic::ceil:
5062 case Intrinsic::trunc:
5063 case Intrinsic::rint:
5064 case Intrinsic::nearbyint:
5065 case Intrinsic::round: {
5067 switch (Intrinsic) {
5068 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5069 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5070 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5071 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5072 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5073 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5074 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5075 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5076 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5077 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5078 case Intrinsic::round: Opcode = ISD::FROUND; break;
5081 setValue(&I, DAG.getNode(Opcode, sdl,
5082 getValue(I.getArgOperand(0)).getValueType(),
5083 getValue(I.getArgOperand(0))));
5086 case Intrinsic::copysign:
5087 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5088 getValue(I.getArgOperand(0)).getValueType(),
5089 getValue(I.getArgOperand(0)),
5090 getValue(I.getArgOperand(1))));
5092 case Intrinsic::fma:
5093 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5094 getValue(I.getArgOperand(0)).getValueType(),
5095 getValue(I.getArgOperand(0)),
5096 getValue(I.getArgOperand(1)),
5097 getValue(I.getArgOperand(2))));
5099 case Intrinsic::fmuladd: {
5100 EVT VT = TLI->getValueType(I.getType());
5101 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5102 TLI->isFMAFasterThanFMulAndFAdd(VT)) {
5103 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5104 getValue(I.getArgOperand(0)).getValueType(),
5105 getValue(I.getArgOperand(0)),
5106 getValue(I.getArgOperand(1)),
5107 getValue(I.getArgOperand(2))));
5109 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5110 getValue(I.getArgOperand(0)).getValueType(),
5111 getValue(I.getArgOperand(0)),
5112 getValue(I.getArgOperand(1)));
5113 SDValue Add = DAG.getNode(ISD::FADD, sdl,
5114 getValue(I.getArgOperand(0)).getValueType(),
5116 getValue(I.getArgOperand(2)));
5121 case Intrinsic::convert_to_fp16:
5122 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, sdl,
5123 MVT::i16, getValue(I.getArgOperand(0))));
5125 case Intrinsic::convert_from_fp16:
5126 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, sdl,
5127 MVT::f32, getValue(I.getArgOperand(0))));
5129 case Intrinsic::pcmarker: {
5130 SDValue Tmp = getValue(I.getArgOperand(0));
5131 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5134 case Intrinsic::readcyclecounter: {
5135 SDValue Op = getRoot();
5136 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5137 DAG.getVTList(MVT::i64, MVT::Other),
5140 DAG.setRoot(Res.getValue(1));
5143 case Intrinsic::bswap:
5144 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5145 getValue(I.getArgOperand(0)).getValueType(),
5146 getValue(I.getArgOperand(0))));
5148 case Intrinsic::cttz: {
5149 SDValue Arg = getValue(I.getArgOperand(0));
5150 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5151 EVT Ty = Arg.getValueType();
5152 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5156 case Intrinsic::ctlz: {
5157 SDValue Arg = getValue(I.getArgOperand(0));
5158 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5159 EVT Ty = Arg.getValueType();
5160 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5164 case Intrinsic::ctpop: {
5165 SDValue Arg = getValue(I.getArgOperand(0));
5166 EVT Ty = Arg.getValueType();
5167 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5170 case Intrinsic::stacksave: {
5171 SDValue Op = getRoot();
5172 Res = DAG.getNode(ISD::STACKSAVE, sdl,
5173 DAG.getVTList(TLI->getPointerTy(), MVT::Other), &Op, 1);
5175 DAG.setRoot(Res.getValue(1));
5178 case Intrinsic::stackrestore: {
5179 Res = getValue(I.getArgOperand(0));
5180 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5183 case Intrinsic::stackprotector: {
5184 // Emit code into the DAG to store the stack guard onto the stack.
5185 MachineFunction &MF = DAG.getMachineFunction();
5186 MachineFrameInfo *MFI = MF.getFrameInfo();
5187 EVT PtrTy = TLI->getPointerTy();
5189 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
5190 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5192 int FI = FuncInfo.StaticAllocaMap[Slot];
5193 MFI->setStackProtectorIndex(FI);
5195 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5197 // Store the stack protector onto the stack.
5198 Res = DAG.getStore(getRoot(), sdl, Src, FIN,
5199 MachinePointerInfo::getFixedStack(FI),
5205 case Intrinsic::objectsize: {
5206 // If we don't know by now, we're never going to know.
5207 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5209 assert(CI && "Non-constant type in __builtin_object_size?");
5211 SDValue Arg = getValue(I.getCalledValue());
5212 EVT Ty = Arg.getValueType();
5215 Res = DAG.getConstant(-1ULL, Ty);
5217 Res = DAG.getConstant(0, Ty);
5222 case Intrinsic::annotation:
5223 case Intrinsic::ptr_annotation:
5224 // Drop the intrinsic, but forward the value
5225 setValue(&I, getValue(I.getOperand(0)));
5227 case Intrinsic::var_annotation:
5228 // Discard annotate attributes
5231 case Intrinsic::init_trampoline: {
5232 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5236 Ops[1] = getValue(I.getArgOperand(0));
5237 Ops[2] = getValue(I.getArgOperand(1));
5238 Ops[3] = getValue(I.getArgOperand(2));
5239 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5240 Ops[5] = DAG.getSrcValue(F);
5242 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops, 6);
5247 case Intrinsic::adjust_trampoline: {
5248 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5249 TLI->getPointerTy(),
5250 getValue(I.getArgOperand(0))));
5253 case Intrinsic::gcroot:
5255 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5256 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5258 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5259 GFI->addStackRoot(FI->getIndex(), TypeMap);
5262 case Intrinsic::gcread:
5263 case Intrinsic::gcwrite:
5264 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5265 case Intrinsic::flt_rounds:
5266 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5269 case Intrinsic::expect: {
5270 // Just replace __builtin_expect(exp, c) with EXP.
5271 setValue(&I, getValue(I.getArgOperand(0)));
5275 case Intrinsic::debugtrap:
5276 case Intrinsic::trap: {
5277 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
5278 if (TrapFuncName.empty()) {
5279 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5280 ISD::TRAP : ISD::DEBUGTRAP;
5281 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5284 TargetLowering::ArgListTy Args;
5286 CallLoweringInfo CLI(getRoot(), I.getType(),
5287 false, false, false, false, 0, CallingConv::C,
5288 /*isTailCall=*/false,
5289 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
5290 DAG.getExternalSymbol(TrapFuncName.data(),
5291 TLI->getPointerTy()),
5293 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
5294 DAG.setRoot(Result.second);
5298 case Intrinsic::uadd_with_overflow:
5299 case Intrinsic::sadd_with_overflow:
5300 case Intrinsic::usub_with_overflow:
5301 case Intrinsic::ssub_with_overflow:
5302 case Intrinsic::umul_with_overflow:
5303 case Intrinsic::smul_with_overflow: {
5305 switch (Intrinsic) {
5306 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5307 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5308 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5309 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5310 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5311 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5312 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5314 SDValue Op1 = getValue(I.getArgOperand(0));
5315 SDValue Op2 = getValue(I.getArgOperand(1));
5317 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5318 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5321 case Intrinsic::prefetch: {
5323 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5325 Ops[1] = getValue(I.getArgOperand(0));
5326 Ops[2] = getValue(I.getArgOperand(1));
5327 Ops[3] = getValue(I.getArgOperand(2));
5328 Ops[4] = getValue(I.getArgOperand(3));
5329 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5330 DAG.getVTList(MVT::Other),
5332 EVT::getIntegerVT(*Context, 8),
5333 MachinePointerInfo(I.getArgOperand(0)),
5335 false, /* volatile */
5337 rw==1)); /* write */
5340 case Intrinsic::lifetime_start:
5341 case Intrinsic::lifetime_end: {
5342 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5343 // Stack coloring is not enabled in O0, discard region information.
5344 if (TM.getOptLevel() == CodeGenOpt::None)
5347 SmallVector<Value *, 4> Allocas;
5348 GetUnderlyingObjects(I.getArgOperand(1), Allocas, DL);
5350 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5351 E = Allocas.end(); Object != E; ++Object) {
5352 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5354 // Could not find an Alloca.
5355 if (!LifetimeObject)
5358 int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
5362 Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true);
5363 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5365 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops, 2);
5370 case Intrinsic::invariant_start:
5371 // Discard region information.
5372 setValue(&I, DAG.getUNDEF(TLI->getPointerTy()));
5374 case Intrinsic::invariant_end:
5375 // Discard region information.
5377 case Intrinsic::stackprotectorcheck: {
5378 // Do not actually emit anything for this basic block. Instead we initialize
5379 // the stack protector descriptor and export the guard variable so we can
5380 // access it in FinishBasicBlock.
5381 const BasicBlock *BB = I.getParent();
5382 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5383 ExportFromCurrentBlock(SPDescriptor.getGuard());
5385 // Flush our exports since we are going to process a terminator.
5386 (void)getControlRoot();
5389 case Intrinsic::donothing:
5392 case Intrinsic::experimental_stackmap: {
5396 case Intrinsic::experimental_patchpoint_void:
5397 case Intrinsic::experimental_patchpoint_i64: {
5404 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5406 MachineBasicBlock *LandingPad) {
5407 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5408 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5409 Type *RetTy = FTy->getReturnType();
5410 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5411 MCSymbol *BeginLabel = 0;
5413 TargetLowering::ArgListTy Args;
5414 TargetLowering::ArgListEntry Entry;
5415 Args.reserve(CS.arg_size());
5417 // Check whether the function can return without sret-demotion.
5418 SmallVector<ISD::OutputArg, 4> Outs;
5419 const TargetLowering *TLI = TM.getTargetLowering();
5420 GetReturnInfo(RetTy, CS.getAttributes(), Outs, *TLI);
5422 bool CanLowerReturn = TLI->CanLowerReturn(CS.getCallingConv(),
5423 DAG.getMachineFunction(),
5424 FTy->isVarArg(), Outs,
5427 SDValue DemoteStackSlot;
5428 int DemoteStackIdx = -100;
5430 if (!CanLowerReturn) {
5431 assert(!CS.hasInAllocaArgument() &&
5432 "sret demotion is incompatible with inalloca");
5433 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(
5434 FTy->getReturnType());
5435 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(
5436 FTy->getReturnType());
5437 MachineFunction &MF = DAG.getMachineFunction();
5438 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5439 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
5441 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI->getPointerTy());
5442 Entry.Node = DemoteStackSlot;
5443 Entry.Ty = StackSlotPtrType;
5444 Entry.isSExt = false;
5445 Entry.isZExt = false;
5446 Entry.isInReg = false;
5447 Entry.isSRet = true;
5448 Entry.isNest = false;
5449 Entry.isByVal = false;
5450 Entry.isReturned = false;
5451 Entry.Alignment = Align;
5452 Args.push_back(Entry);
5453 RetTy = Type::getVoidTy(FTy->getContext());
5456 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5458 const Value *V = *i;
5461 if (V->getType()->isEmptyTy())
5464 SDValue ArgNode = getValue(V);
5465 Entry.Node = ArgNode; Entry.Ty = V->getType();
5467 // Skip the first return-type Attribute to get to params.
5468 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5469 Args.push_back(Entry);
5473 // Insert a label before the invoke call to mark the try range. This can be
5474 // used to detect deletion of the invoke via the MachineModuleInfo.
5475 BeginLabel = MMI.getContext().CreateTempSymbol();
5477 // For SjLj, keep track of which landing pads go with which invokes
5478 // so as to maintain the ordering of pads in the LSDA.
5479 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5480 if (CallSiteIndex) {
5481 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5482 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5484 // Now that the call site is handled, stop tracking it.
5485 MMI.setCurrentCallSite(0);
5488 // Both PendingLoads and PendingExports must be flushed here;
5489 // this call might not return.
5491 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5494 // Check if target-independent constraints permit a tail call here.
5495 // Target-dependent constraints are checked within TLI->LowerCallTo.
5496 if (isTailCall && !isInTailCallPosition(CS, *TLI))
5500 CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
5502 std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI);
5503 assert((isTailCall || Result.second.getNode()) &&
5504 "Non-null chain expected with non-tail call!");
5505 assert((Result.second.getNode() || !Result.first.getNode()) &&
5506 "Null value expected with tail call!");
5507 if (Result.first.getNode()) {
5508 setValue(CS.getInstruction(), Result.first);
5509 } else if (!CanLowerReturn && Result.second.getNode()) {
5510 // The instruction result is the result of loading from the
5511 // hidden sret parameter.
5512 SmallVector<EVT, 1> PVTs;
5513 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
5515 ComputeValueVTs(*TLI, PtrRetTy, PVTs);
5516 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5517 EVT PtrVT = PVTs[0];
5519 SmallVector<EVT, 4> RetTys;
5520 SmallVector<uint64_t, 4> Offsets;
5521 RetTy = FTy->getReturnType();
5522 ComputeValueVTs(*TLI, RetTy, RetTys, &Offsets);
5524 unsigned NumValues = RetTys.size();
5525 SmallVector<SDValue, 4> Values(NumValues);
5526 SmallVector<SDValue, 4> Chains(NumValues);
5528 for (unsigned i = 0; i < NumValues; ++i) {
5529 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT,
5531 DAG.getConstant(Offsets[i], PtrVT));
5532 SDValue L = DAG.getLoad(RetTys[i], getCurSDLoc(), Result.second, Add,
5533 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
5534 false, false, false, 1);
5536 Chains[i] = L.getValue(1);
5539 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
5540 MVT::Other, &Chains[0], NumValues);
5541 PendingLoads.push_back(Chain);
5543 setValue(CS.getInstruction(),
5544 DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
5545 DAG.getVTList(&RetTys[0], RetTys.size()),
5546 &Values[0], Values.size()));
5549 if (!Result.second.getNode()) {
5550 // As a special case, a null chain means that a tail call has been emitted
5551 // and the DAG root is already updated.
5554 // Since there's no actual continuation from this block, nothing can be
5555 // relying on us setting vregs for them.
5556 PendingExports.clear();
5558 DAG.setRoot(Result.second);
5562 // Insert a label at the end of the invoke call to mark the try range. This
5563 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5564 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5565 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5567 // Inform MachineModuleInfo of range.
5568 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5572 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5573 /// value is equal or not-equal to zero.
5574 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5575 for (const User *U : V->users()) {
5576 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5577 if (IC->isEquality())
5578 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5579 if (C->isNullValue())
5581 // Unknown instruction.
5587 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5589 SelectionDAGBuilder &Builder) {
5591 // Check to see if this load can be trivially constant folded, e.g. if the
5592 // input is from a string literal.
5593 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5594 // Cast pointer to the type we really want to load.
5595 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5596 PointerType::getUnqual(LoadTy));
5598 if (const Constant *LoadCst =
5599 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5601 return Builder.getValue(LoadCst);
5604 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5605 // still constant memory, the input chain can be the entry node.
5607 bool ConstantMemory = false;
5609 // Do not serialize (non-volatile) loads of constant memory with anything.
5610 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5611 Root = Builder.DAG.getEntryNode();
5612 ConstantMemory = true;
5614 // Do not serialize non-volatile loads against each other.
5615 Root = Builder.DAG.getRoot();
5618 SDValue Ptr = Builder.getValue(PtrVal);
5619 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5620 Ptr, MachinePointerInfo(PtrVal),
5622 false /*nontemporal*/,
5623 false /*isinvariant*/, 1 /* align=1 */);
5625 if (!ConstantMemory)
5626 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5630 /// processIntegerCallValue - Record the value for an instruction that
5631 /// produces an integer result, converting the type where necessary.
5632 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5635 EVT VT = TM.getTargetLowering()->getValueType(I.getType(), true);
5637 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5639 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5640 setValue(&I, Value);
5643 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5644 /// If so, return true and lower it, otherwise return false and it will be
5645 /// lowered like a normal call.
5646 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5647 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5648 if (I.getNumArgOperands() != 3)
5651 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5652 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5653 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5654 !I.getType()->isIntegerTy())
5657 const Value *Size = I.getArgOperand(2);
5658 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5659 if (CSize && CSize->getZExtValue() == 0) {
5660 EVT CallVT = TM.getTargetLowering()->getValueType(I.getType(), true);
5661 setValue(&I, DAG.getConstant(0, CallVT));
5665 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5666 std::pair<SDValue, SDValue> Res =
5667 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5668 getValue(LHS), getValue(RHS), getValue(Size),
5669 MachinePointerInfo(LHS),
5670 MachinePointerInfo(RHS));
5671 if (Res.first.getNode()) {
5672 processIntegerCallValue(I, Res.first, true);
5673 PendingLoads.push_back(Res.second);
5677 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5678 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5679 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5680 bool ActuallyDoIt = true;
5683 switch (CSize->getZExtValue()) {
5685 LoadVT = MVT::Other;
5687 ActuallyDoIt = false;
5691 LoadTy = Type::getInt16Ty(CSize->getContext());
5695 LoadTy = Type::getInt32Ty(CSize->getContext());
5699 LoadTy = Type::getInt64Ty(CSize->getContext());
5703 LoadVT = MVT::v4i32;
5704 LoadTy = Type::getInt32Ty(CSize->getContext());
5705 LoadTy = VectorType::get(LoadTy, 4);
5710 // This turns into unaligned loads. We only do this if the target natively
5711 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5712 // we'll only produce a small number of byte loads.
5714 // Require that we can find a legal MVT, and only do this if the target
5715 // supports unaligned loads of that type. Expanding into byte loads would
5717 const TargetLowering *TLI = TM.getTargetLowering();
5718 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5719 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5720 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5721 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5722 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5723 if (!TLI->isTypeLegal(LoadVT) ||
5724 !TLI->allowsUnalignedMemoryAccesses(LoadVT, SrcAS) ||
5725 !TLI->allowsUnalignedMemoryAccesses(LoadVT, DstAS))
5726 ActuallyDoIt = false;
5730 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5731 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5733 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5735 processIntegerCallValue(I, Res, false);
5744 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5745 /// form. If so, return true and lower it, otherwise return false and it
5746 /// will be lowered like a normal call.
5747 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5748 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5749 if (I.getNumArgOperands() != 3)
5752 const Value *Src = I.getArgOperand(0);
5753 const Value *Char = I.getArgOperand(1);
5754 const Value *Length = I.getArgOperand(2);
5755 if (!Src->getType()->isPointerTy() ||
5756 !Char->getType()->isIntegerTy() ||
5757 !Length->getType()->isIntegerTy() ||
5758 !I.getType()->isPointerTy())
5761 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5762 std::pair<SDValue, SDValue> Res =
5763 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5764 getValue(Src), getValue(Char), getValue(Length),
5765 MachinePointerInfo(Src));
5766 if (Res.first.getNode()) {
5767 setValue(&I, Res.first);
5768 PendingLoads.push_back(Res.second);
5775 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5776 /// optimized form. If so, return true and lower it, otherwise return false
5777 /// and it will be lowered like a normal call.
5778 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5779 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5780 if (I.getNumArgOperands() != 2)
5783 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5784 if (!Arg0->getType()->isPointerTy() ||
5785 !Arg1->getType()->isPointerTy() ||
5786 !I.getType()->isPointerTy())
5789 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5790 std::pair<SDValue, SDValue> Res =
5791 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5792 getValue(Arg0), getValue(Arg1),
5793 MachinePointerInfo(Arg0),
5794 MachinePointerInfo(Arg1), isStpcpy);
5795 if (Res.first.getNode()) {
5796 setValue(&I, Res.first);
5797 DAG.setRoot(Res.second);
5804 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5805 /// If so, return true and lower it, otherwise return false and it will be
5806 /// lowered like a normal call.
5807 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5808 // Verify that the prototype makes sense. int strcmp(void*,void*)
5809 if (I.getNumArgOperands() != 2)
5812 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5813 if (!Arg0->getType()->isPointerTy() ||
5814 !Arg1->getType()->isPointerTy() ||
5815 !I.getType()->isIntegerTy())
5818 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5819 std::pair<SDValue, SDValue> Res =
5820 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5821 getValue(Arg0), getValue(Arg1),
5822 MachinePointerInfo(Arg0),
5823 MachinePointerInfo(Arg1));
5824 if (Res.first.getNode()) {
5825 processIntegerCallValue(I, Res.first, true);
5826 PendingLoads.push_back(Res.second);
5833 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5834 /// form. If so, return true and lower it, otherwise return false and it
5835 /// will be lowered like a normal call.
5836 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5837 // Verify that the prototype makes sense. size_t strlen(char *)
5838 if (I.getNumArgOperands() != 1)
5841 const Value *Arg0 = I.getArgOperand(0);
5842 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5845 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5846 std::pair<SDValue, SDValue> Res =
5847 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5848 getValue(Arg0), MachinePointerInfo(Arg0));
5849 if (Res.first.getNode()) {
5850 processIntegerCallValue(I, Res.first, false);
5851 PendingLoads.push_back(Res.second);
5858 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5859 /// form. If so, return true and lower it, otherwise return false and it
5860 /// will be lowered like a normal call.
5861 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5862 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5863 if (I.getNumArgOperands() != 2)
5866 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5867 if (!Arg0->getType()->isPointerTy() ||
5868 !Arg1->getType()->isIntegerTy() ||
5869 !I.getType()->isIntegerTy())
5872 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5873 std::pair<SDValue, SDValue> Res =
5874 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5875 getValue(Arg0), getValue(Arg1),
5876 MachinePointerInfo(Arg0));
5877 if (Res.first.getNode()) {
5878 processIntegerCallValue(I, Res.first, false);
5879 PendingLoads.push_back(Res.second);
5886 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5887 /// operation (as expected), translate it to an SDNode with the specified opcode
5888 /// and return true.
5889 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5891 // Sanity check that it really is a unary floating-point call.
5892 if (I.getNumArgOperands() != 1 ||
5893 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5894 I.getType() != I.getArgOperand(0)->getType() ||
5895 !I.onlyReadsMemory())
5898 SDValue Tmp = getValue(I.getArgOperand(0));
5899 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5903 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5904 // Handle inline assembly differently.
5905 if (isa<InlineAsm>(I.getCalledValue())) {
5910 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5911 ComputeUsesVAFloatArgument(I, &MMI);
5913 const char *RenameFn = 0;
5914 if (Function *F = I.getCalledFunction()) {
5915 if (F->isDeclaration()) {
5916 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5917 if (unsigned IID = II->getIntrinsicID(F)) {
5918 RenameFn = visitIntrinsicCall(I, IID);
5923 if (unsigned IID = F->getIntrinsicID()) {
5924 RenameFn = visitIntrinsicCall(I, IID);
5930 // Check for well-known libc/libm calls. If the function is internal, it
5931 // can't be a library call.
5933 if (!F->hasLocalLinkage() && F->hasName() &&
5934 LibInfo->getLibFunc(F->getName(), Func) &&
5935 LibInfo->hasOptimizedCodeGen(Func)) {
5938 case LibFunc::copysign:
5939 case LibFunc::copysignf:
5940 case LibFunc::copysignl:
5941 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5942 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5943 I.getType() == I.getArgOperand(0)->getType() &&
5944 I.getType() == I.getArgOperand(1)->getType() &&
5945 I.onlyReadsMemory()) {
5946 SDValue LHS = getValue(I.getArgOperand(0));
5947 SDValue RHS = getValue(I.getArgOperand(1));
5948 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5949 LHS.getValueType(), LHS, RHS));
5954 case LibFunc::fabsf:
5955 case LibFunc::fabsl:
5956 if (visitUnaryFloatCall(I, ISD::FABS))
5962 if (visitUnaryFloatCall(I, ISD::FSIN))
5968 if (visitUnaryFloatCall(I, ISD::FCOS))
5972 case LibFunc::sqrtf:
5973 case LibFunc::sqrtl:
5974 case LibFunc::sqrt_finite:
5975 case LibFunc::sqrtf_finite:
5976 case LibFunc::sqrtl_finite:
5977 if (visitUnaryFloatCall(I, ISD::FSQRT))
5980 case LibFunc::floor:
5981 case LibFunc::floorf:
5982 case LibFunc::floorl:
5983 if (visitUnaryFloatCall(I, ISD::FFLOOR))
5986 case LibFunc::nearbyint:
5987 case LibFunc::nearbyintf:
5988 case LibFunc::nearbyintl:
5989 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
5993 case LibFunc::ceilf:
5994 case LibFunc::ceill:
5995 if (visitUnaryFloatCall(I, ISD::FCEIL))
5999 case LibFunc::rintf:
6000 case LibFunc::rintl:
6001 if (visitUnaryFloatCall(I, ISD::FRINT))
6004 case LibFunc::round:
6005 case LibFunc::roundf:
6006 case LibFunc::roundl:
6007 if (visitUnaryFloatCall(I, ISD::FROUND))
6010 case LibFunc::trunc:
6011 case LibFunc::truncf:
6012 case LibFunc::truncl:
6013 if (visitUnaryFloatCall(I, ISD::FTRUNC))
6017 case LibFunc::log2f:
6018 case LibFunc::log2l:
6019 if (visitUnaryFloatCall(I, ISD::FLOG2))
6023 case LibFunc::exp2f:
6024 case LibFunc::exp2l:
6025 if (visitUnaryFloatCall(I, ISD::FEXP2))
6028 case LibFunc::memcmp:
6029 if (visitMemCmpCall(I))
6032 case LibFunc::memchr:
6033 if (visitMemChrCall(I))
6036 case LibFunc::strcpy:
6037 if (visitStrCpyCall(I, false))
6040 case LibFunc::stpcpy:
6041 if (visitStrCpyCall(I, true))
6044 case LibFunc::strcmp:
6045 if (visitStrCmpCall(I))
6048 case LibFunc::strlen:
6049 if (visitStrLenCall(I))
6052 case LibFunc::strnlen:
6053 if (visitStrNLenCall(I))
6062 Callee = getValue(I.getCalledValue());
6064 Callee = DAG.getExternalSymbol(RenameFn,
6065 TM.getTargetLowering()->getPointerTy());
6067 // Check if we can potentially perform a tail call. More detailed checking is
6068 // be done within LowerCallTo, after more information about the call is known.
6069 LowerCallTo(&I, Callee, I.isTailCall());
6074 /// AsmOperandInfo - This contains information for each constraint that we are
6076 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6078 /// CallOperand - If this is the result output operand or a clobber
6079 /// this is null, otherwise it is the incoming operand to the CallInst.
6080 /// This gets modified as the asm is processed.
6081 SDValue CallOperand;
6083 /// AssignedRegs - If this is a register or register class operand, this
6084 /// contains the set of register corresponding to the operand.
6085 RegsForValue AssignedRegs;
6087 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6088 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
6091 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6092 /// corresponds to. If there is no Value* for this operand, it returns
6094 EVT getCallOperandValEVT(LLVMContext &Context,
6095 const TargetLowering &TLI,
6096 const DataLayout *DL) const {
6097 if (CallOperandVal == 0) return MVT::Other;
6099 if (isa<BasicBlock>(CallOperandVal))
6100 return TLI.getPointerTy();
6102 llvm::Type *OpTy = CallOperandVal->getType();
6104 // FIXME: code duplicated from TargetLowering::ParseConstraints().
6105 // If this is an indirect operand, the operand is a pointer to the
6108 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6110 report_fatal_error("Indirect operand for inline asm not a pointer!");
6111 OpTy = PtrTy->getElementType();
6114 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6115 if (StructType *STy = dyn_cast<StructType>(OpTy))
6116 if (STy->getNumElements() == 1)
6117 OpTy = STy->getElementType(0);
6119 // If OpTy is not a single value, it may be a struct/union that we
6120 // can tile with integers.
6121 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6122 unsigned BitSize = DL->getTypeSizeInBits(OpTy);
6131 OpTy = IntegerType::get(Context, BitSize);
6136 return TLI.getValueType(OpTy, true);
6140 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6142 } // end anonymous namespace
6144 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6145 /// specified operand. We prefer to assign virtual registers, to allow the
6146 /// register allocator to handle the assignment process. However, if the asm
6147 /// uses features that we can't model on machineinstrs, we have SDISel do the
6148 /// allocation. This produces generally horrible, but correct, code.
6150 /// OpInfo describes the operand.
6152 static void GetRegistersForValue(SelectionDAG &DAG,
6153 const TargetLowering &TLI,
6155 SDISelAsmOperandInfo &OpInfo) {
6156 LLVMContext &Context = *DAG.getContext();
6158 MachineFunction &MF = DAG.getMachineFunction();
6159 SmallVector<unsigned, 4> Regs;
6161 // If this is a constraint for a single physreg, or a constraint for a
6162 // register class, find it.
6163 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
6164 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6165 OpInfo.ConstraintVT);
6167 unsigned NumRegs = 1;
6168 if (OpInfo.ConstraintVT != MVT::Other) {
6169 // If this is a FP input in an integer register (or visa versa) insert a bit
6170 // cast of the input value. More generally, handle any case where the input
6171 // value disagrees with the register class we plan to stick this in.
6172 if (OpInfo.Type == InlineAsm::isInput &&
6173 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6174 // Try to convert to the first EVT that the reg class contains. If the
6175 // types are identical size, use a bitcast to convert (e.g. two differing
6177 MVT RegVT = *PhysReg.second->vt_begin();
6178 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6179 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6180 RegVT, OpInfo.CallOperand);
6181 OpInfo.ConstraintVT = RegVT;
6182 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6183 // If the input is a FP value and we want it in FP registers, do a
6184 // bitcast to the corresponding integer type. This turns an f64 value
6185 // into i64, which can be passed with two i32 values on a 32-bit
6187 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6188 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6189 RegVT, OpInfo.CallOperand);
6190 OpInfo.ConstraintVT = RegVT;
6194 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6198 EVT ValueVT = OpInfo.ConstraintVT;
6200 // If this is a constraint for a specific physical register, like {r17},
6202 if (unsigned AssignedReg = PhysReg.first) {
6203 const TargetRegisterClass *RC = PhysReg.second;
6204 if (OpInfo.ConstraintVT == MVT::Other)
6205 ValueVT = *RC->vt_begin();
6207 // Get the actual register value type. This is important, because the user
6208 // may have asked for (e.g.) the AX register in i32 type. We need to
6209 // remember that AX is actually i16 to get the right extension.
6210 RegVT = *RC->vt_begin();
6212 // This is a explicit reference to a physical register.
6213 Regs.push_back(AssignedReg);
6215 // If this is an expanded reference, add the rest of the regs to Regs.
6217 TargetRegisterClass::iterator I = RC->begin();
6218 for (; *I != AssignedReg; ++I)
6219 assert(I != RC->end() && "Didn't find reg!");
6221 // Already added the first reg.
6223 for (; NumRegs; --NumRegs, ++I) {
6224 assert(I != RC->end() && "Ran out of registers to allocate!");
6229 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6233 // Otherwise, if this was a reference to an LLVM register class, create vregs
6234 // for this reference.
6235 if (const TargetRegisterClass *RC = PhysReg.second) {
6236 RegVT = *RC->vt_begin();
6237 if (OpInfo.ConstraintVT == MVT::Other)
6240 // Create the appropriate number of virtual registers.
6241 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6242 for (; NumRegs; --NumRegs)
6243 Regs.push_back(RegInfo.createVirtualRegister(RC));
6245 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6249 // Otherwise, we couldn't allocate enough registers for this.
6252 /// visitInlineAsm - Handle a call to an InlineAsm object.
6254 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6255 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6257 /// ConstraintOperands - Information about all of the constraints.
6258 SDISelAsmOperandInfoVector ConstraintOperands;
6260 const TargetLowering *TLI = TM.getTargetLowering();
6261 TargetLowering::AsmOperandInfoVector
6262 TargetConstraints = TLI->ParseConstraints(CS);
6264 bool hasMemory = false;
6266 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6267 unsigned ResNo = 0; // ResNo - The result number of the next output.
6268 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6269 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6270 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6272 MVT OpVT = MVT::Other;
6274 // Compute the value type for each operand.
6275 switch (OpInfo.Type) {
6276 case InlineAsm::isOutput:
6277 // Indirect outputs just consume an argument.
6278 if (OpInfo.isIndirect) {
6279 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6283 // The return value of the call is this value. As such, there is no
6284 // corresponding argument.
6285 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6286 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6287 OpVT = TLI->getSimpleValueType(STy->getElementType(ResNo));
6289 assert(ResNo == 0 && "Asm only has one result!");
6290 OpVT = TLI->getSimpleValueType(CS.getType());
6294 case InlineAsm::isInput:
6295 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6297 case InlineAsm::isClobber:
6302 // If this is an input or an indirect output, process the call argument.
6303 // BasicBlocks are labels, currently appearing only in asm's.
6304 if (OpInfo.CallOperandVal) {
6305 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6306 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6308 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6311 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), *TLI, DL).
6315 OpInfo.ConstraintVT = OpVT;
6317 // Indirect operand accesses access memory.
6318 if (OpInfo.isIndirect)
6321 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6322 TargetLowering::ConstraintType
6323 CType = TLI->getConstraintType(OpInfo.Codes[j]);
6324 if (CType == TargetLowering::C_Memory) {
6332 SDValue Chain, Flag;
6334 // We won't need to flush pending loads if this asm doesn't touch
6335 // memory and is nonvolatile.
6336 if (hasMemory || IA->hasSideEffects())
6339 Chain = DAG.getRoot();
6341 // Second pass over the constraints: compute which constraint option to use
6342 // and assign registers to constraints that want a specific physreg.
6343 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6344 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6346 // If this is an output operand with a matching input operand, look up the
6347 // matching input. If their types mismatch, e.g. one is an integer, the
6348 // other is floating point, or their sizes are different, flag it as an
6350 if (OpInfo.hasMatchingInput()) {
6351 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6353 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6354 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
6355 TLI->getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6356 OpInfo.ConstraintVT);
6357 std::pair<unsigned, const TargetRegisterClass*> InputRC =
6358 TLI->getRegForInlineAsmConstraint(Input.ConstraintCode,
6359 Input.ConstraintVT);
6360 if ((OpInfo.ConstraintVT.isInteger() !=
6361 Input.ConstraintVT.isInteger()) ||
6362 (MatchRC.second != InputRC.second)) {
6363 report_fatal_error("Unsupported asm: input constraint"
6364 " with a matching output constraint of"
6365 " incompatible type!");
6367 Input.ConstraintVT = OpInfo.ConstraintVT;
6371 // Compute the constraint code and ConstraintType to use.
6372 TLI->ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6374 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6375 OpInfo.Type == InlineAsm::isClobber)
6378 // If this is a memory input, and if the operand is not indirect, do what we
6379 // need to to provide an address for the memory input.
6380 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6381 !OpInfo.isIndirect) {
6382 assert((OpInfo.isMultipleAlternative ||
6383 (OpInfo.Type == InlineAsm::isInput)) &&
6384 "Can only indirectify direct input operands!");
6386 // Memory operands really want the address of the value. If we don't have
6387 // an indirect input, put it in the constpool if we can, otherwise spill
6388 // it to a stack slot.
6389 // TODO: This isn't quite right. We need to handle these according to
6390 // the addressing mode that the constraint wants. Also, this may take
6391 // an additional register for the computation and we don't want that
6394 // If the operand is a float, integer, or vector constant, spill to a
6395 // constant pool entry to get its address.
6396 const Value *OpVal = OpInfo.CallOperandVal;
6397 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6398 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6399 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6400 TLI->getPointerTy());
6402 // Otherwise, create a stack slot and emit a store to it before the
6404 Type *Ty = OpVal->getType();
6405 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
6406 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(Ty);
6407 MachineFunction &MF = DAG.getMachineFunction();
6408 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6409 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI->getPointerTy());
6410 Chain = DAG.getStore(Chain, getCurSDLoc(),
6411 OpInfo.CallOperand, StackSlot,
6412 MachinePointerInfo::getFixedStack(SSFI),
6414 OpInfo.CallOperand = StackSlot;
6417 // There is no longer a Value* corresponding to this operand.
6418 OpInfo.CallOperandVal = 0;
6420 // It is now an indirect operand.
6421 OpInfo.isIndirect = true;
6424 // If this constraint is for a specific register, allocate it before
6426 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6427 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
6430 // Second pass - Loop over all of the operands, assigning virtual or physregs
6431 // to register class operands.
6432 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6433 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6435 // C_Register operands have already been allocated, Other/Memory don't need
6437 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6438 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
6441 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6442 std::vector<SDValue> AsmNodeOperands;
6443 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6444 AsmNodeOperands.push_back(
6445 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6446 TLI->getPointerTy()));
6448 // If we have a !srcloc metadata node associated with it, we want to attach
6449 // this to the ultimately generated inline asm machineinstr. To do this, we
6450 // pass in the third operand as this (potentially null) inline asm MDNode.
6451 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6452 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6454 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6455 // bits as operand 3.
6456 unsigned ExtraInfo = 0;
6457 if (IA->hasSideEffects())
6458 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6459 if (IA->isAlignStack())
6460 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6461 // Set the asm dialect.
6462 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6464 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6465 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6466 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6468 // Compute the constraint code and ConstraintType to use.
6469 TLI->ComputeConstraintToUse(OpInfo, SDValue());
6471 // Ideally, we would only check against memory constraints. However, the
6472 // meaning of an other constraint can be target-specific and we can't easily
6473 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6474 // for other constriants as well.
6475 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6476 OpInfo.ConstraintType == TargetLowering::C_Other) {
6477 if (OpInfo.Type == InlineAsm::isInput)
6478 ExtraInfo |= InlineAsm::Extra_MayLoad;
6479 else if (OpInfo.Type == InlineAsm::isOutput)
6480 ExtraInfo |= InlineAsm::Extra_MayStore;
6481 else if (OpInfo.Type == InlineAsm::isClobber)
6482 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6486 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6487 TLI->getPointerTy()));
6489 // Loop over all of the inputs, copying the operand values into the
6490 // appropriate registers and processing the output regs.
6491 RegsForValue RetValRegs;
6493 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6494 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6496 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6497 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6499 switch (OpInfo.Type) {
6500 case InlineAsm::isOutput: {
6501 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6502 OpInfo.ConstraintType != TargetLowering::C_Register) {
6503 // Memory output, or 'other' output (e.g. 'X' constraint).
6504 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6506 // Add information to the INLINEASM node to know about this output.
6507 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6508 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
6509 TLI->getPointerTy()));
6510 AsmNodeOperands.push_back(OpInfo.CallOperand);
6514 // Otherwise, this is a register or register class output.
6516 // Copy the output from the appropriate register. Find a register that
6518 if (OpInfo.AssignedRegs.Regs.empty()) {
6519 LLVMContext &Ctx = *DAG.getContext();
6520 Ctx.emitError(CS.getInstruction(),
6521 "couldn't allocate output register for constraint '" +
6522 Twine(OpInfo.ConstraintCode) + "'");
6526 // If this is an indirect operand, store through the pointer after the
6528 if (OpInfo.isIndirect) {
6529 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6530 OpInfo.CallOperandVal));
6532 // This is the result value of the call.
6533 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6534 // Concatenate this output onto the outputs list.
6535 RetValRegs.append(OpInfo.AssignedRegs);
6538 // Add information to the INLINEASM node to know that this register is
6541 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6542 ? InlineAsm::Kind_RegDefEarlyClobber
6543 : InlineAsm::Kind_RegDef,
6544 false, 0, DAG, AsmNodeOperands);
6547 case InlineAsm::isInput: {
6548 SDValue InOperandVal = OpInfo.CallOperand;
6550 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6551 // If this is required to match an output register we have already set,
6552 // just use its register.
6553 unsigned OperandNo = OpInfo.getMatchedOperand();
6555 // Scan until we find the definition we already emitted of this operand.
6556 // When we find it, create a RegsForValue operand.
6557 unsigned CurOp = InlineAsm::Op_FirstOperand;
6558 for (; OperandNo; --OperandNo) {
6559 // Advance to the next operand.
6561 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6562 assert((InlineAsm::isRegDefKind(OpFlag) ||
6563 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6564 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6565 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6569 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6570 if (InlineAsm::isRegDefKind(OpFlag) ||
6571 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6572 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6573 if (OpInfo.isIndirect) {
6574 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6575 LLVMContext &Ctx = *DAG.getContext();
6576 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6577 " don't know how to handle tied "
6578 "indirect register inputs");
6582 RegsForValue MatchedRegs;
6583 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6584 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6585 MatchedRegs.RegVTs.push_back(RegVT);
6586 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6587 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6589 if (const TargetRegisterClass *RC = TLI->getRegClassFor(RegVT))
6590 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6592 LLVMContext &Ctx = *DAG.getContext();
6593 Ctx.emitError(CS.getInstruction(),
6594 "inline asm error: This value"
6595 " type register class is not natively supported!");
6599 // Use the produced MatchedRegs object to
6600 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6601 Chain, &Flag, CS.getInstruction());
6602 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6603 true, OpInfo.getMatchedOperand(),
6604 DAG, AsmNodeOperands);
6608 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6609 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6610 "Unexpected number of operands");
6611 // Add information to the INLINEASM node to know about this input.
6612 // See InlineAsm.h isUseOperandTiedToDef.
6613 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6614 OpInfo.getMatchedOperand());
6615 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6616 TLI->getPointerTy()));
6617 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6621 // Treat indirect 'X' constraint as memory.
6622 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6624 OpInfo.ConstraintType = TargetLowering::C_Memory;
6626 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6627 std::vector<SDValue> Ops;
6628 TLI->LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6631 LLVMContext &Ctx = *DAG.getContext();
6632 Ctx.emitError(CS.getInstruction(),
6633 "invalid operand for inline asm constraint '" +
6634 Twine(OpInfo.ConstraintCode) + "'");
6638 // Add information to the INLINEASM node to know about this input.
6639 unsigned ResOpType =
6640 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6641 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6642 TLI->getPointerTy()));
6643 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6647 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6648 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6649 assert(InOperandVal.getValueType() == TLI->getPointerTy() &&
6650 "Memory operands expect pointer values");
6652 // Add information to the INLINEASM node to know about this input.
6653 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6654 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6655 TLI->getPointerTy()));
6656 AsmNodeOperands.push_back(InOperandVal);
6660 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6661 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6662 "Unknown constraint type!");
6664 // TODO: Support this.
6665 if (OpInfo.isIndirect) {
6666 LLVMContext &Ctx = *DAG.getContext();
6667 Ctx.emitError(CS.getInstruction(),
6668 "Don't know how to handle indirect register inputs yet "
6669 "for constraint '" +
6670 Twine(OpInfo.ConstraintCode) + "'");
6674 // Copy the input into the appropriate registers.
6675 if (OpInfo.AssignedRegs.Regs.empty()) {
6676 LLVMContext &Ctx = *DAG.getContext();
6677 Ctx.emitError(CS.getInstruction(),
6678 "couldn't allocate input reg for constraint '" +
6679 Twine(OpInfo.ConstraintCode) + "'");
6683 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6684 Chain, &Flag, CS.getInstruction());
6686 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6687 DAG, AsmNodeOperands);
6690 case InlineAsm::isClobber: {
6691 // Add the clobbered value to the operand list, so that the register
6692 // allocator is aware that the physreg got clobbered.
6693 if (!OpInfo.AssignedRegs.Regs.empty())
6694 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6702 // Finish up input operands. Set the input chain and add the flag last.
6703 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6704 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6706 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6707 DAG.getVTList(MVT::Other, MVT::Glue),
6708 &AsmNodeOperands[0], AsmNodeOperands.size());
6709 Flag = Chain.getValue(1);
6711 // If this asm returns a register value, copy the result from that register
6712 // and set it as the value of the call.
6713 if (!RetValRegs.Regs.empty()) {
6714 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6715 Chain, &Flag, CS.getInstruction());
6717 // FIXME: Why don't we do this for inline asms with MRVs?
6718 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6719 EVT ResultType = TLI->getValueType(CS.getType());
6721 // If any of the results of the inline asm is a vector, it may have the
6722 // wrong width/num elts. This can happen for register classes that can
6723 // contain multiple different value types. The preg or vreg allocated may
6724 // not have the same VT as was expected. Convert it to the right type
6725 // with bit_convert.
6726 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6727 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6730 } else if (ResultType != Val.getValueType() &&
6731 ResultType.isInteger() && Val.getValueType().isInteger()) {
6732 // If a result value was tied to an input value, the computed result may
6733 // have a wider width than the expected result. Extract the relevant
6735 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6738 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6741 setValue(CS.getInstruction(), Val);
6742 // Don't need to use this as a chain in this case.
6743 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6747 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6749 // Process indirect outputs, first output all of the flagged copies out of
6751 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6752 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6753 const Value *Ptr = IndirectStoresToEmit[i].second;
6754 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6756 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6759 // Emit the non-flagged stores from the physregs.
6760 SmallVector<SDValue, 8> OutChains;
6761 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6762 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6763 StoresToEmit[i].first,
6764 getValue(StoresToEmit[i].second),
6765 MachinePointerInfo(StoresToEmit[i].second),
6767 OutChains.push_back(Val);
6770 if (!OutChains.empty())
6771 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
6772 &OutChains[0], OutChains.size());
6777 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6778 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6779 MVT::Other, getRoot(),
6780 getValue(I.getArgOperand(0)),
6781 DAG.getSrcValue(I.getArgOperand(0))));
6784 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6785 const TargetLowering *TLI = TM.getTargetLowering();
6786 const DataLayout &DL = *TLI->getDataLayout();
6787 SDValue V = DAG.getVAArg(TLI->getValueType(I.getType()), getCurSDLoc(),
6788 getRoot(), getValue(I.getOperand(0)),
6789 DAG.getSrcValue(I.getOperand(0)),
6790 DL.getABITypeAlignment(I.getType()));
6792 DAG.setRoot(V.getValue(1));
6795 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6796 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6797 MVT::Other, getRoot(),
6798 getValue(I.getArgOperand(0)),
6799 DAG.getSrcValue(I.getArgOperand(0))));
6802 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6803 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6804 MVT::Other, getRoot(),
6805 getValue(I.getArgOperand(0)),
6806 getValue(I.getArgOperand(1)),
6807 DAG.getSrcValue(I.getArgOperand(0)),
6808 DAG.getSrcValue(I.getArgOperand(1))));
6811 /// \brief Lower an argument list according to the target calling convention.
6813 /// \return A tuple of <return-value, token-chain>
6815 /// This is a helper for lowering intrinsics that follow a target calling
6816 /// convention or require stack pointer adjustment. Only a subset of the
6817 /// intrinsic's operands need to participate in the calling convention.
6818 std::pair<SDValue, SDValue>
6819 SelectionDAGBuilder::LowerCallOperands(const CallInst &CI, unsigned ArgIdx,
6820 unsigned NumArgs, SDValue Callee,
6822 TargetLowering::ArgListTy Args;
6823 Args.reserve(NumArgs);
6825 // Populate the argument list.
6826 // Attributes for args start at offset 1, after the return attribute.
6827 ImmutableCallSite CS(&CI);
6828 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6829 ArgI != ArgE; ++ArgI) {
6830 const Value *V = CI.getOperand(ArgI);
6832 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6834 TargetLowering::ArgListEntry Entry;
6835 Entry.Node = getValue(V);
6836 Entry.Ty = V->getType();
6837 Entry.setAttributes(&CS, AttrI);
6838 Args.push_back(Entry);
6841 Type *retTy = useVoidTy ? Type::getVoidTy(*DAG.getContext()) : CI.getType();
6842 TargetLowering::CallLoweringInfo CLI(getRoot(), retTy, /*retSExt*/ false,
6843 /*retZExt*/ false, /*isVarArg*/ false, /*isInReg*/ false, NumArgs,
6844 CI.getCallingConv(), /*isTailCall*/ false, /*doesNotReturn*/ false,
6845 /*isReturnValueUsed*/ CI.use_empty(), Callee, Args, DAG, getCurSDLoc());
6847 const TargetLowering *TLI = TM.getTargetLowering();
6848 return TLI->LowerCallTo(CLI);
6851 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6852 /// or patchpoint target node's operand list.
6854 /// Constants are converted to TargetConstants purely as an optimization to
6855 /// avoid constant materialization and register allocation.
6857 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6858 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6859 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6860 /// address materialization and register allocation, but may also be required
6861 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6862 /// alloca in the entry block, then the runtime may assume that the alloca's
6863 /// StackMap location can be read immediately after compilation and that the
6864 /// location is valid at any point during execution (this is similar to the
6865 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6866 /// only available in a register, then the runtime would need to trap when
6867 /// execution reaches the StackMap in order to read the alloca's location.
6868 static void addStackMapLiveVars(const CallInst &CI, unsigned StartIdx,
6869 SmallVectorImpl<SDValue> &Ops,
6870 SelectionDAGBuilder &Builder) {
6871 for (unsigned i = StartIdx, e = CI.getNumArgOperands(); i != e; ++i) {
6872 SDValue OpVal = Builder.getValue(CI.getArgOperand(i));
6873 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6875 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
6877 Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
6878 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6879 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6881 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
6883 Ops.push_back(OpVal);
6887 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6888 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6889 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6890 // [live variables...])
6892 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6894 SDValue Chain, InFlag, Callee, NullPtr;
6895 SmallVector<SDValue, 32> Ops;
6897 SDLoc DL = getCurSDLoc();
6898 Callee = getValue(CI.getCalledValue());
6899 NullPtr = DAG.getIntPtrConstant(0, true);
6901 // The stackmap intrinsic only records the live variables (the arguemnts
6902 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
6903 // intrinsic, this won't be lowered to a function call. This means we don't
6904 // have to worry about calling conventions and target specific lowering code.
6905 // Instead we perform the call lowering right here.
6907 // chain, flag = CALLSEQ_START(chain, 0)
6908 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
6909 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
6911 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
6912 InFlag = Chain.getValue(1);
6914 // Add the <id> and <numBytes> constants.
6915 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
6916 Ops.push_back(DAG.getTargetConstant(
6917 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
6918 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
6919 Ops.push_back(DAG.getTargetConstant(
6920 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
6922 // Push live variables for the stack map.
6923 addStackMapLiveVars(CI, 2, Ops, *this);
6925 // We are not pushing any register mask info here on the operands list,
6926 // because the stackmap doesn't clobber anything.
6928 // Push the chain and the glue flag.
6929 Ops.push_back(Chain);
6930 Ops.push_back(InFlag);
6932 // Create the STACKMAP node.
6933 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6934 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
6935 Chain = SDValue(SM, 0);
6936 InFlag = Chain.getValue(1);
6938 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
6940 // Stackmaps don't generate values, so nothing goes into the NodeMap.
6942 // Set the root to the target-lowered call chain.
6945 // Inform the Frame Information that we have a stackmap in this function.
6946 FuncInfo.MF->getFrameInfo()->setHasStackMap();
6949 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6950 void SelectionDAGBuilder::visitPatchpoint(const CallInst &CI) {
6951 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
6956 // [live variables...])
6958 CallingConv::ID CC = CI.getCallingConv();
6959 bool isAnyRegCC = CC == CallingConv::AnyReg;
6960 bool hasDef = !CI.getType()->isVoidTy();
6961 SDValue Callee = getValue(CI.getOperand(2)); // <target>
6963 // Get the real number of arguments participating in the call <numArgs>
6964 SDValue NArgVal = getValue(CI.getArgOperand(PatchPointOpers::NArgPos));
6965 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
6967 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
6968 // Intrinsics include all meta-operands up to but not including CC.
6969 unsigned NumMetaOpers = PatchPointOpers::CCPos;
6970 assert(CI.getNumArgOperands() >= NumMetaOpers + NumArgs &&
6971 "Not enough arguments provided to the patchpoint intrinsic");
6973 // For AnyRegCC the arguments are lowered later on manually.
6974 unsigned NumCallArgs = isAnyRegCC ? 0 : NumArgs;
6975 std::pair<SDValue, SDValue> Result =
6976 LowerCallOperands(CI, NumMetaOpers, NumCallArgs, Callee, isAnyRegCC);
6978 // Set the root to the target-lowered call chain.
6979 SDValue Chain = Result.second;
6982 SDNode *CallEnd = Chain.getNode();
6983 if (hasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
6984 CallEnd = CallEnd->getOperand(0).getNode();
6986 /// Get a call instruction from the call sequence chain.
6987 /// Tail calls are not allowed.
6988 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6989 "Expected a callseq node.");
6990 SDNode *Call = CallEnd->getOperand(0).getNode();
6991 bool hasGlue = Call->getGluedNode();
6993 // Replace the target specific call node with the patchable intrinsic.
6994 SmallVector<SDValue, 8> Ops;
6996 // Add the <id> and <numBytes> constants.
6997 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
6998 Ops.push_back(DAG.getTargetConstant(
6999 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
7000 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7001 Ops.push_back(DAG.getTargetConstant(
7002 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
7004 // Assume that the Callee is a constant address.
7005 // FIXME: handle function symbols in the future.
7007 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
7008 /*isTarget=*/true));
7010 // Adjust <numArgs> to account for any arguments that have been passed on the
7012 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7013 unsigned NumCallRegArgs = Call->getNumOperands() - (hasGlue ? 4 : 3);
7014 NumCallRegArgs = isAnyRegCC ? NumArgs : NumCallRegArgs;
7015 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
7017 // Add the calling convention
7018 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
7020 // Add the arguments we omitted previously. The register allocator should
7021 // place these in any free register.
7023 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7024 Ops.push_back(getValue(CI.getArgOperand(i)));
7026 // Push the arguments from the call instruction up to the register mask.
7027 SDNode::op_iterator e = hasGlue ? Call->op_end()-2 : Call->op_end()-1;
7028 for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
7031 // Push live variables for the stack map.
7032 addStackMapLiveVars(CI, NumMetaOpers + NumArgs, Ops, *this);
7034 // Push the register mask info.
7036 Ops.push_back(*(Call->op_end()-2));
7038 Ops.push_back(*(Call->op_end()-1));
7040 // Push the chain (this is originally the first operand of the call, but
7041 // becomes now the last or second to last operand).
7042 Ops.push_back(*(Call->op_begin()));
7044 // Push the glue flag (last operand).
7046 Ops.push_back(*(Call->op_end()-1));
7049 if (isAnyRegCC && hasDef) {
7050 // Create the return types based on the intrinsic definition
7051 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7052 SmallVector<EVT, 3> ValueVTs;
7053 ComputeValueVTs(TLI, CI.getType(), ValueVTs);
7054 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7056 // There is always a chain and a glue type at the end
7057 ValueVTs.push_back(MVT::Other);
7058 ValueVTs.push_back(MVT::Glue);
7059 NodeTys = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
7061 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7063 // Replace the target specific call node with a PATCHPOINT node.
7064 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7065 getCurSDLoc(), NodeTys, Ops);
7067 // Update the NodeMap.
7070 setValue(&CI, SDValue(MN, 0));
7072 setValue(&CI, Result.first);
7075 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7076 // call sequence. Furthermore the location of the chain and glue can change
7077 // when the AnyReg calling convention is used and the intrinsic returns a
7079 if (isAnyRegCC && hasDef) {
7080 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7081 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7082 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7084 DAG.ReplaceAllUsesWith(Call, MN);
7085 DAG.DeleteNode(Call);
7087 // Inform the Frame Information that we have a patchpoint in this function.
7088 FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
7091 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7092 /// implementation, which just calls LowerCall.
7093 /// FIXME: When all targets are
7094 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7095 std::pair<SDValue, SDValue>
7096 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7097 // Handle the incoming return values from the call.
7099 SmallVector<EVT, 4> RetTys;
7100 ComputeValueVTs(*this, CLI.RetTy, RetTys);
7101 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7103 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7104 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7105 for (unsigned i = 0; i != NumRegs; ++i) {
7106 ISD::InputArg MyFlags;
7107 MyFlags.VT = RegisterVT;
7109 MyFlags.Used = CLI.IsReturnValueUsed;
7111 MyFlags.Flags.setSExt();
7113 MyFlags.Flags.setZExt();
7115 MyFlags.Flags.setInReg();
7116 CLI.Ins.push_back(MyFlags);
7120 // Handle all of the outgoing arguments.
7122 CLI.OutVals.clear();
7123 ArgListTy &Args = CLI.Args;
7124 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7125 SmallVector<EVT, 4> ValueVTs;
7126 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
7127 for (unsigned Value = 0, NumValues = ValueVTs.size();
7128 Value != NumValues; ++Value) {
7129 EVT VT = ValueVTs[Value];
7130 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7131 SDValue Op = SDValue(Args[i].Node.getNode(),
7132 Args[i].Node.getResNo() + Value);
7133 ISD::ArgFlagsTy Flags;
7134 unsigned OriginalAlignment =
7135 getDataLayout()->getABITypeAlignment(ArgTy);
7141 if (Args[i].isInReg)
7145 if (Args[i].isByVal)
7147 if (Args[i].isInAlloca) {
7148 Flags.setInAlloca();
7149 // Set the byval flag for CCAssignFn callbacks that don't know about
7150 // inalloca. This way we can know how many bytes we should've allocated
7151 // and how many bytes a callee cleanup function will pop. If we port
7152 // inalloca to more targets, we'll have to add custom inalloca handling
7153 // in the various CC lowering callbacks.
7156 if (Args[i].isByVal || Args[i].isInAlloca) {
7157 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7158 Type *ElementTy = Ty->getElementType();
7159 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
7160 // For ByVal, alignment should come from FE. BE will guess if this
7161 // info is not there but there are cases it cannot get right.
7162 unsigned FrameAlign;
7163 if (Args[i].Alignment)
7164 FrameAlign = Args[i].Alignment;
7166 FrameAlign = getByValTypeAlignment(ElementTy);
7167 Flags.setByValAlign(FrameAlign);
7171 Flags.setOrigAlign(OriginalAlignment);
7173 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7174 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7175 SmallVector<SDValue, 4> Parts(NumParts);
7176 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7179 ExtendKind = ISD::SIGN_EXTEND;
7180 else if (Args[i].isZExt)
7181 ExtendKind = ISD::ZERO_EXTEND;
7183 // Conservatively only handle 'returned' on non-vectors for now
7184 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7185 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7186 "unexpected use of 'returned'");
7187 // Before passing 'returned' to the target lowering code, ensure that
7188 // either the register MVT and the actual EVT are the same size or that
7189 // the return value and argument are extended in the same way; in these
7190 // cases it's safe to pass the argument register value unchanged as the
7191 // return register value (although it's at the target's option whether
7193 // TODO: allow code generation to take advantage of partially preserved
7194 // registers rather than clobbering the entire register when the
7195 // parameter extension method is not compatible with the return
7197 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7198 (ExtendKind != ISD::ANY_EXTEND &&
7199 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7200 Flags.setReturned();
7203 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts,
7204 PartVT, CLI.CS ? CLI.CS->getInstruction() : 0, ExtendKind);
7206 for (unsigned j = 0; j != NumParts; ++j) {
7207 // if it isn't first piece, alignment must be 1
7208 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7209 i < CLI.NumFixedArgs,
7210 i, j*Parts[j].getValueType().getStoreSize());
7211 if (NumParts > 1 && j == 0)
7212 MyFlags.Flags.setSplit();
7214 MyFlags.Flags.setOrigAlign(1);
7216 CLI.Outs.push_back(MyFlags);
7217 CLI.OutVals.push_back(Parts[j]);
7222 SmallVector<SDValue, 4> InVals;
7223 CLI.Chain = LowerCall(CLI, InVals);
7225 // Verify that the target's LowerCall behaved as expected.
7226 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7227 "LowerCall didn't return a valid chain!");
7228 assert((!CLI.IsTailCall || InVals.empty()) &&
7229 "LowerCall emitted a return value for a tail call!");
7230 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7231 "LowerCall didn't emit the correct number of values!");
7233 // For a tail call, the return value is merely live-out and there aren't
7234 // any nodes in the DAG representing it. Return a special value to
7235 // indicate that a tail call has been emitted and no more Instructions
7236 // should be processed in the current block.
7237 if (CLI.IsTailCall) {
7238 CLI.DAG.setRoot(CLI.Chain);
7239 return std::make_pair(SDValue(), SDValue());
7242 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7243 assert(InVals[i].getNode() &&
7244 "LowerCall emitted a null value!");
7245 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7246 "LowerCall emitted a value with the wrong type!");
7249 // Collect the legal value parts into potentially illegal values
7250 // that correspond to the original function's return values.
7251 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7253 AssertOp = ISD::AssertSext;
7254 else if (CLI.RetZExt)
7255 AssertOp = ISD::AssertZext;
7256 SmallVector<SDValue, 4> ReturnValues;
7257 unsigned CurReg = 0;
7258 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7260 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7261 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7263 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7264 NumRegs, RegisterVT, VT, NULL,
7269 // For a function returning void, there is no return value. We can't create
7270 // such a node, so we just return a null return value in that case. In
7271 // that case, nothing will actually look at the value.
7272 if (ReturnValues.empty())
7273 return std::make_pair(SDValue(), CLI.Chain);
7275 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7276 CLI.DAG.getVTList(&RetTys[0], RetTys.size()),
7277 &ReturnValues[0], ReturnValues.size());
7278 return std::make_pair(Res, CLI.Chain);
7281 void TargetLowering::LowerOperationWrapper(SDNode *N,
7282 SmallVectorImpl<SDValue> &Results,
7283 SelectionDAG &DAG) const {
7284 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
7286 Results.push_back(Res);
7289 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7290 llvm_unreachable("LowerOperation not implemented for this target!");
7294 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7295 SDValue Op = getNonRegisterValue(V);
7296 assert((Op.getOpcode() != ISD::CopyFromReg ||
7297 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7298 "Copy from a reg to the same reg!");
7299 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7301 const TargetLowering *TLI = TM.getTargetLowering();
7302 RegsForValue RFV(V->getContext(), *TLI, Reg, V->getType());
7303 SDValue Chain = DAG.getEntryNode();
7304 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, 0, V);
7305 PendingExports.push_back(Chain);
7308 #include "llvm/CodeGen/SelectionDAGISel.h"
7310 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7311 /// entry block, return true. This includes arguments used by switches, since
7312 /// the switch may expand into multiple basic blocks.
7313 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7314 // With FastISel active, we may be splitting blocks, so force creation
7315 // of virtual registers for all non-dead arguments.
7317 return A->use_empty();
7319 const BasicBlock *Entry = A->getParent()->begin();
7320 for (const User *U : A->users())
7321 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7322 return false; // Use not in entry block.
7327 void SelectionDAGISel::LowerArguments(const Function &F) {
7328 SelectionDAG &DAG = SDB->DAG;
7329 SDLoc dl = SDB->getCurSDLoc();
7330 const TargetLowering *TLI = getTargetLowering();
7331 const DataLayout *DL = TLI->getDataLayout();
7332 SmallVector<ISD::InputArg, 16> Ins;
7334 if (!FuncInfo->CanLowerReturn) {
7335 // Put in an sret pointer parameter before all the other parameters.
7336 SmallVector<EVT, 1> ValueVTs;
7337 ComputeValueVTs(*getTargetLowering(),
7338 PointerType::getUnqual(F.getReturnType()), ValueVTs);
7340 // NOTE: Assuming that a pointer will never break down to more than one VT
7342 ISD::ArgFlagsTy Flags;
7344 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7345 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
7346 Ins.push_back(RetArg);
7349 // Set up the incoming argument description vector.
7351 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7352 I != E; ++I, ++Idx) {
7353 SmallVector<EVT, 4> ValueVTs;
7354 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7355 bool isArgValueUsed = !I->use_empty();
7356 unsigned PartBase = 0;
7357 for (unsigned Value = 0, NumValues = ValueVTs.size();
7358 Value != NumValues; ++Value) {
7359 EVT VT = ValueVTs[Value];
7360 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7361 ISD::ArgFlagsTy Flags;
7362 unsigned OriginalAlignment =
7363 DL->getABITypeAlignment(ArgTy);
7365 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7367 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7369 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7371 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7373 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7375 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7376 Flags.setInAlloca();
7377 // Set the byval flag for CCAssignFn callbacks that don't know about
7378 // inalloca. This way we can know how many bytes we should've allocated
7379 // and how many bytes a callee cleanup function will pop. If we port
7380 // inalloca to more targets, we'll have to add custom inalloca handling
7381 // in the various CC lowering callbacks.
7384 if (Flags.isByVal() || Flags.isInAlloca()) {
7385 PointerType *Ty = cast<PointerType>(I->getType());
7386 Type *ElementTy = Ty->getElementType();
7387 Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
7388 // For ByVal, alignment should be passed from FE. BE will guess if
7389 // this info is not there but there are cases it cannot get right.
7390 unsigned FrameAlign;
7391 if (F.getParamAlignment(Idx))
7392 FrameAlign = F.getParamAlignment(Idx);
7394 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
7395 Flags.setByValAlign(FrameAlign);
7397 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7399 Flags.setOrigAlign(OriginalAlignment);
7401 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7402 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7403 for (unsigned i = 0; i != NumRegs; ++i) {
7404 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7405 Idx-1, PartBase+i*RegisterVT.getStoreSize());
7406 if (NumRegs > 1 && i == 0)
7407 MyFlags.Flags.setSplit();
7408 // if it isn't first piece, alignment must be 1
7410 MyFlags.Flags.setOrigAlign(1);
7411 Ins.push_back(MyFlags);
7413 PartBase += VT.getStoreSize();
7417 // Call the target to set up the argument values.
7418 SmallVector<SDValue, 8> InVals;
7419 SDValue NewRoot = TLI->LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
7423 // Verify that the target's LowerFormalArguments behaved as expected.
7424 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7425 "LowerFormalArguments didn't return a valid chain!");
7426 assert(InVals.size() == Ins.size() &&
7427 "LowerFormalArguments didn't emit the correct number of values!");
7429 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7430 assert(InVals[i].getNode() &&
7431 "LowerFormalArguments emitted a null value!");
7432 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7433 "LowerFormalArguments emitted a value with the wrong type!");
7437 // Update the DAG with the new chain value resulting from argument lowering.
7438 DAG.setRoot(NewRoot);
7440 // Set up the argument values.
7443 if (!FuncInfo->CanLowerReturn) {
7444 // Create a virtual register for the sret pointer, and put in a copy
7445 // from the sret argument into it.
7446 SmallVector<EVT, 1> ValueVTs;
7447 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7448 MVT VT = ValueVTs[0].getSimpleVT();
7449 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7450 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7451 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7452 RegVT, VT, NULL, AssertOp);
7454 MachineFunction& MF = SDB->DAG.getMachineFunction();
7455 MachineRegisterInfo& RegInfo = MF.getRegInfo();
7456 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7457 FuncInfo->DemoteRegister = SRetReg;
7458 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(),
7460 DAG.setRoot(NewRoot);
7462 // i indexes lowered arguments. Bump it past the hidden sret argument.
7463 // Idx indexes LLVM arguments. Don't touch it.
7467 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7469 SmallVector<SDValue, 4> ArgValues;
7470 SmallVector<EVT, 4> ValueVTs;
7471 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7472 unsigned NumValues = ValueVTs.size();
7474 // If this argument is unused then remember its value. It is used to generate
7475 // debugging information.
7476 if (I->use_empty() && NumValues) {
7477 SDB->setUnusedArgValue(I, InVals[i]);
7479 // Also remember any frame index for use in FastISel.
7480 if (FrameIndexSDNode *FI =
7481 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7482 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7485 for (unsigned Val = 0; Val != NumValues; ++Val) {
7486 EVT VT = ValueVTs[Val];
7487 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7488 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7490 if (!I->use_empty()) {
7491 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7492 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7493 AssertOp = ISD::AssertSext;
7494 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7495 AssertOp = ISD::AssertZext;
7497 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7498 NumParts, PartVT, VT,
7505 // We don't need to do anything else for unused arguments.
7506 if (ArgValues.empty())
7509 // Note down frame index.
7510 if (FrameIndexSDNode *FI =
7511 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7512 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7514 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
7515 SDB->getCurSDLoc());
7517 SDB->setValue(I, Res);
7518 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7519 if (LoadSDNode *LNode =
7520 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7521 if (FrameIndexSDNode *FI =
7522 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7523 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7526 // If this argument is live outside of the entry block, insert a copy from
7527 // wherever we got it to the vreg that other BB's will reference it as.
7528 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7529 // If we can, though, try to skip creating an unnecessary vreg.
7530 // FIXME: This isn't very clean... it would be nice to make this more
7531 // general. It's also subtly incompatible with the hacks FastISel
7533 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7534 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7535 FuncInfo->ValueMap[I] = Reg;
7539 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
7540 FuncInfo->InitializeRegForValue(I);
7541 SDB->CopyToExportRegsIfNeeded(I);
7545 assert(i == InVals.size() && "Argument register count mismatch!");
7547 // Finally, if the target has anything special to do, allow it to do so.
7548 // FIXME: this should insert code into the DAG!
7549 EmitFunctionEntryCode();
7552 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7553 /// ensure constants are generated when needed. Remember the virtual registers
7554 /// that need to be added to the Machine PHI nodes as input. We cannot just
7555 /// directly add them, because expansion might result in multiple MBB's for one
7556 /// BB. As such, the start of the BB might correspond to a different MBB than
7560 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7561 const TerminatorInst *TI = LLVMBB->getTerminator();
7563 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7565 // Check successor nodes' PHI nodes that expect a constant to be available
7567 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7568 const BasicBlock *SuccBB = TI->getSuccessor(succ);
7569 if (!isa<PHINode>(SuccBB->begin())) continue;
7570 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7572 // If this terminator has multiple identical successors (common for
7573 // switches), only handle each succ once.
7574 if (!SuccsHandled.insert(SuccMBB)) continue;
7576 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7578 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7579 // nodes and Machine PHI nodes, but the incoming operands have not been
7581 for (BasicBlock::const_iterator I = SuccBB->begin();
7582 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7583 // Ignore dead phi's.
7584 if (PN->use_empty()) continue;
7587 if (PN->getType()->isEmptyTy())
7591 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7593 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7594 unsigned &RegOut = ConstantsOut[C];
7596 RegOut = FuncInfo.CreateRegs(C->getType());
7597 CopyValueToVirtualRegister(C, RegOut);
7601 DenseMap<const Value *, unsigned>::iterator I =
7602 FuncInfo.ValueMap.find(PHIOp);
7603 if (I != FuncInfo.ValueMap.end())
7606 assert(isa<AllocaInst>(PHIOp) &&
7607 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7608 "Didn't codegen value into a register!??");
7609 Reg = FuncInfo.CreateRegs(PHIOp->getType());
7610 CopyValueToVirtualRegister(PHIOp, Reg);
7614 // Remember that this register needs to added to the machine PHI node as
7615 // the input for this MBB.
7616 SmallVector<EVT, 4> ValueVTs;
7617 const TargetLowering *TLI = TM.getTargetLowering();
7618 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
7619 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7620 EVT VT = ValueVTs[vti];
7621 unsigned NumRegisters = TLI->getNumRegisters(*DAG.getContext(), VT);
7622 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7623 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7624 Reg += NumRegisters;
7629 ConstantsOut.clear();
7632 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7635 SelectionDAGBuilder::StackProtectorDescriptor::
7636 AddSuccessorMBB(const BasicBlock *BB,
7637 MachineBasicBlock *ParentMBB,
7638 MachineBasicBlock *SuccMBB) {
7639 // If SuccBB has not been created yet, create it.
7641 MachineFunction *MF = ParentMBB->getParent();
7642 MachineFunction::iterator BBI = ParentMBB;
7643 SuccMBB = MF->CreateMachineBasicBlock(BB);
7644 MF->insert(++BBI, SuccMBB);
7646 // Add it as a successor of ParentMBB.
7647 ParentMBB->addSuccessor(SuccMBB);