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/DebugInfo.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.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 /// areValueTypesLegal - Return true if types of all the values are legal.
631 bool areValueTypesLegal(const TargetLowering &TLI) {
632 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
633 MVT RegisterVT = RegVTs[Value];
634 if (!TLI.isTypeLegal(RegisterVT))
640 /// append - Add the specified values to this one.
641 void append(const RegsForValue &RHS) {
642 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
643 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
644 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
647 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
648 /// this value and returns the result as a ValueVTs value. This uses
649 /// Chain/Flag as the input and updates them for the output Chain/Flag.
650 /// If the Flag pointer is NULL, no flag is used.
651 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
653 SDValue &Chain, SDValue *Flag,
654 const Value *V = 0) const;
656 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
657 /// specified value into the registers specified by this object. This uses
658 /// Chain/Flag as the input and updates them for the output Chain/Flag.
659 /// If the Flag pointer is NULL, no flag is used.
660 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
661 SDValue &Chain, SDValue *Flag, const Value *V) const;
663 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
664 /// operand list. This adds the code marker, matching input operand index
665 /// (if applicable), and includes the number of values added into it.
666 void AddInlineAsmOperands(unsigned Kind,
667 bool HasMatching, unsigned MatchingIdx,
669 std::vector<SDValue> &Ops) const;
673 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
674 /// this value and returns the result as a ValueVT value. This uses
675 /// Chain/Flag as the input and updates them for the output Chain/Flag.
676 /// If the Flag pointer is NULL, no flag is used.
677 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
678 FunctionLoweringInfo &FuncInfo,
680 SDValue &Chain, SDValue *Flag,
681 const Value *V) const {
682 // A Value with type {} or [0 x %t] needs no registers.
683 if (ValueVTs.empty())
686 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
688 // Assemble the legal parts into the final values.
689 SmallVector<SDValue, 4> Values(ValueVTs.size());
690 SmallVector<SDValue, 8> Parts;
691 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
692 // Copy the legal parts from the registers.
693 EVT ValueVT = ValueVTs[Value];
694 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
695 MVT RegisterVT = RegVTs[Value];
697 Parts.resize(NumRegs);
698 for (unsigned i = 0; i != NumRegs; ++i) {
701 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
703 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
704 *Flag = P.getValue(2);
707 Chain = P.getValue(1);
710 // If the source register was virtual and if we know something about it,
711 // add an assert node.
712 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
713 !RegisterVT.isInteger() || RegisterVT.isVector())
716 const FunctionLoweringInfo::LiveOutInfo *LOI =
717 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
721 unsigned RegSize = RegisterVT.getSizeInBits();
722 unsigned NumSignBits = LOI->NumSignBits;
723 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
725 if (NumZeroBits == RegSize) {
726 // The current value is a zero.
727 // Explicitly express that as it would be easier for
728 // optimizations to kick in.
729 Parts[i] = DAG.getConstant(0, RegisterVT);
733 // FIXME: We capture more information than the dag can represent. For
734 // now, just use the tightest assertzext/assertsext possible.
736 EVT FromVT(MVT::Other);
737 if (NumSignBits == RegSize)
738 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
739 else if (NumZeroBits >= RegSize-1)
740 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
741 else if (NumSignBits > RegSize-8)
742 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
743 else if (NumZeroBits >= RegSize-8)
744 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
745 else if (NumSignBits > RegSize-16)
746 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
747 else if (NumZeroBits >= RegSize-16)
748 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
749 else if (NumSignBits > RegSize-32)
750 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
751 else if (NumZeroBits >= RegSize-32)
752 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
756 // Add an assertion node.
757 assert(FromVT != MVT::Other);
758 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
759 RegisterVT, P, DAG.getValueType(FromVT));
762 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
763 NumRegs, RegisterVT, ValueVT, V);
768 return DAG.getNode(ISD::MERGE_VALUES, dl,
769 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
770 &Values[0], ValueVTs.size());
773 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
774 /// specified value into the registers specified by this object. This uses
775 /// Chain/Flag as the input and updates them for the output Chain/Flag.
776 /// If the Flag pointer is NULL, no flag is used.
777 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
778 SDValue &Chain, SDValue *Flag,
779 const Value *V) const {
780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
782 // Get the list of the values's legal parts.
783 unsigned NumRegs = Regs.size();
784 SmallVector<SDValue, 8> Parts(NumRegs);
785 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
786 EVT ValueVT = ValueVTs[Value];
787 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
788 MVT RegisterVT = RegVTs[Value];
789 ISD::NodeType ExtendKind =
790 TLI.isZExtFree(Val, RegisterVT)? ISD::ZERO_EXTEND: ISD::ANY_EXTEND;
792 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
793 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
797 // Copy the parts into the registers.
798 SmallVector<SDValue, 8> Chains(NumRegs);
799 for (unsigned i = 0; i != NumRegs; ++i) {
802 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
804 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
805 *Flag = Part.getValue(1);
808 Chains[i] = Part.getValue(0);
811 if (NumRegs == 1 || Flag)
812 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
813 // flagged to it. That is the CopyToReg nodes and the user are considered
814 // a single scheduling unit. If we create a TokenFactor and return it as
815 // chain, then the TokenFactor is both a predecessor (operand) of the
816 // user as well as a successor (the TF operands are flagged to the user).
817 // c1, f1 = CopyToReg
818 // c2, f2 = CopyToReg
819 // c3 = TokenFactor c1, c2
822 Chain = Chains[NumRegs-1];
824 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
827 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
828 /// operand list. This adds the code marker and includes the number of
829 /// values added into it.
830 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
831 unsigned MatchingIdx,
833 std::vector<SDValue> &Ops) const {
834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
836 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
838 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
839 else if (!Regs.empty() &&
840 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
841 // Put the register class of the virtual registers in the flag word. That
842 // way, later passes can recompute register class constraints for inline
843 // assembly as well as normal instructions.
844 // Don't do this for tied operands that can use the regclass information
846 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
847 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
848 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
851 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
854 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
855 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
856 MVT RegisterVT = RegVTs[Value];
857 for (unsigned i = 0; i != NumRegs; ++i) {
858 assert(Reg < Regs.size() && "Mismatch in # registers expected");
859 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
864 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
865 const TargetLibraryInfo *li) {
869 TD = DAG.getTarget().getDataLayout();
870 Context = DAG.getContext();
871 LPadToCallSiteMap.clear();
874 /// clear - Clear out the current SelectionDAG and the associated
875 /// state and prepare this SelectionDAGBuilder object to be used
876 /// for a new block. This doesn't clear out information about
877 /// additional blocks that are needed to complete switch lowering
878 /// or PHI node updating; that information is cleared out as it is
880 void SelectionDAGBuilder::clear() {
882 UnusedArgNodeMap.clear();
883 PendingLoads.clear();
884 PendingExports.clear();
889 /// clearDanglingDebugInfo - Clear the dangling debug information
890 /// map. This function is separated from the clear so that debug
891 /// information that is dangling in a basic block can be properly
892 /// resolved in a different basic block. This allows the
893 /// SelectionDAG to resolve dangling debug information attached
895 void SelectionDAGBuilder::clearDanglingDebugInfo() {
896 DanglingDebugInfoMap.clear();
899 /// getRoot - Return the current virtual root of the Selection DAG,
900 /// flushing any PendingLoad items. This must be done before emitting
901 /// a store or any other node that may need to be ordered after any
902 /// prior load instructions.
904 SDValue SelectionDAGBuilder::getRoot() {
905 if (PendingLoads.empty())
906 return DAG.getRoot();
908 if (PendingLoads.size() == 1) {
909 SDValue Root = PendingLoads[0];
911 PendingLoads.clear();
915 // Otherwise, we have to make a token factor node.
916 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
917 &PendingLoads[0], PendingLoads.size());
918 PendingLoads.clear();
923 /// getControlRoot - Similar to getRoot, but instead of flushing all the
924 /// PendingLoad items, flush all the PendingExports items. It is necessary
925 /// to do this before emitting a terminator instruction.
927 SDValue SelectionDAGBuilder::getControlRoot() {
928 SDValue Root = DAG.getRoot();
930 if (PendingExports.empty())
933 // Turn all of the CopyToReg chains into one factored node.
934 if (Root.getOpcode() != ISD::EntryToken) {
935 unsigned i = 0, e = PendingExports.size();
936 for (; i != e; ++i) {
937 assert(PendingExports[i].getNode()->getNumOperands() > 1);
938 if (PendingExports[i].getNode()->getOperand(0) == Root)
939 break; // Don't add the root if we already indirectly depend on it.
943 PendingExports.push_back(Root);
946 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
948 PendingExports.size());
949 PendingExports.clear();
954 void SelectionDAGBuilder::visit(const Instruction &I) {
955 // Set up outgoing PHI node register values before emitting the terminator.
956 if (isa<TerminatorInst>(&I))
957 HandlePHINodesInSuccessorBlocks(I.getParent());
963 visit(I.getOpcode(), I);
965 if (!isa<TerminatorInst>(&I) && !HasTailCall)
966 CopyToExportRegsIfNeeded(&I);
971 void SelectionDAGBuilder::visitPHI(const PHINode &) {
972 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
975 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
976 // Note: this doesn't use InstVisitor, because it has to work with
977 // ConstantExpr's in addition to instructions.
979 default: llvm_unreachable("Unknown instruction type encountered!");
980 // Build the switch statement using the Instruction.def file.
981 #define HANDLE_INST(NUM, OPCODE, CLASS) \
982 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
983 #include "llvm/IR/Instruction.def"
987 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
988 // generate the debug data structures now that we've seen its definition.
989 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
991 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
993 const DbgValueInst *DI = DDI.getDI();
994 DebugLoc dl = DDI.getdl();
995 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
996 MDNode *Variable = DI->getVariable();
997 uint64_t Offset = DI->getOffset();
1000 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
1001 SDV = DAG.getDbgValue(Variable, Val.getNode(),
1002 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
1003 DAG.AddDbgValue(SDV, Val.getNode(), false);
1006 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1007 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1011 /// getValue - Return an SDValue for the given Value.
1012 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1013 // If we already have an SDValue for this value, use it. It's important
1014 // to do this first, so that we don't create a CopyFromReg if we already
1015 // have a regular SDValue.
1016 SDValue &N = NodeMap[V];
1017 if (N.getNode()) return N;
1019 // If there's a virtual register allocated and initialized for this
1021 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1022 if (It != FuncInfo.ValueMap.end()) {
1023 unsigned InReg = It->second;
1024 RegsForValue RFV(*DAG.getContext(), *TM.getTargetLowering(),
1025 InReg, V->getType());
1026 SDValue Chain = DAG.getEntryNode();
1027 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
1028 resolveDanglingDebugInfo(V, N);
1032 // Otherwise create a new SDValue and remember it.
1033 SDValue Val = getValueImpl(V);
1035 resolveDanglingDebugInfo(V, Val);
1039 /// getNonRegisterValue - Return an SDValue for the given Value, but
1040 /// don't look in FuncInfo.ValueMap for a virtual register.
1041 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1042 // If we already have an SDValue for this value, use it.
1043 SDValue &N = NodeMap[V];
1044 if (N.getNode()) return N;
1046 // Otherwise create a new SDValue and remember it.
1047 SDValue Val = getValueImpl(V);
1049 resolveDanglingDebugInfo(V, Val);
1053 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1054 /// Create an SDValue for the given value.
1055 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1056 const TargetLowering *TLI = TM.getTargetLowering();
1058 if (const Constant *C = dyn_cast<Constant>(V)) {
1059 EVT VT = TLI->getValueType(V->getType(), true);
1061 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1062 return DAG.getConstant(*CI, VT);
1064 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1065 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1067 if (isa<ConstantPointerNull>(C)) {
1068 unsigned AS = V->getType()->getPointerAddressSpace();
1069 return DAG.getConstant(0, TLI->getPointerTy(AS));
1072 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1073 return DAG.getConstantFP(*CFP, VT);
1075 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1076 return DAG.getUNDEF(VT);
1078 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1079 visit(CE->getOpcode(), *CE);
1080 SDValue N1 = NodeMap[V];
1081 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1085 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1086 SmallVector<SDValue, 4> Constants;
1087 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1089 SDNode *Val = getValue(*OI).getNode();
1090 // If the operand is an empty aggregate, there are no values.
1092 // Add each leaf value from the operand to the Constants list
1093 // to form a flattened list of all the values.
1094 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1095 Constants.push_back(SDValue(Val, i));
1098 return DAG.getMergeValues(&Constants[0], Constants.size(),
1102 if (const ConstantDataSequential *CDS =
1103 dyn_cast<ConstantDataSequential>(C)) {
1104 SmallVector<SDValue, 4> Ops;
1105 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1106 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1107 // Add each leaf value from the operand to the Constants list
1108 // to form a flattened list of all the values.
1109 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1110 Ops.push_back(SDValue(Val, i));
1113 if (isa<ArrayType>(CDS->getType()))
1114 return DAG.getMergeValues(&Ops[0], Ops.size(), getCurSDLoc());
1115 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1116 VT, &Ops[0], Ops.size());
1119 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1120 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1121 "Unknown struct or array constant!");
1123 SmallVector<EVT, 4> ValueVTs;
1124 ComputeValueVTs(*TLI, C->getType(), ValueVTs);
1125 unsigned NumElts = ValueVTs.size();
1127 return SDValue(); // empty struct
1128 SmallVector<SDValue, 4> Constants(NumElts);
1129 for (unsigned i = 0; i != NumElts; ++i) {
1130 EVT EltVT = ValueVTs[i];
1131 if (isa<UndefValue>(C))
1132 Constants[i] = DAG.getUNDEF(EltVT);
1133 else if (EltVT.isFloatingPoint())
1134 Constants[i] = DAG.getConstantFP(0, EltVT);
1136 Constants[i] = DAG.getConstant(0, EltVT);
1139 return DAG.getMergeValues(&Constants[0], NumElts,
1143 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1144 return DAG.getBlockAddress(BA, VT);
1146 VectorType *VecTy = cast<VectorType>(V->getType());
1147 unsigned NumElements = VecTy->getNumElements();
1149 // Now that we know the number and type of the elements, get that number of
1150 // elements into the Ops array based on what kind of constant it is.
1151 SmallVector<SDValue, 16> Ops;
1152 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1153 for (unsigned i = 0; i != NumElements; ++i)
1154 Ops.push_back(getValue(CV->getOperand(i)));
1156 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1157 EVT EltVT = TLI->getValueType(VecTy->getElementType());
1160 if (EltVT.isFloatingPoint())
1161 Op = DAG.getConstantFP(0, EltVT);
1163 Op = DAG.getConstant(0, EltVT);
1164 Ops.assign(NumElements, Op);
1167 // Create a BUILD_VECTOR node.
1168 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1169 VT, &Ops[0], Ops.size());
1172 // If this is a static alloca, generate it as the frameindex instead of
1174 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1175 DenseMap<const AllocaInst*, int>::iterator SI =
1176 FuncInfo.StaticAllocaMap.find(AI);
1177 if (SI != FuncInfo.StaticAllocaMap.end())
1178 return DAG.getFrameIndex(SI->second, TLI->getPointerTy());
1181 // If this is an instruction which fast-isel has deferred, select it now.
1182 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1183 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1184 RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType());
1185 SDValue Chain = DAG.getEntryNode();
1186 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
1189 llvm_unreachable("Can't get register for value!");
1192 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1193 const TargetLowering *TLI = TM.getTargetLowering();
1194 SDValue Chain = getControlRoot();
1195 SmallVector<ISD::OutputArg, 8> Outs;
1196 SmallVector<SDValue, 8> OutVals;
1198 if (!FuncInfo.CanLowerReturn) {
1199 unsigned DemoteReg = FuncInfo.DemoteRegister;
1200 const Function *F = I.getParent()->getParent();
1202 // Emit a store of the return value through the virtual register.
1203 // Leave Outs empty so that LowerReturn won't try to load return
1204 // registers the usual way.
1205 SmallVector<EVT, 1> PtrValueVTs;
1206 ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()),
1209 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1210 SDValue RetOp = getValue(I.getOperand(0));
1212 SmallVector<EVT, 4> ValueVTs;
1213 SmallVector<uint64_t, 4> Offsets;
1214 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1215 unsigned NumValues = ValueVTs.size();
1217 SmallVector<SDValue, 4> Chains(NumValues);
1218 for (unsigned i = 0; i != NumValues; ++i) {
1219 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1220 RetPtr.getValueType(), RetPtr,
1221 DAG.getIntPtrConstant(Offsets[i]));
1223 DAG.getStore(Chain, getCurSDLoc(),
1224 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1225 // FIXME: better loc info would be nice.
1226 Add, MachinePointerInfo(), false, false, 0);
1229 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1230 MVT::Other, &Chains[0], NumValues);
1231 } else if (I.getNumOperands() != 0) {
1232 SmallVector<EVT, 4> ValueVTs;
1233 ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs);
1234 unsigned NumValues = ValueVTs.size();
1236 SDValue RetOp = getValue(I.getOperand(0));
1237 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1238 EVT VT = ValueVTs[j];
1240 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1242 const Function *F = I.getParent()->getParent();
1243 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1245 ExtendKind = ISD::SIGN_EXTEND;
1246 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1248 ExtendKind = ISD::ZERO_EXTEND;
1250 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1251 VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind);
1253 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT);
1254 MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT);
1255 SmallVector<SDValue, 4> Parts(NumParts);
1256 getCopyToParts(DAG, getCurSDLoc(),
1257 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1258 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1260 // 'inreg' on function refers to return value
1261 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1262 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1266 // Propagate extension type if any
1267 if (ExtendKind == ISD::SIGN_EXTEND)
1269 else if (ExtendKind == ISD::ZERO_EXTEND)
1272 for (unsigned i = 0; i < NumParts; ++i) {
1273 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1274 VT, /*isfixed=*/true, 0, 0));
1275 OutVals.push_back(Parts[i]);
1281 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1282 CallingConv::ID CallConv =
1283 DAG.getMachineFunction().getFunction()->getCallingConv();
1284 Chain = TM.getTargetLowering()->LowerReturn(Chain, CallConv, isVarArg,
1285 Outs, OutVals, getCurSDLoc(),
1288 // Verify that the target's LowerReturn behaved as expected.
1289 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1290 "LowerReturn didn't return a valid chain!");
1292 // Update the DAG with the new chain value resulting from return lowering.
1296 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1297 /// created for it, emit nodes to copy the value into the virtual
1299 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1301 if (V->getType()->isEmptyTy())
1304 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1305 if (VMI != FuncInfo.ValueMap.end()) {
1306 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1307 CopyValueToVirtualRegister(V, VMI->second);
1311 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1312 /// the current basic block, add it to ValueMap now so that we'll get a
1314 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1315 // No need to export constants.
1316 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1318 // Already exported?
1319 if (FuncInfo.isExportedInst(V)) return;
1321 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1322 CopyValueToVirtualRegister(V, Reg);
1325 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1326 const BasicBlock *FromBB) {
1327 // The operands of the setcc have to be in this block. We don't know
1328 // how to export them from some other block.
1329 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1330 // Can export from current BB.
1331 if (VI->getParent() == FromBB)
1334 // Is already exported, noop.
1335 return FuncInfo.isExportedInst(V);
1338 // If this is an argument, we can export it if the BB is the entry block or
1339 // if it is already exported.
1340 if (isa<Argument>(V)) {
1341 if (FromBB == &FromBB->getParent()->getEntryBlock())
1344 // Otherwise, can only export this if it is already exported.
1345 return FuncInfo.isExportedInst(V);
1348 // Otherwise, constants can always be exported.
1352 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1353 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1354 const MachineBasicBlock *Dst) const {
1355 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1358 const BasicBlock *SrcBB = Src->getBasicBlock();
1359 const BasicBlock *DstBB = Dst->getBasicBlock();
1360 return BPI->getEdgeWeight(SrcBB, DstBB);
1363 void SelectionDAGBuilder::
1364 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1365 uint32_t Weight /* = 0 */) {
1367 Weight = getEdgeWeight(Src, Dst);
1368 Src->addSuccessor(Dst, Weight);
1372 static bool InBlock(const Value *V, const BasicBlock *BB) {
1373 if (const Instruction *I = dyn_cast<Instruction>(V))
1374 return I->getParent() == BB;
1378 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1379 /// This function emits a branch and is used at the leaves of an OR or an
1380 /// AND operator tree.
1383 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1384 MachineBasicBlock *TBB,
1385 MachineBasicBlock *FBB,
1386 MachineBasicBlock *CurBB,
1387 MachineBasicBlock *SwitchBB) {
1388 const BasicBlock *BB = CurBB->getBasicBlock();
1390 // If the leaf of the tree is a comparison, merge the condition into
1392 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1393 // The operands of the cmp have to be in this block. We don't know
1394 // how to export them from some other block. If this is the first block
1395 // of the sequence, no exporting is needed.
1396 if (CurBB == SwitchBB ||
1397 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1398 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1399 ISD::CondCode Condition;
1400 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1401 Condition = getICmpCondCode(IC->getPredicate());
1402 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1403 Condition = getFCmpCondCode(FC->getPredicate());
1404 if (TM.Options.NoNaNsFPMath)
1405 Condition = getFCmpCodeWithoutNaN(Condition);
1407 Condition = ISD::SETEQ; // silence warning.
1408 llvm_unreachable("Unknown compare instruction");
1411 CaseBlock CB(Condition, BOp->getOperand(0),
1412 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1413 SwitchCases.push_back(CB);
1418 // Create a CaseBlock record representing this branch.
1419 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1420 NULL, TBB, FBB, CurBB);
1421 SwitchCases.push_back(CB);
1424 /// FindMergedConditions - If Cond is an expression like
1425 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1426 MachineBasicBlock *TBB,
1427 MachineBasicBlock *FBB,
1428 MachineBasicBlock *CurBB,
1429 MachineBasicBlock *SwitchBB,
1431 // If this node is not part of the or/and tree, emit it as a branch.
1432 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1433 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1434 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1435 BOp->getParent() != CurBB->getBasicBlock() ||
1436 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1437 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1438 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1442 // Create TmpBB after CurBB.
1443 MachineFunction::iterator BBI = CurBB;
1444 MachineFunction &MF = DAG.getMachineFunction();
1445 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1446 CurBB->getParent()->insert(++BBI, TmpBB);
1448 if (Opc == Instruction::Or) {
1449 // Codegen X | Y as:
1457 // Emit the LHS condition.
1458 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1460 // Emit the RHS condition into TmpBB.
1461 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1463 assert(Opc == Instruction::And && "Unknown merge op!");
1464 // Codegen X & Y as:
1471 // This requires creation of TmpBB after CurBB.
1473 // Emit the LHS condition.
1474 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1476 // Emit the RHS condition into TmpBB.
1477 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1481 /// If the set of cases should be emitted as a series of branches, return true.
1482 /// If we should emit this as a bunch of and/or'd together conditions, return
1485 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1486 if (Cases.size() != 2) return true;
1488 // If this is two comparisons of the same values or'd or and'd together, they
1489 // will get folded into a single comparison, so don't emit two blocks.
1490 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1491 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1492 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1493 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1497 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1498 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1499 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1500 Cases[0].CC == Cases[1].CC &&
1501 isa<Constant>(Cases[0].CmpRHS) &&
1502 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1503 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1505 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1512 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1513 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1515 // Update machine-CFG edges.
1516 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1518 // Figure out which block is immediately after the current one.
1519 MachineBasicBlock *NextBlock = 0;
1520 MachineFunction::iterator BBI = BrMBB;
1521 if (++BBI != FuncInfo.MF->end())
1524 if (I.isUnconditional()) {
1525 // Update machine-CFG edges.
1526 BrMBB->addSuccessor(Succ0MBB);
1528 // If this is not a fall-through branch, emit the branch.
1529 if (Succ0MBB != NextBlock)
1530 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1531 MVT::Other, getControlRoot(),
1532 DAG.getBasicBlock(Succ0MBB)));
1537 // If this condition is one of the special cases we handle, do special stuff
1539 const Value *CondVal = I.getCondition();
1540 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1542 // If this is a series of conditions that are or'd or and'd together, emit
1543 // this as a sequence of branches instead of setcc's with and/or operations.
1544 // As long as jumps are not expensive, this should improve performance.
1545 // For example, instead of something like:
1558 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1559 if (!TM.getTargetLowering()->isJumpExpensive() &&
1561 (BOp->getOpcode() == Instruction::And ||
1562 BOp->getOpcode() == Instruction::Or)) {
1563 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1565 // If the compares in later blocks need to use values not currently
1566 // exported from this block, export them now. This block should always
1567 // be the first entry.
1568 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1570 // Allow some cases to be rejected.
1571 if (ShouldEmitAsBranches(SwitchCases)) {
1572 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1573 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1574 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1577 // Emit the branch for this block.
1578 visitSwitchCase(SwitchCases[0], BrMBB);
1579 SwitchCases.erase(SwitchCases.begin());
1583 // Okay, we decided not to do this, remove any inserted MBB's and clear
1585 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1586 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1588 SwitchCases.clear();
1592 // Create a CaseBlock record representing this branch.
1593 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1594 NULL, Succ0MBB, Succ1MBB, BrMBB);
1596 // Use visitSwitchCase to actually insert the fast branch sequence for this
1598 visitSwitchCase(CB, BrMBB);
1601 /// visitSwitchCase - Emits the necessary code to represent a single node in
1602 /// the binary search tree resulting from lowering a switch instruction.
1603 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1604 MachineBasicBlock *SwitchBB) {
1606 SDValue CondLHS = getValue(CB.CmpLHS);
1607 SDLoc dl = getCurSDLoc();
1609 // Build the setcc now.
1610 if (CB.CmpMHS == NULL) {
1611 // Fold "(X == true)" to X and "(X == false)" to !X to
1612 // handle common cases produced by branch lowering.
1613 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1614 CB.CC == ISD::SETEQ)
1616 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1617 CB.CC == ISD::SETEQ) {
1618 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1619 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1621 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1623 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1625 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1626 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1628 SDValue CmpOp = getValue(CB.CmpMHS);
1629 EVT VT = CmpOp.getValueType();
1631 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1632 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1635 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1636 VT, CmpOp, DAG.getConstant(Low, VT));
1637 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1638 DAG.getConstant(High-Low, VT), ISD::SETULE);
1642 // Update successor info
1643 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1644 // TrueBB and FalseBB are always different unless the incoming IR is
1645 // degenerate. This only happens when running llc on weird IR.
1646 if (CB.TrueBB != CB.FalseBB)
1647 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1649 // Set NextBlock to be the MBB immediately after the current one, if any.
1650 // This is used to avoid emitting unnecessary branches to the next block.
1651 MachineBasicBlock *NextBlock = 0;
1652 MachineFunction::iterator BBI = SwitchBB;
1653 if (++BBI != FuncInfo.MF->end())
1656 // If the lhs block is the next block, invert the condition so that we can
1657 // fall through to the lhs instead of the rhs block.
1658 if (CB.TrueBB == NextBlock) {
1659 std::swap(CB.TrueBB, CB.FalseBB);
1660 SDValue True = DAG.getConstant(1, Cond.getValueType());
1661 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1664 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1665 MVT::Other, getControlRoot(), Cond,
1666 DAG.getBasicBlock(CB.TrueBB));
1668 // Insert the false branch. Do this even if it's a fall through branch,
1669 // this makes it easier to do DAG optimizations which require inverting
1670 // the branch condition.
1671 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1672 DAG.getBasicBlock(CB.FalseBB));
1674 DAG.setRoot(BrCond);
1677 /// visitJumpTable - Emit JumpTable node in the current MBB
1678 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1679 // Emit the code for the jump table
1680 assert(JT.Reg != -1U && "Should lower JT Header first!");
1681 EVT PTy = TM.getTargetLowering()->getPointerTy();
1682 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1684 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1685 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1686 MVT::Other, Index.getValue(1),
1688 DAG.setRoot(BrJumpTable);
1691 /// visitJumpTableHeader - This function emits necessary code to produce index
1692 /// in the JumpTable from switch case.
1693 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1694 JumpTableHeader &JTH,
1695 MachineBasicBlock *SwitchBB) {
1696 // Subtract the lowest switch case value from the value being switched on and
1697 // conditional branch to default mbb if the result is greater than the
1698 // difference between smallest and largest cases.
1699 SDValue SwitchOp = getValue(JTH.SValue);
1700 EVT VT = SwitchOp.getValueType();
1701 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1702 DAG.getConstant(JTH.First, VT));
1704 // The SDNode we just created, which holds the value being switched on minus
1705 // the smallest case value, needs to be copied to a virtual register so it
1706 // can be used as an index into the jump table in a subsequent basic block.
1707 // This value may be smaller or larger than the target's pointer type, and
1708 // therefore require extension or truncating.
1709 const TargetLowering *TLI = TM.getTargetLowering();
1710 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy());
1712 unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy());
1713 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1714 JumpTableReg, SwitchOp);
1715 JT.Reg = JumpTableReg;
1717 // Emit the range check for the jump table, and branch to the default block
1718 // for the switch statement if the value being switched on exceeds the largest
1719 // case in the switch.
1720 SDValue CMP = DAG.getSetCC(getCurSDLoc(),
1721 TLI->getSetCCResultType(*DAG.getContext(),
1722 Sub.getValueType()),
1724 DAG.getConstant(JTH.Last - JTH.First,VT),
1727 // Set NextBlock to be the MBB immediately after the current one, if any.
1728 // This is used to avoid emitting unnecessary branches to the next block.
1729 MachineBasicBlock *NextBlock = 0;
1730 MachineFunction::iterator BBI = SwitchBB;
1732 if (++BBI != FuncInfo.MF->end())
1735 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1736 MVT::Other, CopyTo, CMP,
1737 DAG.getBasicBlock(JT.Default));
1739 if (JT.MBB != NextBlock)
1740 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1741 DAG.getBasicBlock(JT.MBB));
1743 DAG.setRoot(BrCond);
1746 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1747 /// tail spliced into a stack protector check success bb.
1749 /// For a high level explanation of how this fits into the stack protector
1750 /// generation see the comment on the declaration of class
1751 /// StackProtectorDescriptor.
1752 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1753 MachineBasicBlock *ParentBB) {
1755 // First create the loads to the guard/stack slot for the comparison.
1756 const TargetLowering *TLI = TM.getTargetLowering();
1757 EVT PtrTy = TLI->getPointerTy();
1759 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1760 int FI = MFI->getStackProtectorIndex();
1762 const Value *IRGuard = SPD.getGuard();
1763 SDValue GuardPtr = getValue(IRGuard);
1764 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1767 TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1768 SDValue Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1769 GuardPtr, MachinePointerInfo(IRGuard, 0),
1770 true, false, false, Align);
1772 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1774 MachinePointerInfo::getFixedStack(FI),
1775 true, false, false, Align);
1777 // Perform the comparison via a subtract/getsetcc.
1778 EVT VT = Guard.getValueType();
1779 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1781 SDValue Cmp = DAG.getSetCC(getCurSDLoc(),
1782 TLI->getSetCCResultType(*DAG.getContext(),
1783 Sub.getValueType()),
1784 Sub, DAG.getConstant(0, VT),
1787 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1788 // branch to failure MBB.
1789 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1790 MVT::Other, StackSlot.getOperand(0),
1791 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1792 // Otherwise branch to success MBB.
1793 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1795 DAG.getBasicBlock(SPD.getSuccessMBB()));
1800 /// Codegen the failure basic block for a stack protector check.
1802 /// A failure stack protector machine basic block consists simply of a call to
1803 /// __stack_chk_fail().
1805 /// For a high level explanation of how this fits into the stack protector
1806 /// generation see the comment on the declaration of class
1807 /// StackProtectorDescriptor.
1809 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1810 const TargetLowering *TLI = TM.getTargetLowering();
1811 SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
1812 MVT::isVoid, 0, 0, false, getCurSDLoc(),
1813 false, false).second;
1817 /// visitBitTestHeader - This function emits necessary code to produce value
1818 /// suitable for "bit tests"
1819 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1820 MachineBasicBlock *SwitchBB) {
1821 // Subtract the minimum value
1822 SDValue SwitchOp = getValue(B.SValue);
1823 EVT VT = SwitchOp.getValueType();
1824 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1825 DAG.getConstant(B.First, VT));
1828 const TargetLowering *TLI = TM.getTargetLowering();
1829 SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(),
1830 TLI->getSetCCResultType(*DAG.getContext(),
1831 Sub.getValueType()),
1832 Sub, DAG.getConstant(B.Range, VT),
1835 // Determine the type of the test operands.
1836 bool UsePtrType = false;
1837 if (!TLI->isTypeLegal(VT))
1840 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1841 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1842 // Switch table case range are encoded into series of masks.
1843 // Just use pointer type, it's guaranteed to fit.
1849 VT = TLI->getPointerTy();
1850 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1853 B.RegVT = VT.getSimpleVT();
1854 B.Reg = FuncInfo.CreateReg(B.RegVT);
1855 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1858 // Set NextBlock to be the MBB immediately after the current one, if any.
1859 // This is used to avoid emitting unnecessary branches to the next block.
1860 MachineBasicBlock *NextBlock = 0;
1861 MachineFunction::iterator BBI = SwitchBB;
1862 if (++BBI != FuncInfo.MF->end())
1865 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1867 addSuccessorWithWeight(SwitchBB, B.Default);
1868 addSuccessorWithWeight(SwitchBB, MBB);
1870 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1871 MVT::Other, CopyTo, RangeCmp,
1872 DAG.getBasicBlock(B.Default));
1874 if (MBB != NextBlock)
1875 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1876 DAG.getBasicBlock(MBB));
1878 DAG.setRoot(BrRange);
1881 /// visitBitTestCase - this function produces one "bit test"
1882 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1883 MachineBasicBlock* NextMBB,
1884 uint32_t BranchWeightToNext,
1887 MachineBasicBlock *SwitchBB) {
1889 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1892 unsigned PopCount = CountPopulation_64(B.Mask);
1893 const TargetLowering *TLI = TM.getTargetLowering();
1894 if (PopCount == 1) {
1895 // Testing for a single bit; just compare the shift count with what it
1896 // would need to be to shift a 1 bit in that position.
1897 Cmp = DAG.getSetCC(getCurSDLoc(),
1898 TLI->getSetCCResultType(*DAG.getContext(), VT),
1900 DAG.getConstant(countTrailingZeros(B.Mask), VT),
1902 } else if (PopCount == BB.Range) {
1903 // There is only one zero bit in the range, test for it directly.
1904 Cmp = DAG.getSetCC(getCurSDLoc(),
1905 TLI->getSetCCResultType(*DAG.getContext(), VT),
1907 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1910 // Make desired shift
1911 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1912 DAG.getConstant(1, VT), ShiftOp);
1914 // Emit bit tests and jumps
1915 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1916 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1917 Cmp = DAG.getSetCC(getCurSDLoc(),
1918 TLI->getSetCCResultType(*DAG.getContext(), VT),
1919 AndOp, DAG.getConstant(0, VT),
1923 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1924 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1925 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1926 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1928 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1929 MVT::Other, getControlRoot(),
1930 Cmp, DAG.getBasicBlock(B.TargetBB));
1932 // Set NextBlock to be the MBB immediately after the current one, if any.
1933 // This is used to avoid emitting unnecessary branches to the next block.
1934 MachineBasicBlock *NextBlock = 0;
1935 MachineFunction::iterator BBI = SwitchBB;
1936 if (++BBI != FuncInfo.MF->end())
1939 if (NextMBB != NextBlock)
1940 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
1941 DAG.getBasicBlock(NextMBB));
1946 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1947 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1949 // Retrieve successors.
1950 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1951 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1953 const Value *Callee(I.getCalledValue());
1954 const Function *Fn = dyn_cast<Function>(Callee);
1955 if (isa<InlineAsm>(Callee))
1957 else if (Fn && Fn->isIntrinsic()) {
1958 assert(Fn->getIntrinsicID() == Intrinsic::donothing);
1959 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
1961 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1963 // If the value of the invoke is used outside of its defining block, make it
1964 // available as a virtual register.
1965 CopyToExportRegsIfNeeded(&I);
1967 // Update successor info
1968 addSuccessorWithWeight(InvokeMBB, Return);
1969 addSuccessorWithWeight(InvokeMBB, LandingPad);
1971 // Drop into normal successor.
1972 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1973 MVT::Other, getControlRoot(),
1974 DAG.getBasicBlock(Return)));
1977 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
1978 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
1981 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
1982 assert(FuncInfo.MBB->isLandingPad() &&
1983 "Call to landingpad not in landing pad!");
1985 MachineBasicBlock *MBB = FuncInfo.MBB;
1986 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
1987 AddLandingPadInfo(LP, MMI, MBB);
1989 // If there aren't registers to copy the values into (e.g., during SjLj
1990 // exceptions), then don't bother to create these DAG nodes.
1991 const TargetLowering *TLI = TM.getTargetLowering();
1992 if (TLI->getExceptionPointerRegister() == 0 &&
1993 TLI->getExceptionSelectorRegister() == 0)
1996 SmallVector<EVT, 2> ValueVTs;
1997 ComputeValueVTs(*TLI, LP.getType(), ValueVTs);
1998 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2000 // Get the two live-in registers as SDValues. The physregs have already been
2001 // copied into virtual registers.
2003 Ops[0] = DAG.getZExtOrTrunc(
2004 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2005 FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()),
2006 getCurSDLoc(), ValueVTs[0]);
2007 Ops[1] = DAG.getZExtOrTrunc(
2008 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2009 FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()),
2010 getCurSDLoc(), ValueVTs[1]);
2013 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2014 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
2019 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2020 /// small case ranges).
2021 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2022 CaseRecVector& WorkList,
2024 MachineBasicBlock *Default,
2025 MachineBasicBlock *SwitchBB) {
2026 // Size is the number of Cases represented by this range.
2027 size_t Size = CR.Range.second - CR.Range.first;
2031 // Get the MachineFunction which holds the current MBB. This is used when
2032 // inserting any additional MBBs necessary to represent the switch.
2033 MachineFunction *CurMF = FuncInfo.MF;
2035 // Figure out which block is immediately after the current one.
2036 MachineBasicBlock *NextBlock = 0;
2037 MachineFunction::iterator BBI = CR.CaseBB;
2039 if (++BBI != FuncInfo.MF->end())
2042 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2043 // If any two of the cases has the same destination, and if one value
2044 // is the same as the other, but has one bit unset that the other has set,
2045 // use bit manipulation to do two compares at once. For example:
2046 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2047 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2048 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2049 if (Size == 2 && CR.CaseBB == SwitchBB) {
2050 Case &Small = *CR.Range.first;
2051 Case &Big = *(CR.Range.second-1);
2053 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2054 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2055 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2057 // Check that there is only one bit different.
2058 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2059 (SmallValue | BigValue) == BigValue) {
2060 // Isolate the common bit.
2061 APInt CommonBit = BigValue & ~SmallValue;
2062 assert((SmallValue | CommonBit) == BigValue &&
2063 CommonBit.countPopulation() == 1 && "Not a common bit?");
2065 SDValue CondLHS = getValue(SV);
2066 EVT VT = CondLHS.getValueType();
2067 SDLoc DL = getCurSDLoc();
2069 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2070 DAG.getConstant(CommonBit, VT));
2071 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2072 Or, DAG.getConstant(BigValue, VT),
2075 // Update successor info.
2076 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2077 addSuccessorWithWeight(SwitchBB, Small.BB,
2078 Small.ExtraWeight + Big.ExtraWeight);
2079 addSuccessorWithWeight(SwitchBB, Default,
2080 // The default destination is the first successor in IR.
2081 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2083 // Insert the true branch.
2084 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2085 getControlRoot(), Cond,
2086 DAG.getBasicBlock(Small.BB));
2088 // Insert the false branch.
2089 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2090 DAG.getBasicBlock(Default));
2092 DAG.setRoot(BrCond);
2098 // Order cases by weight so the most likely case will be checked first.
2099 uint32_t UnhandledWeights = 0;
2101 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2102 uint32_t IWeight = I->ExtraWeight;
2103 UnhandledWeights += IWeight;
2104 for (CaseItr J = CR.Range.first; J < I; ++J) {
2105 uint32_t JWeight = J->ExtraWeight;
2106 if (IWeight > JWeight)
2111 // Rearrange the case blocks so that the last one falls through if possible.
2112 Case &BackCase = *(CR.Range.second-1);
2114 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2115 // The last case block won't fall through into 'NextBlock' if we emit the
2116 // branches in this order. See if rearranging a case value would help.
2117 // We start at the bottom as it's the case with the least weight.
2118 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2119 if (I->BB == NextBlock) {
2120 std::swap(*I, BackCase);
2125 // Create a CaseBlock record representing a conditional branch to
2126 // the Case's target mbb if the value being switched on SV is equal
2128 MachineBasicBlock *CurBlock = CR.CaseBB;
2129 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2130 MachineBasicBlock *FallThrough;
2132 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2133 CurMF->insert(BBI, FallThrough);
2135 // Put SV in a virtual register to make it available from the new blocks.
2136 ExportFromCurrentBlock(SV);
2138 // If the last case doesn't match, go to the default block.
2139 FallThrough = Default;
2142 const Value *RHS, *LHS, *MHS;
2144 if (I->High == I->Low) {
2145 // This is just small small case range :) containing exactly 1 case
2147 LHS = SV; RHS = I->High; MHS = NULL;
2150 LHS = I->Low; MHS = SV; RHS = I->High;
2153 // The false weight should be sum of all un-handled cases.
2154 UnhandledWeights -= I->ExtraWeight;
2155 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2157 /* trueweight */ I->ExtraWeight,
2158 /* falseweight */ UnhandledWeights);
2160 // If emitting the first comparison, just call visitSwitchCase to emit the
2161 // code into the current block. Otherwise, push the CaseBlock onto the
2162 // vector to be later processed by SDISel, and insert the node's MBB
2163 // before the next MBB.
2164 if (CurBlock == SwitchBB)
2165 visitSwitchCase(CB, SwitchBB);
2167 SwitchCases.push_back(CB);
2169 CurBlock = FallThrough;
2175 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2176 return TLI.supportJumpTables() &&
2177 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2178 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
2181 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2182 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2183 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2184 return (LastExt - FirstExt + 1ULL);
2187 /// handleJTSwitchCase - Emit jumptable for current switch case range
2188 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2189 CaseRecVector &WorkList,
2191 MachineBasicBlock *Default,
2192 MachineBasicBlock *SwitchBB) {
2193 Case& FrontCase = *CR.Range.first;
2194 Case& BackCase = *(CR.Range.second-1);
2196 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2197 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2199 APInt TSize(First.getBitWidth(), 0);
2200 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2203 const TargetLowering *TLI = TM.getTargetLowering();
2204 if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries()))
2207 APInt Range = ComputeRange(First, Last);
2208 // The density is TSize / Range. Require at least 40%.
2209 // It should not be possible for IntTSize to saturate for sane code, but make
2210 // sure we handle Range saturation correctly.
2211 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2212 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2213 if (IntTSize * 10 < IntRange * 4)
2216 DEBUG(dbgs() << "Lowering jump table\n"
2217 << "First entry: " << First << ". Last entry: " << Last << '\n'
2218 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2220 // Get the MachineFunction which holds the current MBB. This is used when
2221 // inserting any additional MBBs necessary to represent the switch.
2222 MachineFunction *CurMF = FuncInfo.MF;
2224 // Figure out which block is immediately after the current one.
2225 MachineFunction::iterator BBI = CR.CaseBB;
2228 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2230 // Create a new basic block to hold the code for loading the address
2231 // of the jump table, and jumping to it. Update successor information;
2232 // we will either branch to the default case for the switch, or the jump
2234 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2235 CurMF->insert(BBI, JumpTableBB);
2237 addSuccessorWithWeight(CR.CaseBB, Default);
2238 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2240 // Build a vector of destination BBs, corresponding to each target
2241 // of the jump table. If the value of the jump table slot corresponds to
2242 // a case statement, push the case's BB onto the vector, otherwise, push
2244 std::vector<MachineBasicBlock*> DestBBs;
2246 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2247 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2248 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2250 if (Low.sle(TEI) && TEI.sle(High)) {
2251 DestBBs.push_back(I->BB);
2255 DestBBs.push_back(Default);
2259 // Calculate weight for each unique destination in CR.
2260 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2262 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2263 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2264 DestWeights.find(I->BB);
2265 if (Itr != DestWeights.end())
2266 Itr->second += I->ExtraWeight;
2268 DestWeights[I->BB] = I->ExtraWeight;
2271 // Update successor info. Add one edge to each unique successor.
2272 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2273 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2274 E = DestBBs.end(); I != E; ++I) {
2275 if (!SuccsHandled[(*I)->getNumber()]) {
2276 SuccsHandled[(*I)->getNumber()] = true;
2277 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2278 DestWeights.find(*I);
2279 addSuccessorWithWeight(JumpTableBB, *I,
2280 Itr != DestWeights.end() ? Itr->second : 0);
2284 // Create a jump table index for this jump table.
2285 unsigned JTEncoding = TLI->getJumpTableEncoding();
2286 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2287 ->createJumpTableIndex(DestBBs);
2289 // Set the jump table information so that we can codegen it as a second
2290 // MachineBasicBlock
2291 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2292 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2293 if (CR.CaseBB == SwitchBB)
2294 visitJumpTableHeader(JT, JTH, SwitchBB);
2296 JTCases.push_back(JumpTableBlock(JTH, JT));
2300 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2302 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2303 CaseRecVector& WorkList,
2305 MachineBasicBlock* Default,
2306 MachineBasicBlock* SwitchBB) {
2307 // Get the MachineFunction which holds the current MBB. This is used when
2308 // inserting any additional MBBs necessary to represent the switch.
2309 MachineFunction *CurMF = FuncInfo.MF;
2311 // Figure out which block is immediately after the current one.
2312 MachineFunction::iterator BBI = CR.CaseBB;
2315 Case& FrontCase = *CR.Range.first;
2316 Case& BackCase = *(CR.Range.second-1);
2317 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2319 // Size is the number of Cases represented by this range.
2320 unsigned Size = CR.Range.second - CR.Range.first;
2322 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2323 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2325 CaseItr Pivot = CR.Range.first + Size/2;
2327 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2328 // (heuristically) allow us to emit JumpTable's later.
2329 APInt TSize(First.getBitWidth(), 0);
2330 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2334 APInt LSize = FrontCase.size();
2335 APInt RSize = TSize-LSize;
2336 DEBUG(dbgs() << "Selecting best pivot: \n"
2337 << "First: " << First << ", Last: " << Last <<'\n'
2338 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2339 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2341 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2342 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2343 APInt Range = ComputeRange(LEnd, RBegin);
2344 assert((Range - 2ULL).isNonNegative() &&
2345 "Invalid case distance");
2346 // Use volatile double here to avoid excess precision issues on some hosts,
2347 // e.g. that use 80-bit X87 registers.
2348 volatile double LDensity =
2349 (double)LSize.roundToDouble() /
2350 (LEnd - First + 1ULL).roundToDouble();
2351 volatile double RDensity =
2352 (double)RSize.roundToDouble() /
2353 (Last - RBegin + 1ULL).roundToDouble();
2354 double Metric = Range.logBase2()*(LDensity+RDensity);
2355 // Should always split in some non-trivial place
2356 DEBUG(dbgs() <<"=>Step\n"
2357 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2358 << "LDensity: " << LDensity
2359 << ", RDensity: " << RDensity << '\n'
2360 << "Metric: " << Metric << '\n');
2361 if (FMetric < Metric) {
2364 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2371 const TargetLowering *TLI = TM.getTargetLowering();
2372 if (areJTsAllowed(*TLI)) {
2373 // If our case is dense we *really* should handle it earlier!
2374 assert((FMetric > 0) && "Should handle dense range earlier!");
2376 Pivot = CR.Range.first + Size/2;
2379 CaseRange LHSR(CR.Range.first, Pivot);
2380 CaseRange RHSR(Pivot, CR.Range.second);
2381 const Constant *C = Pivot->Low;
2382 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2384 // We know that we branch to the LHS if the Value being switched on is
2385 // less than the Pivot value, C. We use this to optimize our binary
2386 // tree a bit, by recognizing that if SV is greater than or equal to the
2387 // LHS's Case Value, and that Case Value is exactly one less than the
2388 // Pivot's Value, then we can branch directly to the LHS's Target,
2389 // rather than creating a leaf node for it.
2390 if ((LHSR.second - LHSR.first) == 1 &&
2391 LHSR.first->High == CR.GE &&
2392 cast<ConstantInt>(C)->getValue() ==
2393 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2394 TrueBB = LHSR.first->BB;
2396 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2397 CurMF->insert(BBI, TrueBB);
2398 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2400 // Put SV in a virtual register to make it available from the new blocks.
2401 ExportFromCurrentBlock(SV);
2404 // Similar to the optimization above, if the Value being switched on is
2405 // known to be less than the Constant CR.LT, and the current Case Value
2406 // is CR.LT - 1, then we can branch directly to the target block for
2407 // the current Case Value, rather than emitting a RHS leaf node for it.
2408 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2409 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2410 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2411 FalseBB = RHSR.first->BB;
2413 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2414 CurMF->insert(BBI, FalseBB);
2415 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2417 // Put SV in a virtual register to make it available from the new blocks.
2418 ExportFromCurrentBlock(SV);
2421 // Create a CaseBlock record representing a conditional branch to
2422 // the LHS node if the value being switched on SV is less than C.
2423 // Otherwise, branch to LHS.
2424 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2426 if (CR.CaseBB == SwitchBB)
2427 visitSwitchCase(CB, SwitchBB);
2429 SwitchCases.push_back(CB);
2434 /// handleBitTestsSwitchCase - if current case range has few destination and
2435 /// range span less, than machine word bitwidth, encode case range into series
2436 /// of masks and emit bit tests with these masks.
2437 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2438 CaseRecVector& WorkList,
2440 MachineBasicBlock* Default,
2441 MachineBasicBlock* SwitchBB) {
2442 const TargetLowering *TLI = TM.getTargetLowering();
2443 EVT PTy = TLI->getPointerTy();
2444 unsigned IntPtrBits = PTy.getSizeInBits();
2446 Case& FrontCase = *CR.Range.first;
2447 Case& BackCase = *(CR.Range.second-1);
2449 // Get the MachineFunction which holds the current MBB. This is used when
2450 // inserting any additional MBBs necessary to represent the switch.
2451 MachineFunction *CurMF = FuncInfo.MF;
2453 // If target does not have legal shift left, do not emit bit tests at all.
2454 if (!TLI->isOperationLegal(ISD::SHL, PTy))
2458 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2460 // Single case counts one, case range - two.
2461 numCmps += (I->Low == I->High ? 1 : 2);
2464 // Count unique destinations
2465 SmallSet<MachineBasicBlock*, 4> Dests;
2466 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2467 Dests.insert(I->BB);
2468 if (Dests.size() > 3)
2469 // Don't bother the code below, if there are too much unique destinations
2472 DEBUG(dbgs() << "Total number of unique destinations: "
2473 << Dests.size() << '\n'
2474 << "Total number of comparisons: " << numCmps << '\n');
2476 // Compute span of values.
2477 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2478 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2479 APInt cmpRange = maxValue - minValue;
2481 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2482 << "Low bound: " << minValue << '\n'
2483 << "High bound: " << maxValue << '\n');
2485 if (cmpRange.uge(IntPtrBits) ||
2486 (!(Dests.size() == 1 && numCmps >= 3) &&
2487 !(Dests.size() == 2 && numCmps >= 5) &&
2488 !(Dests.size() >= 3 && numCmps >= 6)))
2491 DEBUG(dbgs() << "Emitting bit tests\n");
2492 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2494 // Optimize the case where all the case values fit in a
2495 // word without having to subtract minValue. In this case,
2496 // we can optimize away the subtraction.
2497 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2498 cmpRange = maxValue;
2500 lowBound = minValue;
2503 CaseBitsVector CasesBits;
2504 unsigned i, count = 0;
2506 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2507 MachineBasicBlock* Dest = I->BB;
2508 for (i = 0; i < count; ++i)
2509 if (Dest == CasesBits[i].BB)
2513 assert((count < 3) && "Too much destinations to test!");
2514 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2518 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2519 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2521 uint64_t lo = (lowValue - lowBound).getZExtValue();
2522 uint64_t hi = (highValue - lowBound).getZExtValue();
2523 CasesBits[i].ExtraWeight += I->ExtraWeight;
2525 for (uint64_t j = lo; j <= hi; j++) {
2526 CasesBits[i].Mask |= 1ULL << j;
2527 CasesBits[i].Bits++;
2531 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2535 // Figure out which block is immediately after the current one.
2536 MachineFunction::iterator BBI = CR.CaseBB;
2539 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2541 DEBUG(dbgs() << "Cases:\n");
2542 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2543 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2544 << ", Bits: " << CasesBits[i].Bits
2545 << ", BB: " << CasesBits[i].BB << '\n');
2547 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2548 CurMF->insert(BBI, CaseBB);
2549 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2551 CasesBits[i].BB, CasesBits[i].ExtraWeight));
2553 // Put SV in a virtual register to make it available from the new blocks.
2554 ExportFromCurrentBlock(SV);
2557 BitTestBlock BTB(lowBound, cmpRange, SV,
2558 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2559 CR.CaseBB, Default, BTC);
2561 if (CR.CaseBB == SwitchBB)
2562 visitBitTestHeader(BTB, SwitchBB);
2564 BitTestCases.push_back(BTB);
2569 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2570 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2571 const SwitchInst& SI) {
2574 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2575 // Start with "simple" cases
2576 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
2578 const BasicBlock *SuccBB = i.getCaseSuccessor();
2579 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2581 uint32_t ExtraWeight =
2582 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2584 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2585 SMBB, ExtraWeight));
2587 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2589 // Merge case into clusters
2590 if (Cases.size() >= 2)
2591 // Must recompute end() each iteration because it may be
2592 // invalidated by erase if we hold on to it
2593 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
2594 J != Cases.end(); ) {
2595 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2596 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2597 MachineBasicBlock* nextBB = J->BB;
2598 MachineBasicBlock* currentBB = I->BB;
2600 // If the two neighboring cases go to the same destination, merge them
2601 // into a single case.
2602 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2604 I->ExtraWeight += J->ExtraWeight;
2611 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2612 if (I->Low != I->High)
2613 // A range counts double, since it requires two compares.
2620 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2621 MachineBasicBlock *Last) {
2623 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2624 if (JTCases[i].first.HeaderBB == First)
2625 JTCases[i].first.HeaderBB = Last;
2627 // Update BitTestCases.
2628 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2629 if (BitTestCases[i].Parent == First)
2630 BitTestCases[i].Parent = Last;
2633 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2634 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2636 // Figure out which block is immediately after the current one.
2637 MachineBasicBlock *NextBlock = 0;
2638 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2640 // If there is only the default destination, branch to it if it is not the
2641 // next basic block. Otherwise, just fall through.
2642 if (!SI.getNumCases()) {
2643 // Update machine-CFG edges.
2645 // If this is not a fall-through branch, emit the branch.
2646 SwitchMBB->addSuccessor(Default);
2647 if (Default != NextBlock)
2648 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2649 MVT::Other, getControlRoot(),
2650 DAG.getBasicBlock(Default)));
2655 // If there are any non-default case statements, create a vector of Cases
2656 // representing each one, and sort the vector so that we can efficiently
2657 // create a binary search tree from them.
2659 size_t numCmps = Clusterify(Cases, SI);
2660 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2661 << ". Total compares: " << numCmps << '\n');
2664 // Get the Value to be switched on and default basic blocks, which will be
2665 // inserted into CaseBlock records, representing basic blocks in the binary
2667 const Value *SV = SI.getCondition();
2669 // Push the initial CaseRec onto the worklist
2670 CaseRecVector WorkList;
2671 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2672 CaseRange(Cases.begin(),Cases.end())));
2674 while (!WorkList.empty()) {
2675 // Grab a record representing a case range to process off the worklist
2676 CaseRec CR = WorkList.back();
2677 WorkList.pop_back();
2679 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2682 // If the range has few cases (two or less) emit a series of specific
2684 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2687 // If the switch has more than N blocks, and is at least 40% dense, and the
2688 // target supports indirect branches, then emit a jump table rather than
2689 // lowering the switch to a binary tree of conditional branches.
2690 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2691 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2694 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2695 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2696 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2700 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2701 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2703 // Update machine-CFG edges with unique successors.
2704 SmallSet<BasicBlock*, 32> Done;
2705 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2706 BasicBlock *BB = I.getSuccessor(i);
2707 bool Inserted = Done.insert(BB);
2711 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2712 addSuccessorWithWeight(IndirectBrMBB, Succ);
2715 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2716 MVT::Other, getControlRoot(),
2717 getValue(I.getAddress())));
2720 void SelectionDAGBuilder::visitFSub(const User &I) {
2721 // -0.0 - X --> fneg
2722 Type *Ty = I.getType();
2723 if (isa<Constant>(I.getOperand(0)) &&
2724 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2725 SDValue Op2 = getValue(I.getOperand(1));
2726 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2727 Op2.getValueType(), Op2));
2731 visitBinary(I, ISD::FSUB);
2734 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2735 SDValue Op1 = getValue(I.getOperand(0));
2736 SDValue Op2 = getValue(I.getOperand(1));
2737 setValue(&I, DAG.getNode(OpCode, getCurSDLoc(),
2738 Op1.getValueType(), Op1, Op2));
2741 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2742 SDValue Op1 = getValue(I.getOperand(0));
2743 SDValue Op2 = getValue(I.getOperand(1));
2745 EVT ShiftTy = TM.getTargetLowering()->getShiftAmountTy(Op2.getValueType());
2747 // Coerce the shift amount to the right type if we can.
2748 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2749 unsigned ShiftSize = ShiftTy.getSizeInBits();
2750 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2751 SDLoc DL = getCurSDLoc();
2753 // If the operand is smaller than the shift count type, promote it.
2754 if (ShiftSize > Op2Size)
2755 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2757 // If the operand is larger than the shift count type but the shift
2758 // count type has enough bits to represent any shift value, truncate
2759 // it now. This is a common case and it exposes the truncate to
2760 // optimization early.
2761 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2762 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2763 // Otherwise we'll need to temporarily settle for some other convenient
2764 // type. Type legalization will make adjustments once the shiftee is split.
2766 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2769 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(),
2770 Op1.getValueType(), Op1, Op2));
2773 void SelectionDAGBuilder::visitSDiv(const User &I) {
2774 SDValue Op1 = getValue(I.getOperand(0));
2775 SDValue Op2 = getValue(I.getOperand(1));
2777 // Turn exact SDivs into multiplications.
2778 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2780 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2781 !isa<ConstantSDNode>(Op1) &&
2782 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2783 setValue(&I, TM.getTargetLowering()->BuildExactSDIV(Op1, Op2,
2784 getCurSDLoc(), DAG));
2786 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2790 void SelectionDAGBuilder::visitICmp(const User &I) {
2791 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2792 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2793 predicate = IC->getPredicate();
2794 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2795 predicate = ICmpInst::Predicate(IC->getPredicate());
2796 SDValue Op1 = getValue(I.getOperand(0));
2797 SDValue Op2 = getValue(I.getOperand(1));
2798 ISD::CondCode Opcode = getICmpCondCode(predicate);
2800 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2801 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2804 void SelectionDAGBuilder::visitFCmp(const User &I) {
2805 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2806 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2807 predicate = FC->getPredicate();
2808 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2809 predicate = FCmpInst::Predicate(FC->getPredicate());
2810 SDValue Op1 = getValue(I.getOperand(0));
2811 SDValue Op2 = getValue(I.getOperand(1));
2812 ISD::CondCode Condition = getFCmpCondCode(predicate);
2813 if (TM.Options.NoNaNsFPMath)
2814 Condition = getFCmpCodeWithoutNaN(Condition);
2815 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2816 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2819 void SelectionDAGBuilder::visitSelect(const User &I) {
2820 SmallVector<EVT, 4> ValueVTs;
2821 ComputeValueVTs(*TM.getTargetLowering(), I.getType(), ValueVTs);
2822 unsigned NumValues = ValueVTs.size();
2823 if (NumValues == 0) return;
2825 SmallVector<SDValue, 4> Values(NumValues);
2826 SDValue Cond = getValue(I.getOperand(0));
2827 SDValue TrueVal = getValue(I.getOperand(1));
2828 SDValue FalseVal = getValue(I.getOperand(2));
2829 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2830 ISD::VSELECT : ISD::SELECT;
2832 for (unsigned i = 0; i != NumValues; ++i)
2833 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2834 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2836 SDValue(TrueVal.getNode(),
2837 TrueVal.getResNo() + i),
2838 SDValue(FalseVal.getNode(),
2839 FalseVal.getResNo() + i));
2841 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2842 DAG.getVTList(&ValueVTs[0], NumValues),
2843 &Values[0], NumValues));
2846 void SelectionDAGBuilder::visitTrunc(const User &I) {
2847 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2848 SDValue N = getValue(I.getOperand(0));
2849 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2850 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2853 void SelectionDAGBuilder::visitZExt(const User &I) {
2854 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2855 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2856 SDValue N = getValue(I.getOperand(0));
2857 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2858 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2861 void SelectionDAGBuilder::visitSExt(const User &I) {
2862 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2863 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2864 SDValue N = getValue(I.getOperand(0));
2865 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2866 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2869 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2870 // FPTrunc is never a no-op cast, no need to check
2871 SDValue N = getValue(I.getOperand(0));
2872 const TargetLowering *TLI = TM.getTargetLowering();
2873 EVT DestVT = TLI->getValueType(I.getType());
2874 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(),
2876 DAG.getTargetConstant(0, TLI->getPointerTy())));
2879 void SelectionDAGBuilder::visitFPExt(const User &I) {
2880 // FPExt is never a no-op cast, no need to check
2881 SDValue N = getValue(I.getOperand(0));
2882 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2883 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2886 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2887 // FPToUI is never a no-op cast, no need to check
2888 SDValue N = getValue(I.getOperand(0));
2889 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2890 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2893 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2894 // FPToSI is never a no-op cast, no need to check
2895 SDValue N = getValue(I.getOperand(0));
2896 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2897 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2900 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2901 // UIToFP is never a no-op cast, no need to check
2902 SDValue N = getValue(I.getOperand(0));
2903 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2904 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2907 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2908 // SIToFP is never a no-op cast, no need to check
2909 SDValue N = getValue(I.getOperand(0));
2910 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2911 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2914 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2915 // What to do depends on the size of the integer and the size of the pointer.
2916 // We can either truncate, zero extend, or no-op, accordingly.
2917 SDValue N = getValue(I.getOperand(0));
2918 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2919 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2922 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2923 // What to do depends on the size of the integer and the size of the pointer.
2924 // We can either truncate, zero extend, or no-op, accordingly.
2925 SDValue N = getValue(I.getOperand(0));
2926 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2927 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2930 void SelectionDAGBuilder::visitBitCast(const User &I) {
2931 SDValue N = getValue(I.getOperand(0));
2932 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2934 // BitCast assures us that source and destination are the same size so this is
2935 // either a BITCAST or a no-op.
2936 if (DestVT != N.getValueType())
2937 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
2938 DestVT, N)); // convert types.
2940 setValue(&I, N); // noop cast.
2943 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2944 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2945 const Value *SV = I.getOperand(0);
2946 SDValue N = getValue(SV);
2947 EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
2949 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
2950 unsigned DestAS = I.getType()->getPointerAddressSpace();
2952 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2953 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
2958 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2959 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2960 SDValue InVec = getValue(I.getOperand(0));
2961 SDValue InVal = getValue(I.getOperand(1));
2962 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
2963 getCurSDLoc(), TLI.getVectorIdxTy());
2964 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
2965 TM.getTargetLowering()->getValueType(I.getType()),
2966 InVec, InVal, InIdx));
2969 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2970 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2971 SDValue InVec = getValue(I.getOperand(0));
2972 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
2973 getCurSDLoc(), TLI.getVectorIdxTy());
2974 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
2975 TM.getTargetLowering()->getValueType(I.getType()),
2979 // Utility for visitShuffleVector - Return true if every element in Mask,
2980 // beginning from position Pos and ending in Pos+Size, falls within the
2981 // specified sequential range [L, L+Pos). or is undef.
2982 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
2983 unsigned Pos, unsigned Size, int Low) {
2984 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
2985 if (Mask[i] >= 0 && Mask[i] != Low)
2990 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2991 SDValue Src1 = getValue(I.getOperand(0));
2992 SDValue Src2 = getValue(I.getOperand(1));
2994 SmallVector<int, 8> Mask;
2995 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2996 unsigned MaskNumElts = Mask.size();
2998 const TargetLowering *TLI = TM.getTargetLowering();
2999 EVT VT = TLI->getValueType(I.getType());
3000 EVT SrcVT = Src1.getValueType();
3001 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3003 if (SrcNumElts == MaskNumElts) {
3004 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3009 // Normalize the shuffle vector since mask and vector length don't match.
3010 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3011 // Mask is longer than the source vectors and is a multiple of the source
3012 // vectors. We can use concatenate vector to make the mask and vectors
3014 if (SrcNumElts*2 == MaskNumElts) {
3015 // First check for Src1 in low and Src2 in high
3016 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3017 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3018 // The shuffle is concatenating two vectors together.
3019 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3023 // Then check for Src2 in low and Src1 in high
3024 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3025 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3026 // The shuffle is concatenating two vectors together.
3027 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3033 // Pad both vectors with undefs to make them the same length as the mask.
3034 unsigned NumConcat = MaskNumElts / SrcNumElts;
3035 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3036 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
3037 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3039 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3040 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3044 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3046 &MOps1[0], NumConcat);
3047 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3049 &MOps2[0], NumConcat);
3051 // Readjust mask for new input vector length.
3052 SmallVector<int, 8> MappedOps;
3053 for (unsigned i = 0; i != MaskNumElts; ++i) {
3055 if (Idx >= (int)SrcNumElts)
3056 Idx -= SrcNumElts - MaskNumElts;
3057 MappedOps.push_back(Idx);
3060 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3065 if (SrcNumElts > MaskNumElts) {
3066 // Analyze the access pattern of the vector to see if we can extract
3067 // two subvectors and do the shuffle. The analysis is done by calculating
3068 // the range of elements the mask access on both vectors.
3069 int MinRange[2] = { static_cast<int>(SrcNumElts),
3070 static_cast<int>(SrcNumElts)};
3071 int MaxRange[2] = {-1, -1};
3073 for (unsigned i = 0; i != MaskNumElts; ++i) {
3079 if (Idx >= (int)SrcNumElts) {
3083 if (Idx > MaxRange[Input])
3084 MaxRange[Input] = Idx;
3085 if (Idx < MinRange[Input])
3086 MinRange[Input] = Idx;
3089 // Check if the access is smaller than the vector size and can we find
3090 // a reasonable extract index.
3091 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3093 int StartIdx[2]; // StartIdx to extract from
3094 for (unsigned Input = 0; Input < 2; ++Input) {
3095 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
3096 RangeUse[Input] = 0; // Unused
3097 StartIdx[Input] = 0;
3101 // Find a good start index that is a multiple of the mask length. Then
3102 // see if the rest of the elements are in range.
3103 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3104 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3105 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3106 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3109 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3110 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3113 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3114 // Extract appropriate subvector and generate a vector shuffle
3115 for (unsigned Input = 0; Input < 2; ++Input) {
3116 SDValue &Src = Input == 0 ? Src1 : Src2;
3117 if (RangeUse[Input] == 0)
3118 Src = DAG.getUNDEF(VT);
3120 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT,
3121 Src, DAG.getConstant(StartIdx[Input],
3122 TLI->getVectorIdxTy()));
3125 // Calculate new mask.
3126 SmallVector<int, 8> MappedOps;
3127 for (unsigned i = 0; i != MaskNumElts; ++i) {
3130 if (Idx < (int)SrcNumElts)
3133 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3135 MappedOps.push_back(Idx);
3138 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3144 // We can't use either concat vectors or extract subvectors so fall back to
3145 // replacing the shuffle with extract and build vector.
3146 // to insert and build vector.
3147 EVT EltVT = VT.getVectorElementType();
3148 EVT IdxVT = TLI->getVectorIdxTy();
3149 SmallVector<SDValue,8> Ops;
3150 for (unsigned i = 0; i != MaskNumElts; ++i) {
3155 Res = DAG.getUNDEF(EltVT);
3157 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3158 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3160 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3161 EltVT, Src, DAG.getConstant(Idx, IdxVT));
3167 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
3168 VT, &Ops[0], Ops.size()));
3171 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3172 const Value *Op0 = I.getOperand(0);
3173 const Value *Op1 = I.getOperand(1);
3174 Type *AggTy = I.getType();
3175 Type *ValTy = Op1->getType();
3176 bool IntoUndef = isa<UndefValue>(Op0);
3177 bool FromUndef = isa<UndefValue>(Op1);
3179 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3181 const TargetLowering *TLI = TM.getTargetLowering();
3182 SmallVector<EVT, 4> AggValueVTs;
3183 ComputeValueVTs(*TLI, AggTy, AggValueVTs);
3184 SmallVector<EVT, 4> ValValueVTs;
3185 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
3187 unsigned NumAggValues = AggValueVTs.size();
3188 unsigned NumValValues = ValValueVTs.size();
3189 SmallVector<SDValue, 4> Values(NumAggValues);
3191 SDValue Agg = getValue(Op0);
3193 // Copy the beginning value(s) from the original aggregate.
3194 for (; i != LinearIndex; ++i)
3195 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3196 SDValue(Agg.getNode(), Agg.getResNo() + i);
3197 // Copy values from the inserted value(s).
3199 SDValue Val = getValue(Op1);
3200 for (; i != LinearIndex + NumValValues; ++i)
3201 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3202 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3204 // Copy remaining value(s) from the original aggregate.
3205 for (; i != NumAggValues; ++i)
3206 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3207 SDValue(Agg.getNode(), Agg.getResNo() + i);
3209 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3210 DAG.getVTList(&AggValueVTs[0], NumAggValues),
3211 &Values[0], NumAggValues));
3214 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3215 const Value *Op0 = I.getOperand(0);
3216 Type *AggTy = Op0->getType();
3217 Type *ValTy = I.getType();
3218 bool OutOfUndef = isa<UndefValue>(Op0);
3220 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3222 const TargetLowering *TLI = TM.getTargetLowering();
3223 SmallVector<EVT, 4> ValValueVTs;
3224 ComputeValueVTs(*TLI, ValTy, ValValueVTs);
3226 unsigned NumValValues = ValValueVTs.size();
3228 // Ignore a extractvalue that produces an empty object
3229 if (!NumValValues) {
3230 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3234 SmallVector<SDValue, 4> Values(NumValValues);
3236 SDValue Agg = getValue(Op0);
3237 // Copy out the selected value(s).
3238 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3239 Values[i - LinearIndex] =
3241 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3242 SDValue(Agg.getNode(), Agg.getResNo() + i);
3244 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3245 DAG.getVTList(&ValValueVTs[0], NumValValues),
3246 &Values[0], NumValValues));
3249 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3250 Value *Op0 = I.getOperand(0);
3251 // Note that the pointer operand may be a vector of pointers. Take the scalar
3252 // element which holds a pointer.
3253 Type *Ty = Op0->getType()->getScalarType();
3254 unsigned AS = Ty->getPointerAddressSpace();
3255 SDValue N = getValue(Op0);
3257 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3259 const Value *Idx = *OI;
3260 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3261 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3264 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
3265 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3266 DAG.getConstant(Offset, N.getValueType()));
3269 Ty = StTy->getElementType(Field);
3271 Ty = cast<SequentialType>(Ty)->getElementType();
3273 // If this is a constant subscript, handle it quickly.
3274 const TargetLowering *TLI = TM.getTargetLowering();
3275 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3276 if (CI->isZero()) continue;
3278 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3280 EVT PTy = TLI->getPointerTy(AS);
3281 unsigned PtrBits = PTy.getSizeInBits();
3283 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
3284 DAG.getConstant(Offs, MVT::i64));
3286 OffsVal = DAG.getConstant(Offs, PTy);
3288 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3293 // N = N + Idx * ElementSize;
3294 APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS),
3295 TD->getTypeAllocSize(Ty));
3296 SDValue IdxN = getValue(Idx);
3298 // If the index is smaller or larger than intptr_t, truncate or extend
3300 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
3302 // If this is a multiply by a power of two, turn it into a shl
3303 // immediately. This is a very common case.
3304 if (ElementSize != 1) {
3305 if (ElementSize.isPowerOf2()) {
3306 unsigned Amt = ElementSize.logBase2();
3307 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
3308 N.getValueType(), IdxN,
3309 DAG.getConstant(Amt, IdxN.getValueType()));
3311 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
3312 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
3313 N.getValueType(), IdxN, Scale);
3317 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
3318 N.getValueType(), N, IdxN);
3325 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3326 // If this is a fixed sized alloca in the entry block of the function,
3327 // allocate it statically on the stack.
3328 if (FuncInfo.StaticAllocaMap.count(&I))
3329 return; // getValue will auto-populate this.
3331 Type *Ty = I.getAllocatedType();
3332 const TargetLowering *TLI = TM.getTargetLowering();
3333 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
3335 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
3338 SDValue AllocSize = getValue(I.getArraySize());
3340 EVT IntPtr = TLI->getPointerTy();
3341 if (AllocSize.getValueType() != IntPtr)
3342 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
3344 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
3346 DAG.getConstant(TySize, IntPtr));
3348 // Handle alignment. If the requested alignment is less than or equal to
3349 // the stack alignment, ignore it. If the size is greater than or equal to
3350 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3351 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
3352 if (Align <= StackAlign)
3355 // Round the size of the allocation up to the stack alignment size
3356 // by add SA-1 to the size.
3357 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
3358 AllocSize.getValueType(), AllocSize,
3359 DAG.getIntPtrConstant(StackAlign-1));
3361 // Mask out the low bits for alignment purposes.
3362 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
3363 AllocSize.getValueType(), AllocSize,
3364 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3366 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3367 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3368 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(),
3371 DAG.setRoot(DSA.getValue(1));
3373 // Inform the Frame Information that we have just allocated a variable-sized
3375 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
3378 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3380 return visitAtomicLoad(I);
3382 const Value *SV = I.getOperand(0);
3383 SDValue Ptr = getValue(SV);
3385 Type *Ty = I.getType();
3387 bool isVolatile = I.isVolatile();
3388 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3389 bool isInvariant = I.getMetadata("invariant.load") != 0;
3390 unsigned Alignment = I.getAlignment();
3391 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3392 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3394 SmallVector<EVT, 4> ValueVTs;
3395 SmallVector<uint64_t, 4> Offsets;
3396 ComputeValueVTs(*TM.getTargetLowering(), Ty, ValueVTs, &Offsets);
3397 unsigned NumValues = ValueVTs.size();
3402 bool ConstantMemory = false;
3403 if (I.isVolatile() || NumValues > MaxParallelChains)
3404 // Serialize volatile loads with other side effects.
3406 else if (AA->pointsToConstantMemory(
3407 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
3408 // Do not serialize (non-volatile) loads of constant memory with anything.
3409 Root = DAG.getEntryNode();
3410 ConstantMemory = true;
3412 // Do not serialize non-volatile loads against each other.
3413 Root = DAG.getRoot();
3416 SmallVector<SDValue, 4> Values(NumValues);
3417 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3419 EVT PtrVT = Ptr.getValueType();
3420 unsigned ChainI = 0;
3421 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3422 // Serializing loads here may result in excessive register pressure, and
3423 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3424 // could recover a bit by hoisting nodes upward in the chain by recognizing
3425 // they are side-effect free or do not alias. The optimizer should really
3426 // avoid this case by converting large object/array copies to llvm.memcpy
3427 // (MaxParallelChains should always remain as failsafe).
3428 if (ChainI == MaxParallelChains) {
3429 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3430 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3431 MVT::Other, &Chains[0], ChainI);
3435 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
3437 DAG.getConstant(Offsets[i], PtrVT));
3438 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
3439 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3440 isNonTemporal, isInvariant, Alignment, TBAAInfo,
3444 Chains[ChainI] = L.getValue(1);
3447 if (!ConstantMemory) {
3448 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3449 MVT::Other, &Chains[0], ChainI);
3453 PendingLoads.push_back(Chain);
3456 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3457 DAG.getVTList(&ValueVTs[0], NumValues),
3458 &Values[0], NumValues));
3461 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3463 return visitAtomicStore(I);
3465 const Value *SrcV = I.getOperand(0);
3466 const Value *PtrV = I.getOperand(1);
3468 SmallVector<EVT, 4> ValueVTs;
3469 SmallVector<uint64_t, 4> Offsets;
3470 ComputeValueVTs(*TM.getTargetLowering(), SrcV->getType(), ValueVTs, &Offsets);
3471 unsigned NumValues = ValueVTs.size();
3475 // Get the lowered operands. Note that we do this after
3476 // checking if NumResults is zero, because with zero results
3477 // the operands won't have values in the map.
3478 SDValue Src = getValue(SrcV);
3479 SDValue Ptr = getValue(PtrV);
3481 SDValue Root = getRoot();
3482 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3484 EVT PtrVT = Ptr.getValueType();
3485 bool isVolatile = I.isVolatile();
3486 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3487 unsigned Alignment = I.getAlignment();
3488 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3490 unsigned ChainI = 0;
3491 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3492 // See visitLoad comments.
3493 if (ChainI == MaxParallelChains) {
3494 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3495 MVT::Other, &Chains[0], ChainI);
3499 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
3500 DAG.getConstant(Offsets[i], PtrVT));
3501 SDValue St = DAG.getStore(Root, getCurSDLoc(),
3502 SDValue(Src.getNode(), Src.getResNo() + i),
3503 Add, MachinePointerInfo(PtrV, Offsets[i]),
3504 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3505 Chains[ChainI] = St;
3508 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
3509 MVT::Other, &Chains[0], ChainI);
3510 DAG.setRoot(StoreNode);
3513 static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
3514 SynchronizationScope Scope,
3515 bool Before, SDLoc dl,
3517 const TargetLowering &TLI) {
3518 // Fence, if necessary
3520 if (Order == AcquireRelease || Order == SequentiallyConsistent)
3522 else if (Order == Acquire || Order == Monotonic)
3525 if (Order == AcquireRelease)
3527 else if (Order == Release || Order == Monotonic)
3532 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3533 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
3534 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
3537 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3538 SDLoc dl = getCurSDLoc();
3539 AtomicOrdering Order = I.getOrdering();
3540 SynchronizationScope Scope = I.getSynchScope();
3542 SDValue InChain = getRoot();
3544 const TargetLowering *TLI = TM.getTargetLowering();
3545 if (TLI->getInsertFencesForAtomic())
3546 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3550 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
3551 getValue(I.getCompareOperand()).getSimpleValueType(),
3553 getValue(I.getPointerOperand()),
3554 getValue(I.getCompareOperand()),
3555 getValue(I.getNewValOperand()),
3556 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
3557 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3560 SDValue OutChain = L.getValue(1);
3562 if (TLI->getInsertFencesForAtomic())
3563 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3567 DAG.setRoot(OutChain);
3570 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3571 SDLoc dl = getCurSDLoc();
3573 switch (I.getOperation()) {
3574 default: llvm_unreachable("Unknown atomicrmw operation");
3575 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3576 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3577 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3578 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3579 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3580 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3581 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3582 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3583 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3584 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3585 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3587 AtomicOrdering Order = I.getOrdering();
3588 SynchronizationScope Scope = I.getSynchScope();
3590 SDValue InChain = getRoot();
3592 const TargetLowering *TLI = TM.getTargetLowering();
3593 if (TLI->getInsertFencesForAtomic())
3594 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3598 DAG.getAtomic(NT, dl,
3599 getValue(I.getValOperand()).getSimpleValueType(),
3601 getValue(I.getPointerOperand()),
3602 getValue(I.getValOperand()),
3603 I.getPointerOperand(), 0 /* Alignment */,
3604 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3607 SDValue OutChain = L.getValue(1);
3609 if (TLI->getInsertFencesForAtomic())
3610 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3614 DAG.setRoot(OutChain);
3617 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3618 SDLoc dl = getCurSDLoc();
3619 const TargetLowering *TLI = TM.getTargetLowering();
3622 Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy());
3623 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy());
3624 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
3627 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3628 SDLoc dl = getCurSDLoc();
3629 AtomicOrdering Order = I.getOrdering();
3630 SynchronizationScope Scope = I.getSynchScope();
3632 SDValue InChain = getRoot();
3634 const TargetLowering *TLI = TM.getTargetLowering();
3635 EVT VT = TLI->getValueType(I.getType());
3637 if (I.getAlignment() < VT.getSizeInBits() / 8)
3638 report_fatal_error("Cannot generate unaligned atomic load");
3641 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3642 getValue(I.getPointerOperand()),
3643 I.getPointerOperand(), I.getAlignment(),
3644 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3647 SDValue OutChain = L.getValue(1);
3649 if (TLI->getInsertFencesForAtomic())
3650 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3654 DAG.setRoot(OutChain);
3657 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3658 SDLoc dl = getCurSDLoc();
3660 AtomicOrdering Order = I.getOrdering();
3661 SynchronizationScope Scope = I.getSynchScope();
3663 SDValue InChain = getRoot();
3665 const TargetLowering *TLI = TM.getTargetLowering();
3666 EVT VT = TLI->getValueType(I.getValueOperand()->getType());
3668 if (I.getAlignment() < VT.getSizeInBits() / 8)
3669 report_fatal_error("Cannot generate unaligned atomic store");
3671 if (TLI->getInsertFencesForAtomic())
3672 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3676 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3678 getValue(I.getPointerOperand()),
3679 getValue(I.getValueOperand()),
3680 I.getPointerOperand(), I.getAlignment(),
3681 TLI->getInsertFencesForAtomic() ? Monotonic : Order,
3684 if (TLI->getInsertFencesForAtomic())
3685 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3688 DAG.setRoot(OutChain);
3691 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3693 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3694 unsigned Intrinsic) {
3695 bool HasChain = !I.doesNotAccessMemory();
3696 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3698 // Build the operand list.
3699 SmallVector<SDValue, 8> Ops;
3700 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3702 // We don't need to serialize loads against other loads.
3703 Ops.push_back(DAG.getRoot());
3705 Ops.push_back(getRoot());
3709 // Info is set by getTgtMemInstrinsic
3710 TargetLowering::IntrinsicInfo Info;
3711 const TargetLowering *TLI = TM.getTargetLowering();
3712 bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic);
3714 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3715 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3716 Info.opc == ISD::INTRINSIC_W_CHAIN)
3717 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy()));
3719 // Add all operands of the call to the operand list.
3720 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3721 SDValue Op = getValue(I.getArgOperand(i));
3725 SmallVector<EVT, 4> ValueVTs;
3726 ComputeValueVTs(*TLI, I.getType(), ValueVTs);
3729 ValueVTs.push_back(MVT::Other);
3731 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3735 if (IsTgtIntrinsic) {
3736 // This is target intrinsic that touches memory
3737 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3738 VTs, &Ops[0], Ops.size(),
3740 MachinePointerInfo(Info.ptrVal, Info.offset),
3741 Info.align, Info.vol,
3742 Info.readMem, Info.writeMem);
3743 } else if (!HasChain) {
3744 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(),
3745 VTs, &Ops[0], Ops.size());
3746 } else if (!I.getType()->isVoidTy()) {
3747 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(),
3748 VTs, &Ops[0], Ops.size());
3750 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(),
3751 VTs, &Ops[0], Ops.size());
3755 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3757 PendingLoads.push_back(Chain);
3762 if (!I.getType()->isVoidTy()) {
3763 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3764 EVT VT = TLI->getValueType(PTy);
3765 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3768 setValue(&I, Result);
3772 /// GetSignificand - Get the significand and build it into a floating-point
3773 /// number with exponent of 1:
3775 /// Op = (Op & 0x007fffff) | 0x3f800000;
3777 /// where Op is the hexadecimal representation of floating point value.
3779 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3780 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3781 DAG.getConstant(0x007fffff, MVT::i32));
3782 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3783 DAG.getConstant(0x3f800000, MVT::i32));
3784 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3787 /// GetExponent - Get the exponent:
3789 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3791 /// where Op is the hexadecimal representation of floating point value.
3793 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3795 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3796 DAG.getConstant(0x7f800000, MVT::i32));
3797 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3798 DAG.getConstant(23, TLI.getPointerTy()));
3799 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3800 DAG.getConstant(127, MVT::i32));
3801 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3804 /// getF32Constant - Get 32-bit floating point constant.
3806 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3807 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3811 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
3812 /// limited-precision mode.
3813 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3814 const TargetLowering &TLI) {
3815 if (Op.getValueType() == MVT::f32 &&
3816 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3818 // Put the exponent in the right bit position for later addition to the
3821 // #define LOG2OFe 1.4426950f
3822 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3823 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3824 getF32Constant(DAG, 0x3fb8aa3b));
3825 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3827 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3828 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3829 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3831 // IntegerPartOfX <<= 23;
3832 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3833 DAG.getConstant(23, TLI.getPointerTy()));
3835 SDValue TwoToFracPartOfX;
3836 if (LimitFloatPrecision <= 6) {
3837 // For floating-point precision of 6:
3839 // TwoToFractionalPartOfX =
3841 // (0.735607626f + 0.252464424f * x) * x;
3843 // error 0.0144103317, which is 6 bits
3844 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3845 getF32Constant(DAG, 0x3e814304));
3846 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3847 getF32Constant(DAG, 0x3f3c50c8));
3848 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3849 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3850 getF32Constant(DAG, 0x3f7f5e7e));
3851 } else if (LimitFloatPrecision <= 12) {
3852 // For floating-point precision of 12:
3854 // TwoToFractionalPartOfX =
3857 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3859 // 0.000107046256 error, which is 13 to 14 bits
3860 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3861 getF32Constant(DAG, 0x3da235e3));
3862 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3863 getF32Constant(DAG, 0x3e65b8f3));
3864 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3865 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3866 getF32Constant(DAG, 0x3f324b07));
3867 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3868 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3869 getF32Constant(DAG, 0x3f7ff8fd));
3870 } else { // LimitFloatPrecision <= 18
3871 // For floating-point precision of 18:
3873 // TwoToFractionalPartOfX =
3877 // (0.554906021e-1f +
3878 // (0.961591928e-2f +
3879 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3881 // error 2.47208000*10^(-7), which is better than 18 bits
3882 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3883 getF32Constant(DAG, 0x3924b03e));
3884 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3885 getF32Constant(DAG, 0x3ab24b87));
3886 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3887 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3888 getF32Constant(DAG, 0x3c1d8c17));
3889 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3890 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3891 getF32Constant(DAG, 0x3d634a1d));
3892 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3893 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3894 getF32Constant(DAG, 0x3e75fe14));
3895 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3896 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3897 getF32Constant(DAG, 0x3f317234));
3898 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3899 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3900 getF32Constant(DAG, 0x3f800000));
3903 // Add the exponent into the result in integer domain.
3904 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
3905 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3906 DAG.getNode(ISD::ADD, dl, MVT::i32,
3907 t13, IntegerPartOfX));
3910 // No special expansion.
3911 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
3914 /// expandLog - Lower a log intrinsic. Handles the special sequences for
3915 /// limited-precision mode.
3916 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3917 const TargetLowering &TLI) {
3918 if (Op.getValueType() == MVT::f32 &&
3919 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3920 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3922 // Scale the exponent by log(2) [0.69314718f].
3923 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3924 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3925 getF32Constant(DAG, 0x3f317218));
3927 // Get the significand and build it into a floating-point number with
3929 SDValue X = GetSignificand(DAG, Op1, dl);
3931 SDValue LogOfMantissa;
3932 if (LimitFloatPrecision <= 6) {
3933 // For floating-point precision of 6:
3937 // (1.4034025f - 0.23903021f * x) * x;
3939 // error 0.0034276066, which is better than 8 bits
3940 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3941 getF32Constant(DAG, 0xbe74c456));
3942 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3943 getF32Constant(DAG, 0x3fb3a2b1));
3944 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3945 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3946 getF32Constant(DAG, 0x3f949a29));
3947 } else if (LimitFloatPrecision <= 12) {
3948 // For floating-point precision of 12:
3954 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3956 // error 0.000061011436, which is 14 bits
3957 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3958 getF32Constant(DAG, 0xbd67b6d6));
3959 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3960 getF32Constant(DAG, 0x3ee4f4b8));
3961 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3962 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3963 getF32Constant(DAG, 0x3fbc278b));
3964 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3965 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3966 getF32Constant(DAG, 0x40348e95));
3967 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3968 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3969 getF32Constant(DAG, 0x3fdef31a));
3970 } else { // LimitFloatPrecision <= 18
3971 // For floating-point precision of 18:
3979 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3981 // error 0.0000023660568, which is better than 18 bits
3982 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3983 getF32Constant(DAG, 0xbc91e5ac));
3984 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3985 getF32Constant(DAG, 0x3e4350aa));
3986 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3987 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3988 getF32Constant(DAG, 0x3f60d3e3));
3989 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3990 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3991 getF32Constant(DAG, 0x4011cdf0));
3992 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3993 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3994 getF32Constant(DAG, 0x406cfd1c));
3995 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3996 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3997 getF32Constant(DAG, 0x408797cb));
3998 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3999 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4000 getF32Constant(DAG, 0x4006dcab));
4003 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4006 // No special expansion.
4007 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4010 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4011 /// limited-precision mode.
4012 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4013 const TargetLowering &TLI) {
4014 if (Op.getValueType() == MVT::f32 &&
4015 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4016 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4018 // Get the exponent.
4019 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4021 // Get the significand and build it into a floating-point number with
4023 SDValue X = GetSignificand(DAG, Op1, dl);
4025 // Different possible minimax approximations of significand in
4026 // floating-point for various degrees of accuracy over [1,2].
4027 SDValue Log2ofMantissa;
4028 if (LimitFloatPrecision <= 6) {
4029 // For floating-point precision of 6:
4031 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4033 // error 0.0049451742, which is more than 7 bits
4034 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4035 getF32Constant(DAG, 0xbeb08fe0));
4036 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4037 getF32Constant(DAG, 0x40019463));
4038 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4039 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4040 getF32Constant(DAG, 0x3fd6633d));
4041 } else if (LimitFloatPrecision <= 12) {
4042 // For floating-point precision of 12:
4048 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4050 // error 0.0000876136000, which is better than 13 bits
4051 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4052 getF32Constant(DAG, 0xbda7262e));
4053 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4054 getF32Constant(DAG, 0x3f25280b));
4055 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4056 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4057 getF32Constant(DAG, 0x4007b923));
4058 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4059 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4060 getF32Constant(DAG, 0x40823e2f));
4061 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4062 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4063 getF32Constant(DAG, 0x4020d29c));
4064 } else { // LimitFloatPrecision <= 18
4065 // For floating-point precision of 18:
4074 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4076 // error 0.0000018516, which is better than 18 bits
4077 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4078 getF32Constant(DAG, 0xbcd2769e));
4079 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4080 getF32Constant(DAG, 0x3e8ce0b9));
4081 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4082 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4083 getF32Constant(DAG, 0x3fa22ae7));
4084 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4085 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4086 getF32Constant(DAG, 0x40525723));
4087 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4088 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4089 getF32Constant(DAG, 0x40aaf200));
4090 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4091 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4092 getF32Constant(DAG, 0x40c39dad));
4093 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4094 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4095 getF32Constant(DAG, 0x4042902c));
4098 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4101 // No special expansion.
4102 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4105 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4106 /// limited-precision mode.
4107 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4108 const TargetLowering &TLI) {
4109 if (Op.getValueType() == MVT::f32 &&
4110 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4111 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4113 // Scale the exponent by log10(2) [0.30102999f].
4114 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4115 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4116 getF32Constant(DAG, 0x3e9a209a));
4118 // Get the significand and build it into a floating-point number with
4120 SDValue X = GetSignificand(DAG, Op1, dl);
4122 SDValue Log10ofMantissa;
4123 if (LimitFloatPrecision <= 6) {
4124 // For floating-point precision of 6:
4126 // Log10ofMantissa =
4128 // (0.60948995f - 0.10380950f * x) * x;
4130 // error 0.0014886165, which is 6 bits
4131 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4132 getF32Constant(DAG, 0xbdd49a13));
4133 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4134 getF32Constant(DAG, 0x3f1c0789));
4135 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4136 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4137 getF32Constant(DAG, 0x3f011300));
4138 } else if (LimitFloatPrecision <= 12) {
4139 // For floating-point precision of 12:
4141 // Log10ofMantissa =
4144 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4146 // error 0.00019228036, which is better than 12 bits
4147 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4148 getF32Constant(DAG, 0x3d431f31));
4149 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4150 getF32Constant(DAG, 0x3ea21fb2));
4151 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4152 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4153 getF32Constant(DAG, 0x3f6ae232));
4154 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4155 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4156 getF32Constant(DAG, 0x3f25f7c3));
4157 } else { // LimitFloatPrecision <= 18
4158 // For floating-point precision of 18:
4160 // Log10ofMantissa =
4165 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4167 // error 0.0000037995730, which is better than 18 bits
4168 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4169 getF32Constant(DAG, 0x3c5d51ce));
4170 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4171 getF32Constant(DAG, 0x3e00685a));
4172 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4173 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4174 getF32Constant(DAG, 0x3efb6798));
4175 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4176 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4177 getF32Constant(DAG, 0x3f88d192));
4178 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4179 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4180 getF32Constant(DAG, 0x3fc4316c));
4181 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4182 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4183 getF32Constant(DAG, 0x3f57ce70));
4186 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4189 // No special expansion.
4190 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4193 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4194 /// limited-precision mode.
4195 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4196 const TargetLowering &TLI) {
4197 if (Op.getValueType() == MVT::f32 &&
4198 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4199 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
4201 // FractionalPartOfX = x - (float)IntegerPartOfX;
4202 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4203 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
4205 // IntegerPartOfX <<= 23;
4206 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4207 DAG.getConstant(23, TLI.getPointerTy()));
4209 SDValue TwoToFractionalPartOfX;
4210 if (LimitFloatPrecision <= 6) {
4211 // For floating-point precision of 6:
4213 // TwoToFractionalPartOfX =
4215 // (0.735607626f + 0.252464424f * x) * x;
4217 // error 0.0144103317, which is 6 bits
4218 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4219 getF32Constant(DAG, 0x3e814304));
4220 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4221 getF32Constant(DAG, 0x3f3c50c8));
4222 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4223 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4224 getF32Constant(DAG, 0x3f7f5e7e));
4225 } else if (LimitFloatPrecision <= 12) {
4226 // For floating-point precision of 12:
4228 // TwoToFractionalPartOfX =
4231 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4233 // error 0.000107046256, which is 13 to 14 bits
4234 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4235 getF32Constant(DAG, 0x3da235e3));
4236 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4237 getF32Constant(DAG, 0x3e65b8f3));
4238 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4239 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4240 getF32Constant(DAG, 0x3f324b07));
4241 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4242 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4243 getF32Constant(DAG, 0x3f7ff8fd));
4244 } else { // LimitFloatPrecision <= 18
4245 // For floating-point precision of 18:
4247 // TwoToFractionalPartOfX =
4251 // (0.554906021e-1f +
4252 // (0.961591928e-2f +
4253 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4254 // error 2.47208000*10^(-7), which is better than 18 bits
4255 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4256 getF32Constant(DAG, 0x3924b03e));
4257 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4258 getF32Constant(DAG, 0x3ab24b87));
4259 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4260 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4261 getF32Constant(DAG, 0x3c1d8c17));
4262 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4263 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4264 getF32Constant(DAG, 0x3d634a1d));
4265 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4266 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4267 getF32Constant(DAG, 0x3e75fe14));
4268 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4269 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4270 getF32Constant(DAG, 0x3f317234));
4271 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4272 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4273 getF32Constant(DAG, 0x3f800000));
4276 // Add the exponent into the result in integer domain.
4277 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4278 TwoToFractionalPartOfX);
4279 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4280 DAG.getNode(ISD::ADD, dl, MVT::i32,
4281 t13, IntegerPartOfX));
4284 // No special expansion.
4285 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4288 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4289 /// limited-precision mode with x == 10.0f.
4290 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4291 SelectionDAG &DAG, const TargetLowering &TLI) {
4292 bool IsExp10 = false;
4293 if (LHS.getValueType() == MVT::f32 && LHS.getValueType() == MVT::f32 &&
4294 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4295 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4297 IsExp10 = LHSC->isExactlyValue(Ten);
4302 // Put the exponent in the right bit position for later addition to the
4305 // #define LOG2OF10 3.3219281f
4306 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4307 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4308 getF32Constant(DAG, 0x40549a78));
4309 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4311 // FractionalPartOfX = x - (float)IntegerPartOfX;
4312 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4313 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4315 // IntegerPartOfX <<= 23;
4316 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4317 DAG.getConstant(23, TLI.getPointerTy()));
4319 SDValue TwoToFractionalPartOfX;
4320 if (LimitFloatPrecision <= 6) {
4321 // For floating-point precision of 6:
4323 // twoToFractionalPartOfX =
4325 // (0.735607626f + 0.252464424f * x) * x;
4327 // error 0.0144103317, which is 6 bits
4328 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4329 getF32Constant(DAG, 0x3e814304));
4330 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4331 getF32Constant(DAG, 0x3f3c50c8));
4332 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4333 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4334 getF32Constant(DAG, 0x3f7f5e7e));
4335 } else if (LimitFloatPrecision <= 12) {
4336 // For floating-point precision of 12:
4338 // TwoToFractionalPartOfX =
4341 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4343 // error 0.000107046256, which is 13 to 14 bits
4344 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4345 getF32Constant(DAG, 0x3da235e3));
4346 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4347 getF32Constant(DAG, 0x3e65b8f3));
4348 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4349 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4350 getF32Constant(DAG, 0x3f324b07));
4351 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4352 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4353 getF32Constant(DAG, 0x3f7ff8fd));
4354 } else { // LimitFloatPrecision <= 18
4355 // For floating-point precision of 18:
4357 // TwoToFractionalPartOfX =
4361 // (0.554906021e-1f +
4362 // (0.961591928e-2f +
4363 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4364 // error 2.47208000*10^(-7), which is better than 18 bits
4365 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4366 getF32Constant(DAG, 0x3924b03e));
4367 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4368 getF32Constant(DAG, 0x3ab24b87));
4369 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4370 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4371 getF32Constant(DAG, 0x3c1d8c17));
4372 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4373 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4374 getF32Constant(DAG, 0x3d634a1d));
4375 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4376 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4377 getF32Constant(DAG, 0x3e75fe14));
4378 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4379 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4380 getF32Constant(DAG, 0x3f317234));
4381 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4382 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4383 getF32Constant(DAG, 0x3f800000));
4386 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
4387 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4388 DAG.getNode(ISD::ADD, dl, MVT::i32,
4389 t13, IntegerPartOfX));
4392 // No special expansion.
4393 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4397 /// ExpandPowI - Expand a llvm.powi intrinsic.
4398 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4399 SelectionDAG &DAG) {
4400 // If RHS is a constant, we can expand this out to a multiplication tree,
4401 // otherwise we end up lowering to a call to __powidf2 (for example). When
4402 // optimizing for size, we only want to do this if the expansion would produce
4403 // a small number of multiplies, otherwise we do the full expansion.
4404 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4405 // Get the exponent as a positive value.
4406 unsigned Val = RHSC->getSExtValue();
4407 if ((int)Val < 0) Val = -Val;
4409 // powi(x, 0) -> 1.0
4411 return DAG.getConstantFP(1.0, LHS.getValueType());
4413 const Function *F = DAG.getMachineFunction().getFunction();
4414 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4415 Attribute::OptimizeForSize) ||
4416 // If optimizing for size, don't insert too many multiplies. This
4417 // inserts up to 5 multiplies.
4418 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4419 // We use the simple binary decomposition method to generate the multiply
4420 // sequence. There are more optimal ways to do this (for example,
4421 // powi(x,15) generates one more multiply than it should), but this has
4422 // the benefit of being both really simple and much better than a libcall.
4423 SDValue Res; // Logically starts equal to 1.0
4424 SDValue CurSquare = LHS;
4428 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4430 Res = CurSquare; // 1.0*CurSquare.
4433 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4434 CurSquare, CurSquare);
4438 // If the original was negative, invert the result, producing 1/(x*x*x).
4439 if (RHSC->getSExtValue() < 0)
4440 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4441 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4446 // Otherwise, expand to a libcall.
4447 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4450 // getTruncatedArgReg - Find underlying register used for an truncated
4452 static unsigned getTruncatedArgReg(const SDValue &N) {
4453 if (N.getOpcode() != ISD::TRUNCATE)
4456 const SDValue &Ext = N.getOperand(0);
4457 if (Ext.getOpcode() == ISD::AssertZext ||
4458 Ext.getOpcode() == ISD::AssertSext) {
4459 const SDValue &CFR = Ext.getOperand(0);
4460 if (CFR.getOpcode() == ISD::CopyFromReg)
4461 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4462 if (CFR.getOpcode() == ISD::TRUNCATE)
4463 return getTruncatedArgReg(CFR);
4468 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4469 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4470 /// At the end of instruction selection, they will be inserted to the entry BB.
4472 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
4475 const Argument *Arg = dyn_cast<Argument>(V);
4479 MachineFunction &MF = DAG.getMachineFunction();
4480 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4482 // Ignore inlined function arguments here.
4483 DIVariable DV(Variable);
4484 if (DV.isInlinedFnArgument(MF.getFunction()))
4487 Optional<MachineOperand> Op;
4488 // Some arguments' frame index is recorded during argument lowering.
4489 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4490 Op = MachineOperand::CreateFI(FI);
4492 if (!Op && N.getNode()) {
4494 if (N.getOpcode() == ISD::CopyFromReg)
4495 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4497 Reg = getTruncatedArgReg(N);
4498 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4499 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4500 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4505 Op = MachineOperand::CreateReg(Reg, false);
4509 // Check if ValueMap has reg number.
4510 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4511 if (VMI != FuncInfo.ValueMap.end())
4512 Op = MachineOperand::CreateReg(VMI->second, false);
4515 if (!Op && N.getNode())
4516 // Check if frame index is available.
4517 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4518 if (FrameIndexSDNode *FINode =
4519 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4520 Op = MachineOperand::CreateFI(FINode->getIndex());
4525 // FIXME: This does not handle register-indirect values at offset 0.
4526 bool IsIndirect = Offset != 0;
4528 FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(),
4529 TII->get(TargetOpcode::DBG_VALUE),
4531 Op->getReg(), Offset, Variable));
4533 FuncInfo.ArgDbgValues.push_back(
4534 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4535 .addOperand(*Op).addImm(Offset).addMetadata(Variable));
4540 // VisualStudio defines setjmp as _setjmp
4541 #if defined(_MSC_VER) && defined(setjmp) && \
4542 !defined(setjmp_undefined_for_msvc)
4543 # pragma push_macro("setjmp")
4545 # define setjmp_undefined_for_msvc
4548 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4549 /// we want to emit this as a call to a named external function, return the name
4550 /// otherwise lower it and return null.
4552 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4553 const TargetLowering *TLI = TM.getTargetLowering();
4554 SDLoc sdl = getCurSDLoc();
4555 DebugLoc dl = getCurDebugLoc();
4558 switch (Intrinsic) {
4560 // By default, turn this into a target intrinsic node.
4561 visitTargetIntrinsic(I, Intrinsic);
4563 case Intrinsic::vastart: visitVAStart(I); return 0;
4564 case Intrinsic::vaend: visitVAEnd(I); return 0;
4565 case Intrinsic::vacopy: visitVACopy(I); return 0;
4566 case Intrinsic::returnaddress:
4567 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(),
4568 getValue(I.getArgOperand(0))));
4570 case Intrinsic::frameaddress:
4571 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(),
4572 getValue(I.getArgOperand(0))));
4574 case Intrinsic::setjmp:
4575 return &"_setjmp"[!TLI->usesUnderscoreSetJmp()];
4576 case Intrinsic::longjmp:
4577 return &"_longjmp"[!TLI->usesUnderscoreLongJmp()];
4578 case Intrinsic::memcpy: {
4579 // Assert for address < 256 since we support only user defined address
4581 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4583 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4585 "Unknown address space");
4586 SDValue Op1 = getValue(I.getArgOperand(0));
4587 SDValue Op2 = getValue(I.getArgOperand(1));
4588 SDValue Op3 = getValue(I.getArgOperand(2));
4589 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4591 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4592 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4593 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
4594 MachinePointerInfo(I.getArgOperand(0)),
4595 MachinePointerInfo(I.getArgOperand(1))));
4598 case Intrinsic::memset: {
4599 // Assert for address < 256 since we support only user defined address
4601 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4603 "Unknown address space");
4604 SDValue Op1 = getValue(I.getArgOperand(0));
4605 SDValue Op2 = getValue(I.getArgOperand(1));
4606 SDValue Op3 = getValue(I.getArgOperand(2));
4607 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4609 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4610 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4611 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4612 MachinePointerInfo(I.getArgOperand(0))));
4615 case Intrinsic::memmove: {
4616 // Assert for address < 256 since we support only user defined address
4618 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4620 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4622 "Unknown address space");
4623 SDValue Op1 = getValue(I.getArgOperand(0));
4624 SDValue Op2 = getValue(I.getArgOperand(1));
4625 SDValue Op3 = getValue(I.getArgOperand(2));
4626 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4628 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4629 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4630 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4631 MachinePointerInfo(I.getArgOperand(0)),
4632 MachinePointerInfo(I.getArgOperand(1))));
4635 case Intrinsic::dbg_declare: {
4636 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4637 MDNode *Variable = DI.getVariable();
4638 const Value *Address = DI.getAddress();
4639 DIVariable DIVar(Variable);
4640 assert((!DIVar || DIVar.isVariable()) &&
4641 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4642 if (!Address || !DIVar) {
4643 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4647 // Check if address has undef value.
4648 if (isa<UndefValue>(Address) ||
4649 (Address->use_empty() && !isa<Argument>(Address))) {
4650 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4654 SDValue &N = NodeMap[Address];
4655 if (!N.getNode() && isa<Argument>(Address))
4656 // Check unused arguments map.
4657 N = UnusedArgNodeMap[Address];
4660 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4661 Address = BCI->getOperand(0);
4662 // Parameters are handled specially.
4664 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4665 isa<Argument>(Address));
4667 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4669 if (isParameter && !AI) {
4670 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4672 // Byval parameter. We have a frame index at this point.
4673 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4674 0, dl, SDNodeOrder);
4676 // Address is an argument, so try to emit its dbg value using
4677 // virtual register info from the FuncInfo.ValueMap.
4678 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
4682 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4683 0, dl, SDNodeOrder);
4685 // Can't do anything with other non-AI cases yet.
4686 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4687 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4688 DEBUG(Address->dump());
4691 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4693 // If Address is an argument then try to emit its dbg value using
4694 // virtual register info from the FuncInfo.ValueMap.
4695 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
4696 // If variable is pinned by a alloca in dominating bb then
4697 // use StaticAllocaMap.
4698 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4699 if (AI->getParent() != DI.getParent()) {
4700 DenseMap<const AllocaInst*, int>::iterator SI =
4701 FuncInfo.StaticAllocaMap.find(AI);
4702 if (SI != FuncInfo.StaticAllocaMap.end()) {
4703 SDV = DAG.getDbgValue(Variable, SI->second,
4704 0, dl, SDNodeOrder);
4705 DAG.AddDbgValue(SDV, 0, false);
4710 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4715 case Intrinsic::dbg_value: {
4716 const DbgValueInst &DI = cast<DbgValueInst>(I);
4717 DIVariable DIVar(DI.getVariable());
4718 assert((!DIVar || DIVar.isVariable()) &&
4719 "Variable in DbgValueInst should be either null or a DIVariable.");
4723 MDNode *Variable = DI.getVariable();
4724 uint64_t Offset = DI.getOffset();
4725 const Value *V = DI.getValue();
4730 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4731 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4732 DAG.AddDbgValue(SDV, 0, false);
4734 // Do not use getValue() in here; we don't want to generate code at
4735 // this point if it hasn't been done yet.
4736 SDValue N = NodeMap[V];
4737 if (!N.getNode() && isa<Argument>(V))
4738 // Check unused arguments map.
4739 N = UnusedArgNodeMap[V];
4741 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
4742 SDV = DAG.getDbgValue(Variable, N.getNode(),
4743 N.getResNo(), Offset, dl, SDNodeOrder);
4744 DAG.AddDbgValue(SDV, N.getNode(), false);
4746 } else if (!V->use_empty() ) {
4747 // Do not call getValue(V) yet, as we don't want to generate code.
4748 // Remember it for later.
4749 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4750 DanglingDebugInfoMap[V] = DDI;
4752 // We may expand this to cover more cases. One case where we have no
4753 // data available is an unreferenced parameter.
4754 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4758 // Build a debug info table entry.
4759 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4760 V = BCI->getOperand(0);
4761 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4762 // Don't handle byval struct arguments or VLAs, for example.
4764 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4765 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
4768 DenseMap<const AllocaInst*, int>::iterator SI =
4769 FuncInfo.StaticAllocaMap.find(AI);
4770 if (SI == FuncInfo.StaticAllocaMap.end())
4772 int FI = SI->second;
4774 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4775 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4776 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4780 case Intrinsic::eh_typeid_for: {
4781 // Find the type id for the given typeinfo.
4782 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4783 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4784 Res = DAG.getConstant(TypeID, MVT::i32);
4789 case Intrinsic::eh_return_i32:
4790 case Intrinsic::eh_return_i64:
4791 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4792 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4795 getValue(I.getArgOperand(0)),
4796 getValue(I.getArgOperand(1))));
4798 case Intrinsic::eh_unwind_init:
4799 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4801 case Intrinsic::eh_dwarf_cfa: {
4802 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4803 TLI->getPointerTy());
4804 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4805 CfaArg.getValueType(),
4806 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4807 CfaArg.getValueType()),
4809 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl,
4810 TLI->getPointerTy(),
4811 DAG.getConstant(0, TLI->getPointerTy()));
4812 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4816 case Intrinsic::eh_sjlj_callsite: {
4817 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4818 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4819 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4820 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4822 MMI.setCurrentCallSite(CI->getZExtValue());
4825 case Intrinsic::eh_sjlj_functioncontext: {
4826 // Get and store the index of the function context.
4827 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4829 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4830 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4831 MFI->setFunctionContextIndex(FI);
4834 case Intrinsic::eh_sjlj_setjmp: {
4837 Ops[1] = getValue(I.getArgOperand(0));
4838 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4839 DAG.getVTList(MVT::i32, MVT::Other),
4841 setValue(&I, Op.getValue(0));
4842 DAG.setRoot(Op.getValue(1));
4845 case Intrinsic::eh_sjlj_longjmp: {
4846 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4847 getRoot(), getValue(I.getArgOperand(0))));
4851 case Intrinsic::x86_mmx_pslli_w:
4852 case Intrinsic::x86_mmx_pslli_d:
4853 case Intrinsic::x86_mmx_pslli_q:
4854 case Intrinsic::x86_mmx_psrli_w:
4855 case Intrinsic::x86_mmx_psrli_d:
4856 case Intrinsic::x86_mmx_psrli_q:
4857 case Intrinsic::x86_mmx_psrai_w:
4858 case Intrinsic::x86_mmx_psrai_d: {
4859 SDValue ShAmt = getValue(I.getArgOperand(1));
4860 if (isa<ConstantSDNode>(ShAmt)) {
4861 visitTargetIntrinsic(I, Intrinsic);
4864 unsigned NewIntrinsic = 0;
4865 EVT ShAmtVT = MVT::v2i32;
4866 switch (Intrinsic) {
4867 case Intrinsic::x86_mmx_pslli_w:
4868 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4870 case Intrinsic::x86_mmx_pslli_d:
4871 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4873 case Intrinsic::x86_mmx_pslli_q:
4874 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4876 case Intrinsic::x86_mmx_psrli_w:
4877 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4879 case Intrinsic::x86_mmx_psrli_d:
4880 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4882 case Intrinsic::x86_mmx_psrli_q:
4883 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4885 case Intrinsic::x86_mmx_psrai_w:
4886 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4888 case Intrinsic::x86_mmx_psrai_d:
4889 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4891 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4894 // The vector shift intrinsics with scalars uses 32b shift amounts but
4895 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4897 // We must do this early because v2i32 is not a legal type.
4900 ShOps[1] = DAG.getConstant(0, MVT::i32);
4901 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, &ShOps[0], 2);
4902 EVT DestVT = TLI->getValueType(I.getType());
4903 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4904 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4905 DAG.getConstant(NewIntrinsic, MVT::i32),
4906 getValue(I.getArgOperand(0)), ShAmt);
4910 case Intrinsic::x86_avx_vinsertf128_pd_256:
4911 case Intrinsic::x86_avx_vinsertf128_ps_256:
4912 case Intrinsic::x86_avx_vinsertf128_si_256:
4913 case Intrinsic::x86_avx2_vinserti128: {
4914 EVT DestVT = TLI->getValueType(I.getType());
4915 EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType());
4916 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4917 ElVT.getVectorNumElements();
4918 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
4919 getValue(I.getArgOperand(0)),
4920 getValue(I.getArgOperand(1)),
4921 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
4925 case Intrinsic::x86_avx_vextractf128_pd_256:
4926 case Intrinsic::x86_avx_vextractf128_ps_256:
4927 case Intrinsic::x86_avx_vextractf128_si_256:
4928 case Intrinsic::x86_avx2_vextracti128: {
4929 EVT DestVT = TLI->getValueType(I.getType());
4930 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
4931 DestVT.getVectorNumElements();
4932 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
4933 getValue(I.getArgOperand(0)),
4934 DAG.getConstant(Idx, TLI->getVectorIdxTy()));
4938 case Intrinsic::convertff:
4939 case Intrinsic::convertfsi:
4940 case Intrinsic::convertfui:
4941 case Intrinsic::convertsif:
4942 case Intrinsic::convertuif:
4943 case Intrinsic::convertss:
4944 case Intrinsic::convertsu:
4945 case Intrinsic::convertus:
4946 case Intrinsic::convertuu: {
4947 ISD::CvtCode Code = ISD::CVT_INVALID;
4948 switch (Intrinsic) {
4949 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4950 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4951 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4952 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4953 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4954 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4955 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4956 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4957 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4958 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4960 EVT DestVT = TLI->getValueType(I.getType());
4961 const Value *Op1 = I.getArgOperand(0);
4962 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
4963 DAG.getValueType(DestVT),
4964 DAG.getValueType(getValue(Op1).getValueType()),
4965 getValue(I.getArgOperand(1)),
4966 getValue(I.getArgOperand(2)),
4971 case Intrinsic::powi:
4972 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
4973 getValue(I.getArgOperand(1)), DAG));
4975 case Intrinsic::log:
4976 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4978 case Intrinsic::log2:
4979 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4981 case Intrinsic::log10:
4982 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4984 case Intrinsic::exp:
4985 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4987 case Intrinsic::exp2:
4988 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
4990 case Intrinsic::pow:
4991 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
4992 getValue(I.getArgOperand(1)), DAG, *TLI));
4994 case Intrinsic::sqrt:
4995 case Intrinsic::fabs:
4996 case Intrinsic::sin:
4997 case Intrinsic::cos:
4998 case Intrinsic::floor:
4999 case Intrinsic::ceil:
5000 case Intrinsic::trunc:
5001 case Intrinsic::rint:
5002 case Intrinsic::nearbyint:
5003 case Intrinsic::round: {
5005 switch (Intrinsic) {
5006 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5007 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5008 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5009 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5010 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5011 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5012 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5013 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5014 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5015 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5016 case Intrinsic::round: Opcode = ISD::FROUND; break;
5019 setValue(&I, DAG.getNode(Opcode, sdl,
5020 getValue(I.getArgOperand(0)).getValueType(),
5021 getValue(I.getArgOperand(0))));
5024 case Intrinsic::copysign:
5025 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5026 getValue(I.getArgOperand(0)).getValueType(),
5027 getValue(I.getArgOperand(0)),
5028 getValue(I.getArgOperand(1))));
5030 case Intrinsic::fma:
5031 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5032 getValue(I.getArgOperand(0)).getValueType(),
5033 getValue(I.getArgOperand(0)),
5034 getValue(I.getArgOperand(1)),
5035 getValue(I.getArgOperand(2))));
5037 case Intrinsic::fmuladd: {
5038 EVT VT = TLI->getValueType(I.getType());
5039 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5040 TLI->isFMAFasterThanFMulAndFAdd(VT)) {
5041 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5042 getValue(I.getArgOperand(0)).getValueType(),
5043 getValue(I.getArgOperand(0)),
5044 getValue(I.getArgOperand(1)),
5045 getValue(I.getArgOperand(2))));
5047 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5048 getValue(I.getArgOperand(0)).getValueType(),
5049 getValue(I.getArgOperand(0)),
5050 getValue(I.getArgOperand(1)));
5051 SDValue Add = DAG.getNode(ISD::FADD, sdl,
5052 getValue(I.getArgOperand(0)).getValueType(),
5054 getValue(I.getArgOperand(2)));
5059 case Intrinsic::convert_to_fp16:
5060 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, sdl,
5061 MVT::i16, getValue(I.getArgOperand(0))));
5063 case Intrinsic::convert_from_fp16:
5064 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, sdl,
5065 MVT::f32, getValue(I.getArgOperand(0))));
5067 case Intrinsic::pcmarker: {
5068 SDValue Tmp = getValue(I.getArgOperand(0));
5069 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5072 case Intrinsic::readcyclecounter: {
5073 SDValue Op = getRoot();
5074 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5075 DAG.getVTList(MVT::i64, MVT::Other),
5078 DAG.setRoot(Res.getValue(1));
5081 case Intrinsic::bswap:
5082 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5083 getValue(I.getArgOperand(0)).getValueType(),
5084 getValue(I.getArgOperand(0))));
5086 case Intrinsic::cttz: {
5087 SDValue Arg = getValue(I.getArgOperand(0));
5088 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5089 EVT Ty = Arg.getValueType();
5090 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5094 case Intrinsic::ctlz: {
5095 SDValue Arg = getValue(I.getArgOperand(0));
5096 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5097 EVT Ty = Arg.getValueType();
5098 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5102 case Intrinsic::ctpop: {
5103 SDValue Arg = getValue(I.getArgOperand(0));
5104 EVT Ty = Arg.getValueType();
5105 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5108 case Intrinsic::stacksave: {
5109 SDValue Op = getRoot();
5110 Res = DAG.getNode(ISD::STACKSAVE, sdl,
5111 DAG.getVTList(TLI->getPointerTy(), MVT::Other), &Op, 1);
5113 DAG.setRoot(Res.getValue(1));
5116 case Intrinsic::stackrestore: {
5117 Res = getValue(I.getArgOperand(0));
5118 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5121 case Intrinsic::stackprotector: {
5122 // Emit code into the DAG to store the stack guard onto the stack.
5123 MachineFunction &MF = DAG.getMachineFunction();
5124 MachineFrameInfo *MFI = MF.getFrameInfo();
5125 EVT PtrTy = TLI->getPointerTy();
5127 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
5128 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5130 int FI = FuncInfo.StaticAllocaMap[Slot];
5131 MFI->setStackProtectorIndex(FI);
5133 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5135 // Store the stack protector onto the stack.
5136 Res = DAG.getStore(getRoot(), sdl, Src, FIN,
5137 MachinePointerInfo::getFixedStack(FI),
5143 case Intrinsic::objectsize: {
5144 // If we don't know by now, we're never going to know.
5145 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5147 assert(CI && "Non-constant type in __builtin_object_size?");
5149 SDValue Arg = getValue(I.getCalledValue());
5150 EVT Ty = Arg.getValueType();
5153 Res = DAG.getConstant(-1ULL, Ty);
5155 Res = DAG.getConstant(0, Ty);
5160 case Intrinsic::annotation:
5161 case Intrinsic::ptr_annotation:
5162 // Drop the intrinsic, but forward the value
5163 setValue(&I, getValue(I.getOperand(0)));
5165 case Intrinsic::var_annotation:
5166 // Discard annotate attributes
5169 case Intrinsic::init_trampoline: {
5170 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5174 Ops[1] = getValue(I.getArgOperand(0));
5175 Ops[2] = getValue(I.getArgOperand(1));
5176 Ops[3] = getValue(I.getArgOperand(2));
5177 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5178 Ops[5] = DAG.getSrcValue(F);
5180 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops, 6);
5185 case Intrinsic::adjust_trampoline: {
5186 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5187 TLI->getPointerTy(),
5188 getValue(I.getArgOperand(0))));
5191 case Intrinsic::gcroot:
5193 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5194 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5196 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5197 GFI->addStackRoot(FI->getIndex(), TypeMap);
5200 case Intrinsic::gcread:
5201 case Intrinsic::gcwrite:
5202 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5203 case Intrinsic::flt_rounds:
5204 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5207 case Intrinsic::expect: {
5208 // Just replace __builtin_expect(exp, c) with EXP.
5209 setValue(&I, getValue(I.getArgOperand(0)));
5213 case Intrinsic::debugtrap:
5214 case Intrinsic::trap: {
5215 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
5216 if (TrapFuncName.empty()) {
5217 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5218 ISD::TRAP : ISD::DEBUGTRAP;
5219 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5222 TargetLowering::ArgListTy Args;
5224 CallLoweringInfo CLI(getRoot(), I.getType(),
5225 false, false, false, false, 0, CallingConv::C,
5226 /*isTailCall=*/false,
5227 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
5228 DAG.getExternalSymbol(TrapFuncName.data(),
5229 TLI->getPointerTy()),
5231 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
5232 DAG.setRoot(Result.second);
5236 case Intrinsic::uadd_with_overflow:
5237 case Intrinsic::sadd_with_overflow:
5238 case Intrinsic::usub_with_overflow:
5239 case Intrinsic::ssub_with_overflow:
5240 case Intrinsic::umul_with_overflow:
5241 case Intrinsic::smul_with_overflow: {
5243 switch (Intrinsic) {
5244 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5245 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5246 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5247 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5248 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5249 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5250 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5252 SDValue Op1 = getValue(I.getArgOperand(0));
5253 SDValue Op2 = getValue(I.getArgOperand(1));
5255 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5256 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5259 case Intrinsic::prefetch: {
5261 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5263 Ops[1] = getValue(I.getArgOperand(0));
5264 Ops[2] = getValue(I.getArgOperand(1));
5265 Ops[3] = getValue(I.getArgOperand(2));
5266 Ops[4] = getValue(I.getArgOperand(3));
5267 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5268 DAG.getVTList(MVT::Other),
5270 EVT::getIntegerVT(*Context, 8),
5271 MachinePointerInfo(I.getArgOperand(0)),
5273 false, /* volatile */
5275 rw==1)); /* write */
5278 case Intrinsic::lifetime_start:
5279 case Intrinsic::lifetime_end: {
5280 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5281 // Stack coloring is not enabled in O0, discard region information.
5282 if (TM.getOptLevel() == CodeGenOpt::None)
5285 SmallVector<Value *, 4> Allocas;
5286 GetUnderlyingObjects(I.getArgOperand(1), Allocas, TD);
5288 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5289 E = Allocas.end(); Object != E; ++Object) {
5290 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5292 // Could not find an Alloca.
5293 if (!LifetimeObject)
5296 int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
5300 Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true);
5301 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5303 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops, 2);
5308 case Intrinsic::invariant_start:
5309 // Discard region information.
5310 setValue(&I, DAG.getUNDEF(TLI->getPointerTy()));
5312 case Intrinsic::invariant_end:
5313 // Discard region information.
5315 case Intrinsic::stackprotectorcheck: {
5316 // Do not actually emit anything for this basic block. Instead we initialize
5317 // the stack protector descriptor and export the guard variable so we can
5318 // access it in FinishBasicBlock.
5319 const BasicBlock *BB = I.getParent();
5320 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5321 ExportFromCurrentBlock(SPDescriptor.getGuard());
5323 // Flush our exports since we are going to process a terminator.
5324 (void)getControlRoot();
5327 case Intrinsic::donothing:
5330 case Intrinsic::experimental_stackmap: {
5334 case Intrinsic::experimental_patchpoint_void:
5335 case Intrinsic::experimental_patchpoint_i64: {
5342 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5344 MachineBasicBlock *LandingPad) {
5345 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5346 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5347 Type *RetTy = FTy->getReturnType();
5348 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5349 MCSymbol *BeginLabel = 0;
5351 TargetLowering::ArgListTy Args;
5352 TargetLowering::ArgListEntry Entry;
5353 Args.reserve(CS.arg_size());
5355 // Check whether the function can return without sret-demotion.
5356 SmallVector<ISD::OutputArg, 4> Outs;
5357 const TargetLowering *TLI = TM.getTargetLowering();
5358 GetReturnInfo(RetTy, CS.getAttributes(), Outs, *TLI);
5360 bool CanLowerReturn = TLI->CanLowerReturn(CS.getCallingConv(),
5361 DAG.getMachineFunction(),
5362 FTy->isVarArg(), Outs,
5365 SDValue DemoteStackSlot;
5366 int DemoteStackIdx = -100;
5368 if (!CanLowerReturn) {
5369 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(
5370 FTy->getReturnType());
5371 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(
5372 FTy->getReturnType());
5373 MachineFunction &MF = DAG.getMachineFunction();
5374 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5375 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
5377 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI->getPointerTy());
5378 Entry.Node = DemoteStackSlot;
5379 Entry.Ty = StackSlotPtrType;
5380 Entry.isSExt = false;
5381 Entry.isZExt = false;
5382 Entry.isInReg = false;
5383 Entry.isSRet = true;
5384 Entry.isNest = false;
5385 Entry.isByVal = false;
5386 Entry.isReturned = false;
5387 Entry.Alignment = Align;
5388 Args.push_back(Entry);
5389 RetTy = Type::getVoidTy(FTy->getContext());
5392 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5394 const Value *V = *i;
5397 if (V->getType()->isEmptyTy())
5400 SDValue ArgNode = getValue(V);
5401 Entry.Node = ArgNode; Entry.Ty = V->getType();
5403 // Skip the first return-type Attribute to get to params.
5404 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5405 Args.push_back(Entry);
5409 // Insert a label before the invoke call to mark the try range. This can be
5410 // used to detect deletion of the invoke via the MachineModuleInfo.
5411 BeginLabel = MMI.getContext().CreateTempSymbol();
5413 // For SjLj, keep track of which landing pads go with which invokes
5414 // so as to maintain the ordering of pads in the LSDA.
5415 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5416 if (CallSiteIndex) {
5417 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5418 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5420 // Now that the call site is handled, stop tracking it.
5421 MMI.setCurrentCallSite(0);
5424 // Both PendingLoads and PendingExports must be flushed here;
5425 // this call might not return.
5427 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5430 // Check if target-independent constraints permit a tail call here.
5431 // Target-dependent constraints are checked within TLI->LowerCallTo.
5432 if (isTailCall && !isInTailCallPosition(CS, *TLI))
5436 CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
5438 std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI);
5439 assert((isTailCall || Result.second.getNode()) &&
5440 "Non-null chain expected with non-tail call!");
5441 assert((Result.second.getNode() || !Result.first.getNode()) &&
5442 "Null value expected with tail call!");
5443 if (Result.first.getNode()) {
5444 setValue(CS.getInstruction(), Result.first);
5445 } else if (!CanLowerReturn && Result.second.getNode()) {
5446 // The instruction result is the result of loading from the
5447 // hidden sret parameter.
5448 SmallVector<EVT, 1> PVTs;
5449 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
5451 ComputeValueVTs(*TLI, PtrRetTy, PVTs);
5452 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5453 EVT PtrVT = PVTs[0];
5455 SmallVector<EVT, 4> RetTys;
5456 SmallVector<uint64_t, 4> Offsets;
5457 RetTy = FTy->getReturnType();
5458 ComputeValueVTs(*TLI, RetTy, RetTys, &Offsets);
5460 unsigned NumValues = RetTys.size();
5461 SmallVector<SDValue, 4> Values(NumValues);
5462 SmallVector<SDValue, 4> Chains(NumValues);
5464 for (unsigned i = 0; i < NumValues; ++i) {
5465 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT,
5467 DAG.getConstant(Offsets[i], PtrVT));
5468 SDValue L = DAG.getLoad(RetTys[i], getCurSDLoc(), Result.second, Add,
5469 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
5470 false, false, false, 1);
5472 Chains[i] = L.getValue(1);
5475 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
5476 MVT::Other, &Chains[0], NumValues);
5477 PendingLoads.push_back(Chain);
5479 setValue(CS.getInstruction(),
5480 DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
5481 DAG.getVTList(&RetTys[0], RetTys.size()),
5482 &Values[0], Values.size()));
5485 if (!Result.second.getNode()) {
5486 // As a special case, a null chain means that a tail call has been emitted
5487 // and the DAG root is already updated.
5490 // Since there's no actual continuation from this block, nothing can be
5491 // relying on us setting vregs for them.
5492 PendingExports.clear();
5494 DAG.setRoot(Result.second);
5498 // Insert a label at the end of the invoke call to mark the try range. This
5499 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5500 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5501 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5503 // Inform MachineModuleInfo of range.
5504 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5508 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5509 /// value is equal or not-equal to zero.
5510 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5511 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
5513 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
5514 if (IC->isEquality())
5515 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5516 if (C->isNullValue())
5518 // Unknown instruction.
5524 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5526 SelectionDAGBuilder &Builder) {
5528 // Check to see if this load can be trivially constant folded, e.g. if the
5529 // input is from a string literal.
5530 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5531 // Cast pointer to the type we really want to load.
5532 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5533 PointerType::getUnqual(LoadTy));
5535 if (const Constant *LoadCst =
5536 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5538 return Builder.getValue(LoadCst);
5541 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5542 // still constant memory, the input chain can be the entry node.
5544 bool ConstantMemory = false;
5546 // Do not serialize (non-volatile) loads of constant memory with anything.
5547 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5548 Root = Builder.DAG.getEntryNode();
5549 ConstantMemory = true;
5551 // Do not serialize non-volatile loads against each other.
5552 Root = Builder.DAG.getRoot();
5555 SDValue Ptr = Builder.getValue(PtrVal);
5556 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5557 Ptr, MachinePointerInfo(PtrVal),
5559 false /*nontemporal*/,
5560 false /*isinvariant*/, 1 /* align=1 */);
5562 if (!ConstantMemory)
5563 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5567 /// processIntegerCallValue - Record the value for an instruction that
5568 /// produces an integer result, converting the type where necessary.
5569 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5572 EVT VT = TM.getTargetLowering()->getValueType(I.getType(), true);
5574 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5576 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5577 setValue(&I, Value);
5580 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5581 /// If so, return true and lower it, otherwise return false and it will be
5582 /// lowered like a normal call.
5583 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5584 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5585 if (I.getNumArgOperands() != 3)
5588 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5589 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5590 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5591 !I.getType()->isIntegerTy())
5594 const Value *Size = I.getArgOperand(2);
5595 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5596 if (CSize && CSize->getZExtValue() == 0) {
5597 EVT CallVT = TM.getTargetLowering()->getValueType(I.getType(), true);
5598 setValue(&I, DAG.getConstant(0, CallVT));
5602 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5603 std::pair<SDValue, SDValue> Res =
5604 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5605 getValue(LHS), getValue(RHS), getValue(Size),
5606 MachinePointerInfo(LHS),
5607 MachinePointerInfo(RHS));
5608 if (Res.first.getNode()) {
5609 processIntegerCallValue(I, Res.first, true);
5610 PendingLoads.push_back(Res.second);
5614 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5615 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5616 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5617 bool ActuallyDoIt = true;
5620 switch (CSize->getZExtValue()) {
5622 LoadVT = MVT::Other;
5624 ActuallyDoIt = false;
5628 LoadTy = Type::getInt16Ty(CSize->getContext());
5632 LoadTy = Type::getInt32Ty(CSize->getContext());
5636 LoadTy = Type::getInt64Ty(CSize->getContext());
5640 LoadVT = MVT::v4i32;
5641 LoadTy = Type::getInt32Ty(CSize->getContext());
5642 LoadTy = VectorType::get(LoadTy, 4);
5647 // This turns into unaligned loads. We only do this if the target natively
5648 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5649 // we'll only produce a small number of byte loads.
5651 // Require that we can find a legal MVT, and only do this if the target
5652 // supports unaligned loads of that type. Expanding into byte loads would
5654 const TargetLowering *TLI = TM.getTargetLowering();
5655 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5656 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5657 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5658 if (!TLI->isTypeLegal(LoadVT) ||!TLI->allowsUnalignedMemoryAccesses(LoadVT))
5659 ActuallyDoIt = false;
5663 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5664 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5666 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5668 processIntegerCallValue(I, Res, false);
5677 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5678 /// form. If so, return true and lower it, otherwise return false and it
5679 /// will be lowered like a normal call.
5680 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5681 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5682 if (I.getNumArgOperands() != 3)
5685 const Value *Src = I.getArgOperand(0);
5686 const Value *Char = I.getArgOperand(1);
5687 const Value *Length = I.getArgOperand(2);
5688 if (!Src->getType()->isPointerTy() ||
5689 !Char->getType()->isIntegerTy() ||
5690 !Length->getType()->isIntegerTy() ||
5691 !I.getType()->isPointerTy())
5694 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5695 std::pair<SDValue, SDValue> Res =
5696 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5697 getValue(Src), getValue(Char), getValue(Length),
5698 MachinePointerInfo(Src));
5699 if (Res.first.getNode()) {
5700 setValue(&I, Res.first);
5701 PendingLoads.push_back(Res.second);
5708 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5709 /// optimized form. If so, return true and lower it, otherwise return false
5710 /// and it will be lowered like a normal call.
5711 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5712 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5713 if (I.getNumArgOperands() != 2)
5716 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5717 if (!Arg0->getType()->isPointerTy() ||
5718 !Arg1->getType()->isPointerTy() ||
5719 !I.getType()->isPointerTy())
5722 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5723 std::pair<SDValue, SDValue> Res =
5724 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5725 getValue(Arg0), getValue(Arg1),
5726 MachinePointerInfo(Arg0),
5727 MachinePointerInfo(Arg1), isStpcpy);
5728 if (Res.first.getNode()) {
5729 setValue(&I, Res.first);
5730 DAG.setRoot(Res.second);
5737 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5738 /// If so, return true and lower it, otherwise return false and it will be
5739 /// lowered like a normal call.
5740 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5741 // Verify that the prototype makes sense. int strcmp(void*,void*)
5742 if (I.getNumArgOperands() != 2)
5745 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5746 if (!Arg0->getType()->isPointerTy() ||
5747 !Arg1->getType()->isPointerTy() ||
5748 !I.getType()->isIntegerTy())
5751 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5752 std::pair<SDValue, SDValue> Res =
5753 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5754 getValue(Arg0), getValue(Arg1),
5755 MachinePointerInfo(Arg0),
5756 MachinePointerInfo(Arg1));
5757 if (Res.first.getNode()) {
5758 processIntegerCallValue(I, Res.first, true);
5759 PendingLoads.push_back(Res.second);
5766 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5767 /// form. If so, return true and lower it, otherwise return false and it
5768 /// will be lowered like a normal call.
5769 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5770 // Verify that the prototype makes sense. size_t strlen(char *)
5771 if (I.getNumArgOperands() != 1)
5774 const Value *Arg0 = I.getArgOperand(0);
5775 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5778 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5779 std::pair<SDValue, SDValue> Res =
5780 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5781 getValue(Arg0), MachinePointerInfo(Arg0));
5782 if (Res.first.getNode()) {
5783 processIntegerCallValue(I, Res.first, false);
5784 PendingLoads.push_back(Res.second);
5791 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5792 /// form. If so, return true and lower it, otherwise return false and it
5793 /// will be lowered like a normal call.
5794 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5795 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5796 if (I.getNumArgOperands() != 2)
5799 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5800 if (!Arg0->getType()->isPointerTy() ||
5801 !Arg1->getType()->isIntegerTy() ||
5802 !I.getType()->isIntegerTy())
5805 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5806 std::pair<SDValue, SDValue> Res =
5807 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5808 getValue(Arg0), getValue(Arg1),
5809 MachinePointerInfo(Arg0));
5810 if (Res.first.getNode()) {
5811 processIntegerCallValue(I, Res.first, false);
5812 PendingLoads.push_back(Res.second);
5819 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5820 /// operation (as expected), translate it to an SDNode with the specified opcode
5821 /// and return true.
5822 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5824 // Sanity check that it really is a unary floating-point call.
5825 if (I.getNumArgOperands() != 1 ||
5826 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5827 I.getType() != I.getArgOperand(0)->getType() ||
5828 !I.onlyReadsMemory())
5831 SDValue Tmp = getValue(I.getArgOperand(0));
5832 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5836 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5837 // Handle inline assembly differently.
5838 if (isa<InlineAsm>(I.getCalledValue())) {
5843 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5844 ComputeUsesVAFloatArgument(I, &MMI);
5846 const char *RenameFn = 0;
5847 if (Function *F = I.getCalledFunction()) {
5848 if (F->isDeclaration()) {
5849 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5850 if (unsigned IID = II->getIntrinsicID(F)) {
5851 RenameFn = visitIntrinsicCall(I, IID);
5856 if (unsigned IID = F->getIntrinsicID()) {
5857 RenameFn = visitIntrinsicCall(I, IID);
5863 // Check for well-known libc/libm calls. If the function is internal, it
5864 // can't be a library call.
5866 if (!F->hasLocalLinkage() && F->hasName() &&
5867 LibInfo->getLibFunc(F->getName(), Func) &&
5868 LibInfo->hasOptimizedCodeGen(Func)) {
5871 case LibFunc::copysign:
5872 case LibFunc::copysignf:
5873 case LibFunc::copysignl:
5874 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5875 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5876 I.getType() == I.getArgOperand(0)->getType() &&
5877 I.getType() == I.getArgOperand(1)->getType() &&
5878 I.onlyReadsMemory()) {
5879 SDValue LHS = getValue(I.getArgOperand(0));
5880 SDValue RHS = getValue(I.getArgOperand(1));
5881 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5882 LHS.getValueType(), LHS, RHS));
5887 case LibFunc::fabsf:
5888 case LibFunc::fabsl:
5889 if (visitUnaryFloatCall(I, ISD::FABS))
5895 if (visitUnaryFloatCall(I, ISD::FSIN))
5901 if (visitUnaryFloatCall(I, ISD::FCOS))
5905 case LibFunc::sqrtf:
5906 case LibFunc::sqrtl:
5907 case LibFunc::sqrt_finite:
5908 case LibFunc::sqrtf_finite:
5909 case LibFunc::sqrtl_finite:
5910 if (visitUnaryFloatCall(I, ISD::FSQRT))
5913 case LibFunc::floor:
5914 case LibFunc::floorf:
5915 case LibFunc::floorl:
5916 if (visitUnaryFloatCall(I, ISD::FFLOOR))
5919 case LibFunc::nearbyint:
5920 case LibFunc::nearbyintf:
5921 case LibFunc::nearbyintl:
5922 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
5926 case LibFunc::ceilf:
5927 case LibFunc::ceill:
5928 if (visitUnaryFloatCall(I, ISD::FCEIL))
5932 case LibFunc::rintf:
5933 case LibFunc::rintl:
5934 if (visitUnaryFloatCall(I, ISD::FRINT))
5937 case LibFunc::round:
5938 case LibFunc::roundf:
5939 case LibFunc::roundl:
5940 if (visitUnaryFloatCall(I, ISD::FROUND))
5943 case LibFunc::trunc:
5944 case LibFunc::truncf:
5945 case LibFunc::truncl:
5946 if (visitUnaryFloatCall(I, ISD::FTRUNC))
5950 case LibFunc::log2f:
5951 case LibFunc::log2l:
5952 if (visitUnaryFloatCall(I, ISD::FLOG2))
5956 case LibFunc::exp2f:
5957 case LibFunc::exp2l:
5958 if (visitUnaryFloatCall(I, ISD::FEXP2))
5961 case LibFunc::memcmp:
5962 if (visitMemCmpCall(I))
5965 case LibFunc::memchr:
5966 if (visitMemChrCall(I))
5969 case LibFunc::strcpy:
5970 if (visitStrCpyCall(I, false))
5973 case LibFunc::stpcpy:
5974 if (visitStrCpyCall(I, true))
5977 case LibFunc::strcmp:
5978 if (visitStrCmpCall(I))
5981 case LibFunc::strlen:
5982 if (visitStrLenCall(I))
5985 case LibFunc::strnlen:
5986 if (visitStrNLenCall(I))
5995 Callee = getValue(I.getCalledValue());
5997 Callee = DAG.getExternalSymbol(RenameFn,
5998 TM.getTargetLowering()->getPointerTy());
6000 // Check if we can potentially perform a tail call. More detailed checking is
6001 // be done within LowerCallTo, after more information about the call is known.
6002 LowerCallTo(&I, Callee, I.isTailCall());
6007 /// AsmOperandInfo - This contains information for each constraint that we are
6009 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6011 /// CallOperand - If this is the result output operand or a clobber
6012 /// this is null, otherwise it is the incoming operand to the CallInst.
6013 /// This gets modified as the asm is processed.
6014 SDValue CallOperand;
6016 /// AssignedRegs - If this is a register or register class operand, this
6017 /// contains the set of register corresponding to the operand.
6018 RegsForValue AssignedRegs;
6020 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6021 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
6024 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6025 /// corresponds to. If there is no Value* for this operand, it returns
6027 EVT getCallOperandValEVT(LLVMContext &Context,
6028 const TargetLowering &TLI,
6029 const DataLayout *TD) const {
6030 if (CallOperandVal == 0) return MVT::Other;
6032 if (isa<BasicBlock>(CallOperandVal))
6033 return TLI.getPointerTy();
6035 llvm::Type *OpTy = CallOperandVal->getType();
6037 // FIXME: code duplicated from TargetLowering::ParseConstraints().
6038 // If this is an indirect operand, the operand is a pointer to the
6041 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6043 report_fatal_error("Indirect operand for inline asm not a pointer!");
6044 OpTy = PtrTy->getElementType();
6047 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6048 if (StructType *STy = dyn_cast<StructType>(OpTy))
6049 if (STy->getNumElements() == 1)
6050 OpTy = STy->getElementType(0);
6052 // If OpTy is not a single value, it may be a struct/union that we
6053 // can tile with integers.
6054 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6055 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
6064 OpTy = IntegerType::get(Context, BitSize);
6069 return TLI.getValueType(OpTy, true);
6073 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6075 } // end anonymous namespace
6077 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6078 /// specified operand. We prefer to assign virtual registers, to allow the
6079 /// register allocator to handle the assignment process. However, if the asm
6080 /// uses features that we can't model on machineinstrs, we have SDISel do the
6081 /// allocation. This produces generally horrible, but correct, code.
6083 /// OpInfo describes the operand.
6085 static void GetRegistersForValue(SelectionDAG &DAG,
6086 const TargetLowering &TLI,
6088 SDISelAsmOperandInfo &OpInfo) {
6089 LLVMContext &Context = *DAG.getContext();
6091 MachineFunction &MF = DAG.getMachineFunction();
6092 SmallVector<unsigned, 4> Regs;
6094 // If this is a constraint for a single physreg, or a constraint for a
6095 // register class, find it.
6096 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
6097 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6098 OpInfo.ConstraintVT);
6100 unsigned NumRegs = 1;
6101 if (OpInfo.ConstraintVT != MVT::Other) {
6102 // If this is a FP input in an integer register (or visa versa) insert a bit
6103 // cast of the input value. More generally, handle any case where the input
6104 // value disagrees with the register class we plan to stick this in.
6105 if (OpInfo.Type == InlineAsm::isInput &&
6106 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6107 // Try to convert to the first EVT that the reg class contains. If the
6108 // types are identical size, use a bitcast to convert (e.g. two differing
6110 MVT RegVT = *PhysReg.second->vt_begin();
6111 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
6112 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6113 RegVT, OpInfo.CallOperand);
6114 OpInfo.ConstraintVT = RegVT;
6115 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6116 // If the input is a FP value and we want it in FP registers, do a
6117 // bitcast to the corresponding integer type. This turns an f64 value
6118 // into i64, which can be passed with two i32 values on a 32-bit
6120 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6121 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6122 RegVT, OpInfo.CallOperand);
6123 OpInfo.ConstraintVT = RegVT;
6127 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6131 EVT ValueVT = OpInfo.ConstraintVT;
6133 // If this is a constraint for a specific physical register, like {r17},
6135 if (unsigned AssignedReg = PhysReg.first) {
6136 const TargetRegisterClass *RC = PhysReg.second;
6137 if (OpInfo.ConstraintVT == MVT::Other)
6138 ValueVT = *RC->vt_begin();
6140 // Get the actual register value type. This is important, because the user
6141 // may have asked for (e.g.) the AX register in i32 type. We need to
6142 // remember that AX is actually i16 to get the right extension.
6143 RegVT = *RC->vt_begin();
6145 // This is a explicit reference to a physical register.
6146 Regs.push_back(AssignedReg);
6148 // If this is an expanded reference, add the rest of the regs to Regs.
6150 TargetRegisterClass::iterator I = RC->begin();
6151 for (; *I != AssignedReg; ++I)
6152 assert(I != RC->end() && "Didn't find reg!");
6154 // Already added the first reg.
6156 for (; NumRegs; --NumRegs, ++I) {
6157 assert(I != RC->end() && "Ran out of registers to allocate!");
6162 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6166 // Otherwise, if this was a reference to an LLVM register class, create vregs
6167 // for this reference.
6168 if (const TargetRegisterClass *RC = PhysReg.second) {
6169 RegVT = *RC->vt_begin();
6170 if (OpInfo.ConstraintVT == MVT::Other)
6173 // Create the appropriate number of virtual registers.
6174 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6175 for (; NumRegs; --NumRegs)
6176 Regs.push_back(RegInfo.createVirtualRegister(RC));
6178 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6182 // Otherwise, we couldn't allocate enough registers for this.
6185 /// visitInlineAsm - Handle a call to an InlineAsm object.
6187 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6188 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6190 /// ConstraintOperands - Information about all of the constraints.
6191 SDISelAsmOperandInfoVector ConstraintOperands;
6193 const TargetLowering *TLI = TM.getTargetLowering();
6194 TargetLowering::AsmOperandInfoVector
6195 TargetConstraints = TLI->ParseConstraints(CS);
6197 bool hasMemory = false;
6199 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6200 unsigned ResNo = 0; // ResNo - The result number of the next output.
6201 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6202 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6203 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6205 MVT OpVT = MVT::Other;
6207 // Compute the value type for each operand.
6208 switch (OpInfo.Type) {
6209 case InlineAsm::isOutput:
6210 // Indirect outputs just consume an argument.
6211 if (OpInfo.isIndirect) {
6212 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6216 // The return value of the call is this value. As such, there is no
6217 // corresponding argument.
6218 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6219 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6220 OpVT = TLI->getSimpleValueType(STy->getElementType(ResNo));
6222 assert(ResNo == 0 && "Asm only has one result!");
6223 OpVT = TLI->getSimpleValueType(CS.getType());
6227 case InlineAsm::isInput:
6228 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6230 case InlineAsm::isClobber:
6235 // If this is an input or an indirect output, process the call argument.
6236 // BasicBlocks are labels, currently appearing only in asm's.
6237 if (OpInfo.CallOperandVal) {
6238 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6239 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6241 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6244 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), *TLI, TD).
6248 OpInfo.ConstraintVT = OpVT;
6250 // Indirect operand accesses access memory.
6251 if (OpInfo.isIndirect)
6254 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6255 TargetLowering::ConstraintType
6256 CType = TLI->getConstraintType(OpInfo.Codes[j]);
6257 if (CType == TargetLowering::C_Memory) {
6265 SDValue Chain, Flag;
6267 // We won't need to flush pending loads if this asm doesn't touch
6268 // memory and is nonvolatile.
6269 if (hasMemory || IA->hasSideEffects())
6272 Chain = DAG.getRoot();
6274 // Second pass over the constraints: compute which constraint option to use
6275 // and assign registers to constraints that want a specific physreg.
6276 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6277 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6279 // If this is an output operand with a matching input operand, look up the
6280 // matching input. If their types mismatch, e.g. one is an integer, the
6281 // other is floating point, or their sizes are different, flag it as an
6283 if (OpInfo.hasMatchingInput()) {
6284 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6286 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6287 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
6288 TLI->getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6289 OpInfo.ConstraintVT);
6290 std::pair<unsigned, const TargetRegisterClass*> InputRC =
6291 TLI->getRegForInlineAsmConstraint(Input.ConstraintCode,
6292 Input.ConstraintVT);
6293 if ((OpInfo.ConstraintVT.isInteger() !=
6294 Input.ConstraintVT.isInteger()) ||
6295 (MatchRC.second != InputRC.second)) {
6296 report_fatal_error("Unsupported asm: input constraint"
6297 " with a matching output constraint of"
6298 " incompatible type!");
6300 Input.ConstraintVT = OpInfo.ConstraintVT;
6304 // Compute the constraint code and ConstraintType to use.
6305 TLI->ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6307 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6308 OpInfo.Type == InlineAsm::isClobber)
6311 // If this is a memory input, and if the operand is not indirect, do what we
6312 // need to to provide an address for the memory input.
6313 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6314 !OpInfo.isIndirect) {
6315 assert((OpInfo.isMultipleAlternative ||
6316 (OpInfo.Type == InlineAsm::isInput)) &&
6317 "Can only indirectify direct input operands!");
6319 // Memory operands really want the address of the value. If we don't have
6320 // an indirect input, put it in the constpool if we can, otherwise spill
6321 // it to a stack slot.
6322 // TODO: This isn't quite right. We need to handle these according to
6323 // the addressing mode that the constraint wants. Also, this may take
6324 // an additional register for the computation and we don't want that
6327 // If the operand is a float, integer, or vector constant, spill to a
6328 // constant pool entry to get its address.
6329 const Value *OpVal = OpInfo.CallOperandVal;
6330 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6331 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6332 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6333 TLI->getPointerTy());
6335 // Otherwise, create a stack slot and emit a store to it before the
6337 Type *Ty = OpVal->getType();
6338 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
6339 unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(Ty);
6340 MachineFunction &MF = DAG.getMachineFunction();
6341 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6342 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI->getPointerTy());
6343 Chain = DAG.getStore(Chain, getCurSDLoc(),
6344 OpInfo.CallOperand, StackSlot,
6345 MachinePointerInfo::getFixedStack(SSFI),
6347 OpInfo.CallOperand = StackSlot;
6350 // There is no longer a Value* corresponding to this operand.
6351 OpInfo.CallOperandVal = 0;
6353 // It is now an indirect operand.
6354 OpInfo.isIndirect = true;
6357 // If this constraint is for a specific register, allocate it before
6359 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6360 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
6363 // Second pass - Loop over all of the operands, assigning virtual or physregs
6364 // to register class operands.
6365 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6366 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6368 // C_Register operands have already been allocated, Other/Memory don't need
6370 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6371 GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
6374 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6375 std::vector<SDValue> AsmNodeOperands;
6376 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6377 AsmNodeOperands.push_back(
6378 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6379 TLI->getPointerTy()));
6381 // If we have a !srcloc metadata node associated with it, we want to attach
6382 // this to the ultimately generated inline asm machineinstr. To do this, we
6383 // pass in the third operand as this (potentially null) inline asm MDNode.
6384 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6385 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6387 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6388 // bits as operand 3.
6389 unsigned ExtraInfo = 0;
6390 if (IA->hasSideEffects())
6391 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6392 if (IA->isAlignStack())
6393 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6394 // Set the asm dialect.
6395 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6397 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6398 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6399 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6401 // Compute the constraint code and ConstraintType to use.
6402 TLI->ComputeConstraintToUse(OpInfo, SDValue());
6404 // Ideally, we would only check against memory constraints. However, the
6405 // meaning of an other constraint can be target-specific and we can't easily
6406 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6407 // for other constriants as well.
6408 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6409 OpInfo.ConstraintType == TargetLowering::C_Other) {
6410 if (OpInfo.Type == InlineAsm::isInput)
6411 ExtraInfo |= InlineAsm::Extra_MayLoad;
6412 else if (OpInfo.Type == InlineAsm::isOutput)
6413 ExtraInfo |= InlineAsm::Extra_MayStore;
6414 else if (OpInfo.Type == InlineAsm::isClobber)
6415 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6419 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6420 TLI->getPointerTy()));
6422 // Loop over all of the inputs, copying the operand values into the
6423 // appropriate registers and processing the output regs.
6424 RegsForValue RetValRegs;
6426 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6427 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6429 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6430 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6432 switch (OpInfo.Type) {
6433 case InlineAsm::isOutput: {
6434 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6435 OpInfo.ConstraintType != TargetLowering::C_Register) {
6436 // Memory output, or 'other' output (e.g. 'X' constraint).
6437 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6439 // Add information to the INLINEASM node to know about this output.
6440 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6441 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
6442 TLI->getPointerTy()));
6443 AsmNodeOperands.push_back(OpInfo.CallOperand);
6447 // Otherwise, this is a register or register class output.
6449 // Copy the output from the appropriate register. Find a register that
6451 if (OpInfo.AssignedRegs.Regs.empty()) {
6452 LLVMContext &Ctx = *DAG.getContext();
6453 Ctx.emitError(CS.getInstruction(),
6454 "couldn't allocate output register for constraint '" +
6455 Twine(OpInfo.ConstraintCode) + "'");
6459 // If this is an indirect operand, store through the pointer after the
6461 if (OpInfo.isIndirect) {
6462 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6463 OpInfo.CallOperandVal));
6465 // This is the result value of the call.
6466 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6467 // Concatenate this output onto the outputs list.
6468 RetValRegs.append(OpInfo.AssignedRegs);
6471 // Add information to the INLINEASM node to know that this register is
6474 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6475 ? InlineAsm::Kind_RegDefEarlyClobber
6476 : InlineAsm::Kind_RegDef,
6477 false, 0, DAG, AsmNodeOperands);
6480 case InlineAsm::isInput: {
6481 SDValue InOperandVal = OpInfo.CallOperand;
6483 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6484 // If this is required to match an output register we have already set,
6485 // just use its register.
6486 unsigned OperandNo = OpInfo.getMatchedOperand();
6488 // Scan until we find the definition we already emitted of this operand.
6489 // When we find it, create a RegsForValue operand.
6490 unsigned CurOp = InlineAsm::Op_FirstOperand;
6491 for (; OperandNo; --OperandNo) {
6492 // Advance to the next operand.
6494 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6495 assert((InlineAsm::isRegDefKind(OpFlag) ||
6496 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6497 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6498 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6502 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6503 if (InlineAsm::isRegDefKind(OpFlag) ||
6504 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6505 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6506 if (OpInfo.isIndirect) {
6507 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6508 LLVMContext &Ctx = *DAG.getContext();
6509 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6510 " don't know how to handle tied "
6511 "indirect register inputs");
6515 RegsForValue MatchedRegs;
6516 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6517 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6518 MatchedRegs.RegVTs.push_back(RegVT);
6519 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6520 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6522 if (const TargetRegisterClass *RC = TLI->getRegClassFor(RegVT))
6523 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6525 LLVMContext &Ctx = *DAG.getContext();
6526 Ctx.emitError(CS.getInstruction(),
6527 "inline asm error: This value"
6528 " type register class is not natively supported!");
6532 // Use the produced MatchedRegs object to
6533 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6534 Chain, &Flag, CS.getInstruction());
6535 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6536 true, OpInfo.getMatchedOperand(),
6537 DAG, AsmNodeOperands);
6541 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6542 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6543 "Unexpected number of operands");
6544 // Add information to the INLINEASM node to know about this input.
6545 // See InlineAsm.h isUseOperandTiedToDef.
6546 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6547 OpInfo.getMatchedOperand());
6548 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6549 TLI->getPointerTy()));
6550 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6554 // Treat indirect 'X' constraint as memory.
6555 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6557 OpInfo.ConstraintType = TargetLowering::C_Memory;
6559 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6560 std::vector<SDValue> Ops;
6561 TLI->LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6564 LLVMContext &Ctx = *DAG.getContext();
6565 Ctx.emitError(CS.getInstruction(),
6566 "invalid operand for inline asm constraint '" +
6567 Twine(OpInfo.ConstraintCode) + "'");
6571 // Add information to the INLINEASM node to know about this input.
6572 unsigned ResOpType =
6573 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6574 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6575 TLI->getPointerTy()));
6576 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6580 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6581 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6582 assert(InOperandVal.getValueType() == TLI->getPointerTy() &&
6583 "Memory operands expect pointer values");
6585 // Add information to the INLINEASM node to know about this input.
6586 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6587 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6588 TLI->getPointerTy()));
6589 AsmNodeOperands.push_back(InOperandVal);
6593 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6594 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6595 "Unknown constraint type!");
6597 // TODO: Support this.
6598 if (OpInfo.isIndirect) {
6599 LLVMContext &Ctx = *DAG.getContext();
6600 Ctx.emitError(CS.getInstruction(),
6601 "Don't know how to handle indirect register inputs yet "
6602 "for constraint '" +
6603 Twine(OpInfo.ConstraintCode) + "'");
6607 // Copy the input into the appropriate registers.
6608 if (OpInfo.AssignedRegs.Regs.empty()) {
6609 LLVMContext &Ctx = *DAG.getContext();
6610 Ctx.emitError(CS.getInstruction(),
6611 "couldn't allocate input reg for constraint '" +
6612 Twine(OpInfo.ConstraintCode) + "'");
6616 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6617 Chain, &Flag, CS.getInstruction());
6619 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6620 DAG, AsmNodeOperands);
6623 case InlineAsm::isClobber: {
6624 // Add the clobbered value to the operand list, so that the register
6625 // allocator is aware that the physreg got clobbered.
6626 if (!OpInfo.AssignedRegs.Regs.empty())
6627 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6635 // Finish up input operands. Set the input chain and add the flag last.
6636 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6637 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6639 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6640 DAG.getVTList(MVT::Other, MVT::Glue),
6641 &AsmNodeOperands[0], AsmNodeOperands.size());
6642 Flag = Chain.getValue(1);
6644 // If this asm returns a register value, copy the result from that register
6645 // and set it as the value of the call.
6646 if (!RetValRegs.Regs.empty()) {
6647 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6648 Chain, &Flag, CS.getInstruction());
6650 // FIXME: Why don't we do this for inline asms with MRVs?
6651 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6652 EVT ResultType = TLI->getValueType(CS.getType());
6654 // If any of the results of the inline asm is a vector, it may have the
6655 // wrong width/num elts. This can happen for register classes that can
6656 // contain multiple different value types. The preg or vreg allocated may
6657 // not have the same VT as was expected. Convert it to the right type
6658 // with bit_convert.
6659 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6660 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6663 } else if (ResultType != Val.getValueType() &&
6664 ResultType.isInteger() && Val.getValueType().isInteger()) {
6665 // If a result value was tied to an input value, the computed result may
6666 // have a wider width than the expected result. Extract the relevant
6668 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6671 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6674 setValue(CS.getInstruction(), Val);
6675 // Don't need to use this as a chain in this case.
6676 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6680 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6682 // Process indirect outputs, first output all of the flagged copies out of
6684 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6685 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6686 const Value *Ptr = IndirectStoresToEmit[i].second;
6687 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6689 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6692 // Emit the non-flagged stores from the physregs.
6693 SmallVector<SDValue, 8> OutChains;
6694 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6695 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6696 StoresToEmit[i].first,
6697 getValue(StoresToEmit[i].second),
6698 MachinePointerInfo(StoresToEmit[i].second),
6700 OutChains.push_back(Val);
6703 if (!OutChains.empty())
6704 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
6705 &OutChains[0], OutChains.size());
6710 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6711 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6712 MVT::Other, getRoot(),
6713 getValue(I.getArgOperand(0)),
6714 DAG.getSrcValue(I.getArgOperand(0))));
6717 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6718 const TargetLowering *TLI = TM.getTargetLowering();
6719 const DataLayout &TD = *TLI->getDataLayout();
6720 SDValue V = DAG.getVAArg(TLI->getValueType(I.getType()), getCurSDLoc(),
6721 getRoot(), getValue(I.getOperand(0)),
6722 DAG.getSrcValue(I.getOperand(0)),
6723 TD.getABITypeAlignment(I.getType()));
6725 DAG.setRoot(V.getValue(1));
6728 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6729 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6730 MVT::Other, getRoot(),
6731 getValue(I.getArgOperand(0)),
6732 DAG.getSrcValue(I.getArgOperand(0))));
6735 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6736 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6737 MVT::Other, getRoot(),
6738 getValue(I.getArgOperand(0)),
6739 getValue(I.getArgOperand(1)),
6740 DAG.getSrcValue(I.getArgOperand(0)),
6741 DAG.getSrcValue(I.getArgOperand(1))));
6744 /// \brief Lower an argument list according to the target calling convention.
6746 /// \return A tuple of <return-value, token-chain>
6748 /// This is a helper for lowering intrinsics that follow a target calling
6749 /// convention or require stack pointer adjustment. Only a subset of the
6750 /// intrinsic's operands need to participate in the calling convention.
6751 std::pair<SDValue, SDValue>
6752 SelectionDAGBuilder::LowerCallOperands(const CallInst &CI, unsigned ArgIdx,
6753 unsigned NumArgs, SDValue Callee,
6755 TargetLowering::ArgListTy Args;
6756 Args.reserve(NumArgs);
6758 // Populate the argument list.
6759 // Attributes for args start at offset 1, after the return attribute.
6760 ImmutableCallSite CS(&CI);
6761 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6762 ArgI != ArgE; ++ArgI) {
6763 const Value *V = CI.getOperand(ArgI);
6765 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6767 TargetLowering::ArgListEntry Entry;
6768 Entry.Node = getValue(V);
6769 Entry.Ty = V->getType();
6770 Entry.setAttributes(&CS, AttrI);
6771 Args.push_back(Entry);
6774 Type *retTy = useVoidTy ? Type::getVoidTy(*DAG.getContext()) : CI.getType();
6775 TargetLowering::CallLoweringInfo CLI(getRoot(), retTy, /*retSExt*/ false,
6776 /*retZExt*/ false, /*isVarArg*/ false, /*isInReg*/ false, NumArgs,
6777 CI.getCallingConv(), /*isTailCall*/ false, /*doesNotReturn*/ false,
6778 /*isReturnValueUsed*/ CI.use_empty(), Callee, Args, DAG, getCurSDLoc());
6780 const TargetLowering *TLI = TM.getTargetLowering();
6781 return TLI->LowerCallTo(CLI);
6784 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6785 /// or patchpoint target node's operand list.
6787 /// Constants are converted to TargetConstants purely as an optimization to
6788 /// avoid constant materialization and register allocation.
6790 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6791 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6792 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6793 /// address materialization and register allocation, but may also be required
6794 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6795 /// alloca in the entry block, then the runtime may assume that the alloca's
6796 /// StackMap location can be read immediately after compilation and that the
6797 /// location is valid at any point during execution (this is similar to the
6798 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6799 /// only available in a register, then the runtime would need to trap when
6800 /// execution reaches the StackMap in order to read the alloca's location.
6801 static void addStackMapLiveVars(const CallInst &CI, unsigned StartIdx,
6802 SmallVectorImpl<SDValue> &Ops,
6803 SelectionDAGBuilder &Builder) {
6804 for (unsigned i = StartIdx, e = CI.getNumArgOperands(); i != e; ++i) {
6805 SDValue OpVal = Builder.getValue(CI.getArgOperand(i));
6806 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6808 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
6810 Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
6811 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6812 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6814 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
6816 Ops.push_back(OpVal);
6820 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6821 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6822 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6823 // [live variables...])
6825 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6827 SDValue Callee = getValue(CI.getCalledValue());
6829 // Lower into a call sequence with no args and no return value.
6830 std::pair<SDValue, SDValue> Result = LowerCallOperands(CI, 0, 0, Callee);
6831 // Set the root to the target-lowered call chain.
6832 SDValue Chain = Result.second;
6835 /// Get a call instruction from the call sequence chain.
6836 /// Tail calls are not allowed.
6837 SDNode *CallEnd = Chain.getNode();
6838 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6839 "Expected a callseq node.");
6840 SDNode *Call = CallEnd->getOperand(0).getNode();
6841 bool hasGlue = Call->getGluedNode();
6843 // Replace the target specific call node with the stackmap intrinsic.
6844 SmallVector<SDValue, 8> Ops;
6846 // Add the <id> and <numShadowBytes> constants.
6847 for (unsigned i = 0; i < 2; ++i) {
6848 SDValue tmp = getValue(CI.getOperand(i));
6849 Ops.push_back(DAG.getTargetConstant(
6850 cast<ConstantSDNode>(tmp)->getZExtValue(), MVT::i32));
6852 // Push live variables for the stack map.
6853 addStackMapLiveVars(CI, 2, Ops, *this);
6855 // Push the chain (this is originally the first operand of the call, but
6856 // becomes now the last or second to last operand).
6857 Ops.push_back(*(Call->op_begin()));
6859 // Push the glue flag (last operand).
6861 Ops.push_back(*(Call->op_end()-1));
6863 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6865 // Replace the target specific call node with a STACKMAP node.
6866 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::STACKMAP, getCurSDLoc(),
6869 // StackMap generates no value, so nothing goes in the NodeMap.
6871 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
6873 DAG.ReplaceAllUsesWith(Call, MN);
6875 DAG.DeleteNode(Call);
6878 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6879 void SelectionDAGBuilder::visitPatchpoint(const CallInst &CI) {
6880 // void|i64 @llvm.experimental.patchpoint.void|i64(i32 <id>,
6885 // [live variables...])
6887 CallingConv::ID CC = CI.getCallingConv();
6888 bool isAnyRegCC = CC == CallingConv::AnyReg;
6889 bool hasDef = !CI.getType()->isVoidTy();
6890 SDValue Callee = getValue(CI.getOperand(2)); // <target>
6892 // Get the real number of arguments participating in the call <numArgs>
6893 SDValue NArgVal = getValue(CI.getArgOperand(PatchPointOpers::NArgPos));
6894 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
6896 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
6897 // Intrinsics include all meta-operands up to but not including CC.
6898 unsigned NumMetaOpers = PatchPointOpers::CCPos;
6899 assert(CI.getNumArgOperands() >= NumMetaOpers + NumArgs &&
6900 "Not enough arguments provided to the patchpoint intrinsic");
6902 // For AnyRegCC the arguments are lowered later on manually.
6903 unsigned NumCallArgs = isAnyRegCC ? 0 : NumArgs;
6904 std::pair<SDValue, SDValue> Result =
6905 LowerCallOperands(CI, NumMetaOpers, NumCallArgs, Callee, isAnyRegCC);
6907 // Set the root to the target-lowered call chain.
6908 SDValue Chain = Result.second;
6911 SDNode *CallEnd = Chain.getNode();
6912 if (hasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
6913 CallEnd = CallEnd->getOperand(0).getNode();
6915 /// Get a call instruction from the call sequence chain.
6916 /// Tail calls are not allowed.
6917 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6918 "Expected a callseq node.");
6919 SDNode *Call = CallEnd->getOperand(0).getNode();
6920 bool hasGlue = Call->getGluedNode();
6922 // Replace the target specific call node with the patchable intrinsic.
6923 SmallVector<SDValue, 8> Ops;
6925 // Add the <id> and <numBytes> constants.
6926 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
6927 Ops.push_back(DAG.getTargetConstant(
6928 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i32));
6929 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
6930 Ops.push_back(DAG.getTargetConstant(
6931 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
6933 // Assume that the Callee is a constant address.
6934 // FIXME: handle function symbols in the future.
6936 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
6937 /*isTarget=*/true));
6939 // Adjust <numArgs> to account for any arguments that have been passed on the
6941 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
6942 unsigned NumCallRegArgs = Call->getNumOperands() - (hasGlue ? 4 : 3);
6943 NumCallRegArgs = isAnyRegCC ? NumArgs : NumCallRegArgs;
6944 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
6946 // Add the calling convention
6947 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
6949 // Add the arguments we omitted previously. The register allocator should
6950 // place these in any free register.
6952 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
6953 Ops.push_back(getValue(CI.getArgOperand(i)));
6955 // Push the arguments from the call instruction up to the register mask.
6956 SDNode::op_iterator e = hasGlue ? Call->op_end()-2 : Call->op_end()-1;
6957 for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
6960 // Push live variables for the stack map.
6961 addStackMapLiveVars(CI, NumMetaOpers + NumArgs, Ops, *this);
6963 // Push the register mask info.
6965 Ops.push_back(*(Call->op_end()-2));
6967 Ops.push_back(*(Call->op_end()-1));
6969 // Push the chain (this is originally the first operand of the call, but
6970 // becomes now the last or second to last operand).
6971 Ops.push_back(*(Call->op_begin()));
6973 // Push the glue flag (last operand).
6975 Ops.push_back(*(Call->op_end()-1));
6978 if (isAnyRegCC && hasDef) {
6979 // Create the return types based on the intrinsic definition
6980 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6981 SmallVector<EVT, 3> ValueVTs;
6982 ComputeValueVTs(TLI, CI.getType(), ValueVTs);
6983 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
6985 // There is always a chain and a glue type at the end
6986 ValueVTs.push_back(MVT::Other);
6987 ValueVTs.push_back(MVT::Glue);
6988 NodeTys = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
6990 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6992 // Replace the target specific call node with a PATCHPOINT node.
6993 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
6994 getCurSDLoc(), NodeTys, Ops);
6996 // Update the NodeMap.
6999 setValue(&CI, SDValue(MN, 0));
7001 setValue(&CI, Result.first);
7004 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7005 // call sequence. Furthermore the location of the chain and glue can change
7006 // when the AnyReg calling convention is used and the intrinsic returns a
7008 if (isAnyRegCC && hasDef) {
7009 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7010 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7011 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7013 DAG.ReplaceAllUsesWith(Call, MN);
7014 DAG.DeleteNode(Call);
7017 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7018 /// implementation, which just calls LowerCall.
7019 /// FIXME: When all targets are
7020 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7021 std::pair<SDValue, SDValue>
7022 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7023 // Handle the incoming return values from the call.
7025 SmallVector<EVT, 4> RetTys;
7026 ComputeValueVTs(*this, CLI.RetTy, RetTys);
7027 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7029 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7030 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7031 for (unsigned i = 0; i != NumRegs; ++i) {
7032 ISD::InputArg MyFlags;
7033 MyFlags.VT = RegisterVT;
7035 MyFlags.Used = CLI.IsReturnValueUsed;
7037 MyFlags.Flags.setSExt();
7039 MyFlags.Flags.setZExt();
7041 MyFlags.Flags.setInReg();
7042 CLI.Ins.push_back(MyFlags);
7046 // Handle all of the outgoing arguments.
7048 CLI.OutVals.clear();
7049 ArgListTy &Args = CLI.Args;
7050 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7051 SmallVector<EVT, 4> ValueVTs;
7052 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
7053 for (unsigned Value = 0, NumValues = ValueVTs.size();
7054 Value != NumValues; ++Value) {
7055 EVT VT = ValueVTs[Value];
7056 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7057 SDValue Op = SDValue(Args[i].Node.getNode(),
7058 Args[i].Node.getResNo() + Value);
7059 ISD::ArgFlagsTy Flags;
7060 unsigned OriginalAlignment =
7061 getDataLayout()->getABITypeAlignment(ArgTy);
7067 if (Args[i].isInReg)
7071 if (Args[i].isByVal) {
7073 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7074 Type *ElementTy = Ty->getElementType();
7075 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
7076 // For ByVal, alignment should come from FE. BE will guess if this
7077 // info is not there but there are cases it cannot get right.
7078 unsigned FrameAlign;
7079 if (Args[i].Alignment)
7080 FrameAlign = Args[i].Alignment;
7082 FrameAlign = getByValTypeAlignment(ElementTy);
7083 Flags.setByValAlign(FrameAlign);
7087 Flags.setOrigAlign(OriginalAlignment);
7089 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7090 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7091 SmallVector<SDValue, 4> Parts(NumParts);
7092 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7095 ExtendKind = ISD::SIGN_EXTEND;
7096 else if (Args[i].isZExt)
7097 ExtendKind = ISD::ZERO_EXTEND;
7099 // Conservatively only handle 'returned' on non-vectors for now
7100 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7101 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7102 "unexpected use of 'returned'");
7103 // Before passing 'returned' to the target lowering code, ensure that
7104 // either the register MVT and the actual EVT are the same size or that
7105 // the return value and argument are extended in the same way; in these
7106 // cases it's safe to pass the argument register value unchanged as the
7107 // return register value (although it's at the target's option whether
7109 // TODO: allow code generation to take advantage of partially preserved
7110 // registers rather than clobbering the entire register when the
7111 // parameter extension method is not compatible with the return
7113 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7114 (ExtendKind != ISD::ANY_EXTEND &&
7115 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7116 Flags.setReturned();
7119 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts,
7120 PartVT, CLI.CS ? CLI.CS->getInstruction() : 0, ExtendKind);
7122 for (unsigned j = 0; j != NumParts; ++j) {
7123 // if it isn't first piece, alignment must be 1
7124 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7125 i < CLI.NumFixedArgs,
7126 i, j*Parts[j].getValueType().getStoreSize());
7127 if (NumParts > 1 && j == 0)
7128 MyFlags.Flags.setSplit();
7130 MyFlags.Flags.setOrigAlign(1);
7132 CLI.Outs.push_back(MyFlags);
7133 CLI.OutVals.push_back(Parts[j]);
7138 SmallVector<SDValue, 4> InVals;
7139 CLI.Chain = LowerCall(CLI, InVals);
7141 // Verify that the target's LowerCall behaved as expected.
7142 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7143 "LowerCall didn't return a valid chain!");
7144 assert((!CLI.IsTailCall || InVals.empty()) &&
7145 "LowerCall emitted a return value for a tail call!");
7146 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7147 "LowerCall didn't emit the correct number of values!");
7149 // For a tail call, the return value is merely live-out and there aren't
7150 // any nodes in the DAG representing it. Return a special value to
7151 // indicate that a tail call has been emitted and no more Instructions
7152 // should be processed in the current block.
7153 if (CLI.IsTailCall) {
7154 CLI.DAG.setRoot(CLI.Chain);
7155 return std::make_pair(SDValue(), SDValue());
7158 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7159 assert(InVals[i].getNode() &&
7160 "LowerCall emitted a null value!");
7161 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7162 "LowerCall emitted a value with the wrong type!");
7165 // Collect the legal value parts into potentially illegal values
7166 // that correspond to the original function's return values.
7167 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7169 AssertOp = ISD::AssertSext;
7170 else if (CLI.RetZExt)
7171 AssertOp = ISD::AssertZext;
7172 SmallVector<SDValue, 4> ReturnValues;
7173 unsigned CurReg = 0;
7174 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7176 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7177 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7179 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7180 NumRegs, RegisterVT, VT, NULL,
7185 // For a function returning void, there is no return value. We can't create
7186 // such a node, so we just return a null return value in that case. In
7187 // that case, nothing will actually look at the value.
7188 if (ReturnValues.empty())
7189 return std::make_pair(SDValue(), CLI.Chain);
7191 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7192 CLI.DAG.getVTList(&RetTys[0], RetTys.size()),
7193 &ReturnValues[0], ReturnValues.size());
7194 return std::make_pair(Res, CLI.Chain);
7197 void TargetLowering::LowerOperationWrapper(SDNode *N,
7198 SmallVectorImpl<SDValue> &Results,
7199 SelectionDAG &DAG) const {
7200 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
7202 Results.push_back(Res);
7205 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7206 llvm_unreachable("LowerOperation not implemented for this target!");
7210 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7211 SDValue Op = getNonRegisterValue(V);
7212 assert((Op.getOpcode() != ISD::CopyFromReg ||
7213 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7214 "Copy from a reg to the same reg!");
7215 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7217 const TargetLowering *TLI = TM.getTargetLowering();
7218 RegsForValue RFV(V->getContext(), *TLI, Reg, V->getType());
7219 SDValue Chain = DAG.getEntryNode();
7220 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, 0, V);
7221 PendingExports.push_back(Chain);
7224 #include "llvm/CodeGen/SelectionDAGISel.h"
7226 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7227 /// entry block, return true. This includes arguments used by switches, since
7228 /// the switch may expand into multiple basic blocks.
7229 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7230 // With FastISel active, we may be splitting blocks, so force creation
7231 // of virtual registers for all non-dead arguments.
7233 return A->use_empty();
7235 const BasicBlock *Entry = A->getParent()->begin();
7236 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
7238 const User *U = *UI;
7239 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7240 return false; // Use not in entry block.
7245 void SelectionDAGISel::LowerArguments(const Function &F) {
7246 SelectionDAG &DAG = SDB->DAG;
7247 SDLoc dl = SDB->getCurSDLoc();
7248 const TargetLowering *TLI = getTargetLowering();
7249 const DataLayout *TD = TLI->getDataLayout();
7250 SmallVector<ISD::InputArg, 16> Ins;
7252 if (!FuncInfo->CanLowerReturn) {
7253 // Put in an sret pointer parameter before all the other parameters.
7254 SmallVector<EVT, 1> ValueVTs;
7255 ComputeValueVTs(*getTargetLowering(),
7256 PointerType::getUnqual(F.getReturnType()), ValueVTs);
7258 // NOTE: Assuming that a pointer will never break down to more than one VT
7260 ISD::ArgFlagsTy Flags;
7262 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7263 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
7264 Ins.push_back(RetArg);
7267 // Set up the incoming argument description vector.
7269 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7270 I != E; ++I, ++Idx) {
7271 SmallVector<EVT, 4> ValueVTs;
7272 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7273 bool isArgValueUsed = !I->use_empty();
7274 unsigned PartBase = 0;
7275 for (unsigned Value = 0, NumValues = ValueVTs.size();
7276 Value != NumValues; ++Value) {
7277 EVT VT = ValueVTs[Value];
7278 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7279 ISD::ArgFlagsTy Flags;
7280 unsigned OriginalAlignment =
7281 TD->getABITypeAlignment(ArgTy);
7283 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7285 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7287 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7289 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7291 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) {
7293 PointerType *Ty = cast<PointerType>(I->getType());
7294 Type *ElementTy = Ty->getElementType();
7295 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
7296 // For ByVal, alignment should be passed from FE. BE will guess if
7297 // this info is not there but there are cases it cannot get right.
7298 unsigned FrameAlign;
7299 if (F.getParamAlignment(Idx))
7300 FrameAlign = F.getParamAlignment(Idx);
7302 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
7303 Flags.setByValAlign(FrameAlign);
7305 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7307 Flags.setOrigAlign(OriginalAlignment);
7309 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7310 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7311 for (unsigned i = 0; i != NumRegs; ++i) {
7312 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7313 Idx-1, PartBase+i*RegisterVT.getStoreSize());
7314 if (NumRegs > 1 && i == 0)
7315 MyFlags.Flags.setSplit();
7316 // if it isn't first piece, alignment must be 1
7318 MyFlags.Flags.setOrigAlign(1);
7319 Ins.push_back(MyFlags);
7321 PartBase += VT.getStoreSize();
7325 // Call the target to set up the argument values.
7326 SmallVector<SDValue, 8> InVals;
7327 SDValue NewRoot = TLI->LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
7331 // Verify that the target's LowerFormalArguments behaved as expected.
7332 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7333 "LowerFormalArguments didn't return a valid chain!");
7334 assert(InVals.size() == Ins.size() &&
7335 "LowerFormalArguments didn't emit the correct number of values!");
7337 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7338 assert(InVals[i].getNode() &&
7339 "LowerFormalArguments emitted a null value!");
7340 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7341 "LowerFormalArguments emitted a value with the wrong type!");
7345 // Update the DAG with the new chain value resulting from argument lowering.
7346 DAG.setRoot(NewRoot);
7348 // Set up the argument values.
7351 if (!FuncInfo->CanLowerReturn) {
7352 // Create a virtual register for the sret pointer, and put in a copy
7353 // from the sret argument into it.
7354 SmallVector<EVT, 1> ValueVTs;
7355 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7356 MVT VT = ValueVTs[0].getSimpleVT();
7357 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7358 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7359 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7360 RegVT, VT, NULL, AssertOp);
7362 MachineFunction& MF = SDB->DAG.getMachineFunction();
7363 MachineRegisterInfo& RegInfo = MF.getRegInfo();
7364 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7365 FuncInfo->DemoteRegister = SRetReg;
7366 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(),
7368 DAG.setRoot(NewRoot);
7370 // i indexes lowered arguments. Bump it past the hidden sret argument.
7371 // Idx indexes LLVM arguments. Don't touch it.
7375 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7377 SmallVector<SDValue, 4> ArgValues;
7378 SmallVector<EVT, 4> ValueVTs;
7379 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7380 unsigned NumValues = ValueVTs.size();
7382 // If this argument is unused then remember its value. It is used to generate
7383 // debugging information.
7384 if (I->use_empty() && NumValues) {
7385 SDB->setUnusedArgValue(I, InVals[i]);
7387 // Also remember any frame index for use in FastISel.
7388 if (FrameIndexSDNode *FI =
7389 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7390 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7393 for (unsigned Val = 0; Val != NumValues; ++Val) {
7394 EVT VT = ValueVTs[Val];
7395 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7396 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7398 if (!I->use_empty()) {
7399 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7400 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7401 AssertOp = ISD::AssertSext;
7402 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7403 AssertOp = ISD::AssertZext;
7405 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7406 NumParts, PartVT, VT,
7413 // We don't need to do anything else for unused arguments.
7414 if (ArgValues.empty())
7417 // Note down frame index.
7418 if (FrameIndexSDNode *FI =
7419 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7420 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7422 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
7423 SDB->getCurSDLoc());
7425 SDB->setValue(I, Res);
7426 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7427 if (LoadSDNode *LNode =
7428 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7429 if (FrameIndexSDNode *FI =
7430 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7431 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7434 // If this argument is live outside of the entry block, insert a copy from
7435 // wherever we got it to the vreg that other BB's will reference it as.
7436 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7437 // If we can, though, try to skip creating an unnecessary vreg.
7438 // FIXME: This isn't very clean... it would be nice to make this more
7439 // general. It's also subtly incompatible with the hacks FastISel
7441 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7442 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7443 FuncInfo->ValueMap[I] = Reg;
7447 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
7448 FuncInfo->InitializeRegForValue(I);
7449 SDB->CopyToExportRegsIfNeeded(I);
7453 assert(i == InVals.size() && "Argument register count mismatch!");
7455 // Finally, if the target has anything special to do, allow it to do so.
7456 // FIXME: this should insert code into the DAG!
7457 EmitFunctionEntryCode();
7460 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7461 /// ensure constants are generated when needed. Remember the virtual registers
7462 /// that need to be added to the Machine PHI nodes as input. We cannot just
7463 /// directly add them, because expansion might result in multiple MBB's for one
7464 /// BB. As such, the start of the BB might correspond to a different MBB than
7468 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7469 const TerminatorInst *TI = LLVMBB->getTerminator();
7471 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7473 // Check successor nodes' PHI nodes that expect a constant to be available
7475 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7476 const BasicBlock *SuccBB = TI->getSuccessor(succ);
7477 if (!isa<PHINode>(SuccBB->begin())) continue;
7478 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7480 // If this terminator has multiple identical successors (common for
7481 // switches), only handle each succ once.
7482 if (!SuccsHandled.insert(SuccMBB)) continue;
7484 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7486 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7487 // nodes and Machine PHI nodes, but the incoming operands have not been
7489 for (BasicBlock::const_iterator I = SuccBB->begin();
7490 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7491 // Ignore dead phi's.
7492 if (PN->use_empty()) continue;
7495 if (PN->getType()->isEmptyTy())
7499 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7501 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7502 unsigned &RegOut = ConstantsOut[C];
7504 RegOut = FuncInfo.CreateRegs(C->getType());
7505 CopyValueToVirtualRegister(C, RegOut);
7509 DenseMap<const Value *, unsigned>::iterator I =
7510 FuncInfo.ValueMap.find(PHIOp);
7511 if (I != FuncInfo.ValueMap.end())
7514 assert(isa<AllocaInst>(PHIOp) &&
7515 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7516 "Didn't codegen value into a register!??");
7517 Reg = FuncInfo.CreateRegs(PHIOp->getType());
7518 CopyValueToVirtualRegister(PHIOp, Reg);
7522 // Remember that this register needs to added to the machine PHI node as
7523 // the input for this MBB.
7524 SmallVector<EVT, 4> ValueVTs;
7525 const TargetLowering *TLI = TM.getTargetLowering();
7526 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
7527 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7528 EVT VT = ValueVTs[vti];
7529 unsigned NumRegisters = TLI->getNumRegisters(*DAG.getContext(), VT);
7530 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7531 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7532 Reg += NumRegisters;
7537 ConstantsOut.clear();
7540 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7543 SelectionDAGBuilder::StackProtectorDescriptor::
7544 AddSuccessorMBB(const BasicBlock *BB,
7545 MachineBasicBlock *ParentMBB,
7546 MachineBasicBlock *SuccMBB) {
7547 // If SuccBB has not been created yet, create it.
7549 MachineFunction *MF = ParentMBB->getParent();
7550 MachineFunction::iterator BBI = ParentMBB;
7551 SuccMBB = MF->CreateMachineBasicBlock(BB);
7552 MF->insert(++BBI, SuccMBB);
7554 // Add it as a successor of ParentMBB.
7555 ParentMBB->addSuccessor(SuccMBB);