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 #include "SelectionDAGBuilder.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GCMetadata.h"
28 #include "llvm/CodeGen/GCStrategy.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/StackMaps.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DebugInfo.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/IR/Intrinsics.h"
48 #include "llvm/IR/LLVMContext.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/IR/Statepoint.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Target/TargetFrameLowering.h"
57 #include "llvm/Target/TargetInstrInfo.h"
58 #include "llvm/Target/TargetIntrinsicInfo.h"
59 #include "llvm/Target/TargetLibraryInfo.h"
60 #include "llvm/Target/TargetLowering.h"
61 #include "llvm/Target/TargetOptions.h"
62 #include "llvm/Target/TargetSelectionDAGInfo.h"
63 #include "llvm/Target/TargetSubtargetInfo.h"
67 #define DEBUG_TYPE "isel"
69 /// LimitFloatPrecision - Generate low-precision inline sequences for
70 /// some float libcalls (6, 8 or 12 bits).
71 static unsigned LimitFloatPrecision;
73 static cl::opt<unsigned, true>
74 LimitFPPrecision("limit-float-precision",
75 cl::desc("Generate low-precision inline sequences "
76 "for some float libcalls"),
77 cl::location(LimitFloatPrecision),
80 // Limit the width of DAG chains. This is important in general to prevent
81 // prevent DAG-based analysis from blowing up. For example, alias analysis and
82 // load clustering may not complete in reasonable time. It is difficult to
83 // recognize and avoid this situation within each individual analysis, and
84 // future analyses are likely to have the same behavior. Limiting DAG width is
85 // the safe approach, and will be especially important with global DAGs.
87 // MaxParallelChains default is arbitrarily high to avoid affecting
88 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
89 // sequence over this should have been converted to llvm.memcpy by the
90 // frontend. It easy to induce this behavior with .ll code such as:
91 // %buffer = alloca [4096 x i8]
92 // %data = load [4096 x i8]* %argPtr
93 // store [4096 x i8] %data, [4096 x i8]* %buffer
94 static const unsigned MaxParallelChains = 64;
96 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
97 const SDValue *Parts, unsigned NumParts,
98 MVT PartVT, EVT ValueVT, const Value *V);
100 /// getCopyFromParts - Create a value that contains the specified legal parts
101 /// combined into the value they represent. If the parts combine to a type
102 /// larger then ValueVT then AssertOp can be used to specify whether the extra
103 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
104 /// (ISD::AssertSext).
105 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
106 const SDValue *Parts,
107 unsigned NumParts, MVT PartVT, EVT ValueVT,
109 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
110 if (ValueVT.isVector())
111 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
114 assert(NumParts > 0 && "No parts to assemble!");
115 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
116 SDValue Val = Parts[0];
119 // Assemble the value from multiple parts.
120 if (ValueVT.isInteger()) {
121 unsigned PartBits = PartVT.getSizeInBits();
122 unsigned ValueBits = ValueVT.getSizeInBits();
124 // Assemble the power of 2 part.
125 unsigned RoundParts = NumParts & (NumParts - 1) ?
126 1 << Log2_32(NumParts) : NumParts;
127 unsigned RoundBits = PartBits * RoundParts;
128 EVT RoundVT = RoundBits == ValueBits ?
129 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
132 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
134 if (RoundParts > 2) {
135 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
137 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
138 RoundParts / 2, PartVT, HalfVT, V);
140 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
141 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
144 if (TLI.isBigEndian())
147 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
149 if (RoundParts < NumParts) {
150 // Assemble the trailing non-power-of-2 part.
151 unsigned OddParts = NumParts - RoundParts;
152 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
153 Hi = getCopyFromParts(DAG, DL,
154 Parts + RoundParts, OddParts, PartVT, OddVT, V);
156 // Combine the round and odd parts.
158 if (TLI.isBigEndian())
160 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
161 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
162 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
163 DAG.getConstant(Lo.getValueType().getSizeInBits(),
164 TLI.getPointerTy()));
165 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
166 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
168 } else if (PartVT.isFloatingPoint()) {
169 // FP split into multiple FP parts (for ppcf128)
170 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
173 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
174 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
175 if (TLI.hasBigEndianPartOrdering(ValueVT))
177 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
179 // FP split into integer parts (soft fp)
180 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
181 !PartVT.isVector() && "Unexpected split");
182 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
183 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
187 // There is now one part, held in Val. Correct it to match ValueVT.
188 EVT PartEVT = Val.getValueType();
190 if (PartEVT == ValueVT)
193 if (PartEVT.isInteger() && ValueVT.isInteger()) {
194 if (ValueVT.bitsLT(PartEVT)) {
195 // For a truncate, see if we have any information to
196 // indicate whether the truncated bits will always be
197 // zero or sign-extension.
198 if (AssertOp != ISD::DELETED_NODE)
199 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
200 DAG.getValueType(ValueVT));
201 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
203 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
206 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
207 // FP_ROUND's are always exact here.
208 if (ValueVT.bitsLT(Val.getValueType()))
209 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
210 DAG.getTargetConstant(1, TLI.getPointerTy()));
212 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
215 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
216 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
218 llvm_unreachable("Unknown mismatch!");
221 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
222 const Twine &ErrMsg) {
223 const Instruction *I = dyn_cast_or_null<Instruction>(V);
225 return Ctx.emitError(ErrMsg);
227 const char *AsmError = ", possible invalid constraint for vector type";
228 if (const CallInst *CI = dyn_cast<CallInst>(I))
229 if (isa<InlineAsm>(CI->getCalledValue()))
230 return Ctx.emitError(I, ErrMsg + AsmError);
232 return Ctx.emitError(I, ErrMsg);
235 /// getCopyFromPartsVector - Create a value that contains the specified legal
236 /// parts combined into the value they represent. If the parts combine to a
237 /// type larger then ValueVT then AssertOp can be used to specify whether the
238 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
239 /// ValueVT (ISD::AssertSext).
240 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
241 const SDValue *Parts, unsigned NumParts,
242 MVT PartVT, EVT ValueVT, const Value *V) {
243 assert(ValueVT.isVector() && "Not a vector value");
244 assert(NumParts > 0 && "No parts to assemble!");
245 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
246 SDValue Val = Parts[0];
248 // Handle a multi-element vector.
252 unsigned NumIntermediates;
254 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
255 NumIntermediates, RegisterVT);
256 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
257 NumParts = NumRegs; // Silence a compiler warning.
258 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
259 assert(RegisterVT == Parts[0].getSimpleValueType() &&
260 "Part type doesn't match part!");
262 // Assemble the parts into intermediate operands.
263 SmallVector<SDValue, 8> Ops(NumIntermediates);
264 if (NumIntermediates == NumParts) {
265 // If the register was not expanded, truncate or copy the value,
267 for (unsigned i = 0; i != NumParts; ++i)
268 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
269 PartVT, IntermediateVT, V);
270 } else if (NumParts > 0) {
271 // If the intermediate type was expanded, build the intermediate
272 // operands from the parts.
273 assert(NumParts % NumIntermediates == 0 &&
274 "Must expand into a divisible number of parts!");
275 unsigned Factor = NumParts / NumIntermediates;
276 for (unsigned i = 0; i != NumIntermediates; ++i)
277 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
278 PartVT, IntermediateVT, V);
281 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
282 // intermediate operands.
283 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
288 // There is now one part, held in Val. Correct it to match ValueVT.
289 EVT PartEVT = Val.getValueType();
291 if (PartEVT == ValueVT)
294 if (PartEVT.isVector()) {
295 // If the element type of the source/dest vectors are the same, but the
296 // parts vector has more elements than the value vector, then we have a
297 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
299 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
300 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
301 "Cannot narrow, it would be a lossy transformation");
302 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
303 DAG.getConstant(0, TLI.getVectorIdxTy()));
306 // Vector/Vector bitcast.
307 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
308 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
310 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
311 "Cannot handle this kind of promotion");
312 // Promoted vector extract
313 bool Smaller = ValueVT.bitsLE(PartEVT);
314 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
319 // Trivial bitcast if the types are the same size and the destination
320 // vector type is legal.
321 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
322 TLI.isTypeLegal(ValueVT))
323 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
325 // Handle cases such as i8 -> <1 x i1>
326 if (ValueVT.getVectorNumElements() != 1) {
327 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
328 "non-trivial scalar-to-vector conversion");
329 return DAG.getUNDEF(ValueVT);
332 if (ValueVT.getVectorNumElements() == 1 &&
333 ValueVT.getVectorElementType() != PartEVT) {
334 bool Smaller = ValueVT.bitsLE(PartEVT);
335 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
336 DL, ValueVT.getScalarType(), Val);
339 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
342 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
343 SDValue Val, SDValue *Parts, unsigned NumParts,
344 MVT PartVT, const Value *V);
346 /// getCopyToParts - Create a series of nodes that contain the specified value
347 /// split into legal parts. If the parts contain more bits than Val, then, for
348 /// integers, ExtendKind can be used to specify how to generate the extra bits.
349 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
350 SDValue Val, SDValue *Parts, unsigned NumParts,
351 MVT PartVT, const Value *V,
352 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
353 EVT ValueVT = Val.getValueType();
355 // Handle the vector case separately.
356 if (ValueVT.isVector())
357 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
359 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
360 unsigned PartBits = PartVT.getSizeInBits();
361 unsigned OrigNumParts = NumParts;
362 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
367 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
368 EVT PartEVT = PartVT;
369 if (PartEVT == ValueVT) {
370 assert(NumParts == 1 && "No-op copy with multiple parts!");
375 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
376 // If the parts cover more bits than the value has, promote the value.
377 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
378 assert(NumParts == 1 && "Do not know what to promote to!");
379 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
381 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
382 ValueVT.isInteger() &&
383 "Unknown mismatch!");
384 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
385 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
386 if (PartVT == MVT::x86mmx)
387 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
389 } else if (PartBits == ValueVT.getSizeInBits()) {
390 // Different types of the same size.
391 assert(NumParts == 1 && PartEVT != ValueVT);
392 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
393 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
394 // If the parts cover less bits than value has, truncate the value.
395 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
396 ValueVT.isInteger() &&
397 "Unknown mismatch!");
398 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
399 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
400 if (PartVT == MVT::x86mmx)
401 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
404 // The value may have changed - recompute ValueVT.
405 ValueVT = Val.getValueType();
406 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
407 "Failed to tile the value with PartVT!");
410 if (PartEVT != ValueVT)
411 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
412 "scalar-to-vector conversion failed");
418 // Expand the value into multiple parts.
419 if (NumParts & (NumParts - 1)) {
420 // The number of parts is not a power of 2. Split off and copy the tail.
421 assert(PartVT.isInteger() && ValueVT.isInteger() &&
422 "Do not know what to expand to!");
423 unsigned RoundParts = 1 << Log2_32(NumParts);
424 unsigned RoundBits = RoundParts * PartBits;
425 unsigned OddParts = NumParts - RoundParts;
426 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
427 DAG.getIntPtrConstant(RoundBits));
428 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
430 if (TLI.isBigEndian())
431 // The odd parts were reversed by getCopyToParts - unreverse them.
432 std::reverse(Parts + RoundParts, Parts + NumParts);
434 NumParts = RoundParts;
435 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
436 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
439 // The number of parts is a power of 2. Repeatedly bisect the value using
441 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
442 EVT::getIntegerVT(*DAG.getContext(),
443 ValueVT.getSizeInBits()),
446 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
447 for (unsigned i = 0; i < NumParts; i += StepSize) {
448 unsigned ThisBits = StepSize * PartBits / 2;
449 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
450 SDValue &Part0 = Parts[i];
451 SDValue &Part1 = Parts[i+StepSize/2];
453 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
454 ThisVT, Part0, DAG.getIntPtrConstant(1));
455 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
456 ThisVT, Part0, DAG.getIntPtrConstant(0));
458 if (ThisBits == PartBits && ThisVT != PartVT) {
459 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
460 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
465 if (TLI.isBigEndian())
466 std::reverse(Parts, Parts + OrigNumParts);
470 /// getCopyToPartsVector - Create a series of nodes that contain the specified
471 /// value split into legal parts.
472 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
473 SDValue Val, SDValue *Parts, unsigned NumParts,
474 MVT PartVT, const Value *V) {
475 EVT ValueVT = Val.getValueType();
476 assert(ValueVT.isVector() && "Not a vector");
477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
480 EVT PartEVT = PartVT;
481 if (PartEVT == ValueVT) {
483 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
484 // Bitconvert vector->vector case.
485 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
486 } else if (PartVT.isVector() &&
487 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
488 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
489 EVT ElementVT = PartVT.getVectorElementType();
490 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
492 SmallVector<SDValue, 16> Ops;
493 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
494 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
495 ElementVT, Val, DAG.getConstant(i,
496 TLI.getVectorIdxTy())));
498 for (unsigned i = ValueVT.getVectorNumElements(),
499 e = PartVT.getVectorNumElements(); i != e; ++i)
500 Ops.push_back(DAG.getUNDEF(ElementVT));
502 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
504 // FIXME: Use CONCAT for 2x -> 4x.
506 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
507 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
508 } else if (PartVT.isVector() &&
509 PartEVT.getVectorElementType().bitsGE(
510 ValueVT.getVectorElementType()) &&
511 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
513 // Promoted vector extract
514 bool Smaller = PartEVT.bitsLE(ValueVT);
515 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
518 // Vector -> scalar conversion.
519 assert(ValueVT.getVectorNumElements() == 1 &&
520 "Only trivial vector-to-scalar conversions should get here!");
521 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
522 PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
524 bool Smaller = ValueVT.bitsLE(PartVT);
525 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
533 // Handle a multi-element vector.
536 unsigned NumIntermediates;
537 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
539 NumIntermediates, RegisterVT);
540 unsigned NumElements = ValueVT.getVectorNumElements();
542 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
543 NumParts = NumRegs; // Silence a compiler warning.
544 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
546 // Split the vector into intermediate operands.
547 SmallVector<SDValue, 8> Ops(NumIntermediates);
548 for (unsigned i = 0; i != NumIntermediates; ++i) {
549 if (IntermediateVT.isVector())
550 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
552 DAG.getConstant(i * (NumElements / NumIntermediates),
553 TLI.getVectorIdxTy()));
555 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
557 DAG.getConstant(i, TLI.getVectorIdxTy()));
560 // Split the intermediate operands into legal parts.
561 if (NumParts == NumIntermediates) {
562 // If the register was not expanded, promote or copy the value,
564 for (unsigned i = 0; i != NumParts; ++i)
565 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
566 } else if (NumParts > 0) {
567 // If the intermediate type was expanded, split each the value into
569 assert(NumParts % NumIntermediates == 0 &&
570 "Must expand into a divisible number of parts!");
571 unsigned Factor = NumParts / NumIntermediates;
572 for (unsigned i = 0; i != NumIntermediates; ++i)
573 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
578 /// RegsForValue - This struct represents the registers (physical or virtual)
579 /// that a particular set of values is assigned, and the type information
580 /// about the value. The most common situation is to represent one value at a
581 /// time, but struct or array values are handled element-wise as multiple
582 /// values. The splitting of aggregates is performed recursively, so that we
583 /// never have aggregate-typed registers. The values at this point do not
584 /// necessarily have legal types, so each value may require one or more
585 /// registers of some legal type.
587 struct RegsForValue {
588 /// ValueVTs - The value types of the values, which may not be legal, and
589 /// may need be promoted or synthesized from one or more registers.
591 SmallVector<EVT, 4> ValueVTs;
593 /// RegVTs - The value types of the registers. This is the same size as
594 /// ValueVTs and it records, for each value, what the type of the assigned
595 /// register or registers are. (Individual values are never synthesized
596 /// from more than one type of register.)
598 /// With virtual registers, the contents of RegVTs is redundant with TLI's
599 /// getRegisterType member function, however when with physical registers
600 /// it is necessary to have a separate record of the types.
602 SmallVector<MVT, 4> RegVTs;
604 /// Regs - This list holds the registers assigned to the values.
605 /// Each legal or promoted value requires one register, and each
606 /// expanded value requires multiple registers.
608 SmallVector<unsigned, 4> Regs;
612 RegsForValue(const SmallVector<unsigned, 4> ®s,
613 MVT regvt, EVT valuevt)
614 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
616 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
617 unsigned Reg, Type *Ty) {
618 ComputeValueVTs(tli, Ty, ValueVTs);
620 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
621 EVT ValueVT = ValueVTs[Value];
622 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
623 MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
624 for (unsigned i = 0; i != NumRegs; ++i)
625 Regs.push_back(Reg + i);
626 RegVTs.push_back(RegisterVT);
631 /// append - Add the specified values to this one.
632 void append(const RegsForValue &RHS) {
633 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
634 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
635 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
638 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
639 /// this value and returns the result as a ValueVTs value. This uses
640 /// Chain/Flag as the input and updates them for the output Chain/Flag.
641 /// If the Flag pointer is NULL, no flag is used.
642 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
644 SDValue &Chain, SDValue *Flag,
645 const Value *V = nullptr) const;
647 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
648 /// specified value into the registers specified by this object. 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.
652 getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl, SDValue &Chain,
653 SDValue *Flag, const Value *V,
654 ISD::NodeType PreferredExtendType = ISD::ANY_EXTEND) const;
656 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
657 /// operand list. This adds the code marker, matching input operand index
658 /// (if applicable), and includes the number of values added into it.
659 void AddInlineAsmOperands(unsigned Kind,
660 bool HasMatching, unsigned MatchingIdx,
662 std::vector<SDValue> &Ops) const;
666 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
667 /// this value and returns the result as a ValueVT value. This uses
668 /// Chain/Flag as the input and updates them for the output Chain/Flag.
669 /// If the Flag pointer is NULL, no flag is used.
670 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
671 FunctionLoweringInfo &FuncInfo,
673 SDValue &Chain, SDValue *Flag,
674 const Value *V) const {
675 // A Value with type {} or [0 x %t] needs no registers.
676 if (ValueVTs.empty())
679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
681 // Assemble the legal parts into the final values.
682 SmallVector<SDValue, 4> Values(ValueVTs.size());
683 SmallVector<SDValue, 8> Parts;
684 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
685 // Copy the legal parts from the registers.
686 EVT ValueVT = ValueVTs[Value];
687 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
688 MVT RegisterVT = RegVTs[Value];
690 Parts.resize(NumRegs);
691 for (unsigned i = 0; i != NumRegs; ++i) {
694 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
696 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
697 *Flag = P.getValue(2);
700 Chain = P.getValue(1);
703 // If the source register was virtual and if we know something about it,
704 // add an assert node.
705 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
706 !RegisterVT.isInteger() || RegisterVT.isVector())
709 const FunctionLoweringInfo::LiveOutInfo *LOI =
710 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
714 unsigned RegSize = RegisterVT.getSizeInBits();
715 unsigned NumSignBits = LOI->NumSignBits;
716 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
718 if (NumZeroBits == RegSize) {
719 // The current value is a zero.
720 // Explicitly express that as it would be easier for
721 // optimizations to kick in.
722 Parts[i] = DAG.getConstant(0, RegisterVT);
726 // FIXME: We capture more information than the dag can represent. For
727 // now, just use the tightest assertzext/assertsext possible.
729 EVT FromVT(MVT::Other);
730 if (NumSignBits == RegSize)
731 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
732 else if (NumZeroBits >= RegSize-1)
733 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
734 else if (NumSignBits > RegSize-8)
735 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
736 else if (NumZeroBits >= RegSize-8)
737 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
738 else if (NumSignBits > RegSize-16)
739 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
740 else if (NumZeroBits >= RegSize-16)
741 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
742 else if (NumSignBits > RegSize-32)
743 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
744 else if (NumZeroBits >= RegSize-32)
745 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
749 // Add an assertion node.
750 assert(FromVT != MVT::Other);
751 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
752 RegisterVT, P, DAG.getValueType(FromVT));
755 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
756 NumRegs, RegisterVT, ValueVT, V);
761 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
764 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
765 /// specified value into the registers specified by this object. This uses
766 /// Chain/Flag as the input and updates them for the output Chain/Flag.
767 /// If the Flag pointer is NULL, no flag is used.
768 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
769 SDValue &Chain, SDValue *Flag, const Value *V,
770 ISD::NodeType PreferredExtendType) const {
771 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
772 ISD::NodeType ExtendKind = PreferredExtendType;
774 // Get the list of the values's legal parts.
775 unsigned NumRegs = Regs.size();
776 SmallVector<SDValue, 8> Parts(NumRegs);
777 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
778 EVT ValueVT = ValueVTs[Value];
779 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
780 MVT RegisterVT = RegVTs[Value];
782 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
783 ExtendKind = ISD::ZERO_EXTEND;
785 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
786 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
790 // Copy the parts into the registers.
791 SmallVector<SDValue, 8> Chains(NumRegs);
792 for (unsigned i = 0; i != NumRegs; ++i) {
795 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
797 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
798 *Flag = Part.getValue(1);
801 Chains[i] = Part.getValue(0);
804 if (NumRegs == 1 || Flag)
805 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
806 // flagged to it. That is the CopyToReg nodes and the user are considered
807 // a single scheduling unit. If we create a TokenFactor and return it as
808 // chain, then the TokenFactor is both a predecessor (operand) of the
809 // user as well as a successor (the TF operands are flagged to the user).
810 // c1, f1 = CopyToReg
811 // c2, f2 = CopyToReg
812 // c3 = TokenFactor c1, c2
815 Chain = Chains[NumRegs-1];
817 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
820 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
821 /// operand list. This adds the code marker and includes the number of
822 /// values added into it.
823 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
824 unsigned MatchingIdx,
826 std::vector<SDValue> &Ops) const {
827 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
829 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
831 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
832 else if (!Regs.empty() &&
833 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
834 // Put the register class of the virtual registers in the flag word. That
835 // way, later passes can recompute register class constraints for inline
836 // assembly as well as normal instructions.
837 // Don't do this for tied operands that can use the regclass information
839 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
840 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
841 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
844 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
847 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
848 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
849 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
850 MVT RegisterVT = RegVTs[Value];
851 for (unsigned i = 0; i != NumRegs; ++i) {
852 assert(Reg < Regs.size() && "Mismatch in # registers expected");
853 unsigned TheReg = Regs[Reg++];
854 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
856 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
857 // If we clobbered the stack pointer, MFI should know about it.
858 assert(DAG.getMachineFunction().getFrameInfo()->
859 hasInlineAsmWithSPAdjust());
865 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
866 const TargetLibraryInfo *li) {
870 DL = DAG.getSubtarget().getDataLayout();
871 Context = DAG.getContext();
872 LPadToCallSiteMap.clear();
875 /// clear - Clear out the current SelectionDAG and the associated
876 /// state and prepare this SelectionDAGBuilder object to be used
877 /// for a new block. This doesn't clear out information about
878 /// additional blocks that are needed to complete switch lowering
879 /// or PHI node updating; that information is cleared out as it is
881 void SelectionDAGBuilder::clear() {
883 UnusedArgNodeMap.clear();
884 PendingLoads.clear();
885 PendingExports.clear();
888 SDNodeOrder = LowestSDNodeOrder;
889 StatepointLowering.clear();
892 /// clearDanglingDebugInfo - Clear the dangling debug information
893 /// map. This function is separated from the clear so that debug
894 /// information that is dangling in a basic block can be properly
895 /// resolved in a different basic block. This allows the
896 /// SelectionDAG to resolve dangling debug information attached
898 void SelectionDAGBuilder::clearDanglingDebugInfo() {
899 DanglingDebugInfoMap.clear();
902 /// getRoot - Return the current virtual root of the Selection DAG,
903 /// flushing any PendingLoad items. This must be done before emitting
904 /// a store or any other node that may need to be ordered after any
905 /// prior load instructions.
907 SDValue SelectionDAGBuilder::getRoot() {
908 if (PendingLoads.empty())
909 return DAG.getRoot();
911 if (PendingLoads.size() == 1) {
912 SDValue Root = PendingLoads[0];
914 PendingLoads.clear();
918 // Otherwise, we have to make a token factor node.
919 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
921 PendingLoads.clear();
926 /// getControlRoot - Similar to getRoot, but instead of flushing all the
927 /// PendingLoad items, flush all the PendingExports items. It is necessary
928 /// to do this before emitting a terminator instruction.
930 SDValue SelectionDAGBuilder::getControlRoot() {
931 SDValue Root = DAG.getRoot();
933 if (PendingExports.empty())
936 // Turn all of the CopyToReg chains into one factored node.
937 if (Root.getOpcode() != ISD::EntryToken) {
938 unsigned i = 0, e = PendingExports.size();
939 for (; i != e; ++i) {
940 assert(PendingExports[i].getNode()->getNumOperands() > 1);
941 if (PendingExports[i].getNode()->getOperand(0) == Root)
942 break; // Don't add the root if we already indirectly depend on it.
946 PendingExports.push_back(Root);
949 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
951 PendingExports.clear();
956 void SelectionDAGBuilder::visit(const Instruction &I) {
957 // Set up outgoing PHI node register values before emitting the terminator.
958 if (isa<TerminatorInst>(&I))
959 HandlePHINodesInSuccessorBlocks(I.getParent());
965 visit(I.getOpcode(), I);
967 if (!isa<TerminatorInst>(&I) && !HasTailCall)
968 CopyToExportRegsIfNeeded(&I);
973 void SelectionDAGBuilder::visitPHI(const PHINode &) {
974 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
977 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
978 // Note: this doesn't use InstVisitor, because it has to work with
979 // ConstantExpr's in addition to instructions.
981 default: llvm_unreachable("Unknown instruction type encountered!");
982 // Build the switch statement using the Instruction.def file.
983 #define HANDLE_INST(NUM, OPCODE, CLASS) \
984 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
985 #include "llvm/IR/Instruction.def"
989 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
990 // generate the debug data structures now that we've seen its definition.
991 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
993 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
995 const DbgValueInst *DI = DDI.getDI();
996 DebugLoc dl = DDI.getdl();
997 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
998 MDNode *Variable = DI->getVariable();
999 MDNode *Expr = DI->getExpression();
1000 uint64_t Offset = DI->getOffset();
1001 // A dbg.value for an alloca is always indirect.
1002 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
1004 if (Val.getNode()) {
1005 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, Offset, IsIndirect,
1007 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
1008 IsIndirect, Offset, dl, DbgSDNodeOrder);
1009 DAG.AddDbgValue(SDV, Val.getNode(), false);
1012 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1013 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1017 /// getValue - Return an SDValue for the given Value.
1018 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1019 // If we already have an SDValue for this value, use it. It's important
1020 // to do this first, so that we don't create a CopyFromReg if we already
1021 // have a regular SDValue.
1022 SDValue &N = NodeMap[V];
1023 if (N.getNode()) return N;
1025 // If there's a virtual register allocated and initialized for this
1027 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1028 if (It != FuncInfo.ValueMap.end()) {
1029 unsigned InReg = It->second;
1030 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(), InReg,
1032 SDValue Chain = DAG.getEntryNode();
1033 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1034 resolveDanglingDebugInfo(V, N);
1038 // Otherwise create a new SDValue and remember it.
1039 SDValue Val = getValueImpl(V);
1041 resolveDanglingDebugInfo(V, Val);
1045 /// getNonRegisterValue - Return an SDValue for the given Value, but
1046 /// don't look in FuncInfo.ValueMap for a virtual register.
1047 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1048 // If we already have an SDValue for this value, use it.
1049 SDValue &N = NodeMap[V];
1050 if (N.getNode()) return N;
1052 // Otherwise create a new SDValue and remember it.
1053 SDValue Val = getValueImpl(V);
1055 resolveDanglingDebugInfo(V, Val);
1059 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1060 /// Create an SDValue for the given value.
1061 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1062 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1064 if (const Constant *C = dyn_cast<Constant>(V)) {
1065 EVT VT = TLI.getValueType(V->getType(), true);
1067 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1068 return DAG.getConstant(*CI, VT);
1070 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1071 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1073 if (isa<ConstantPointerNull>(C)) {
1074 unsigned AS = V->getType()->getPointerAddressSpace();
1075 return DAG.getConstant(0, TLI.getPointerTy(AS));
1078 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1079 return DAG.getConstantFP(*CFP, VT);
1081 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1082 return DAG.getUNDEF(VT);
1084 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1085 visit(CE->getOpcode(), *CE);
1086 SDValue N1 = NodeMap[V];
1087 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1091 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1092 SmallVector<SDValue, 4> Constants;
1093 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1095 SDNode *Val = getValue(*OI).getNode();
1096 // If the operand is an empty aggregate, there are no values.
1098 // Add each leaf value from the operand to the Constants list
1099 // to form a flattened list of all the values.
1100 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1101 Constants.push_back(SDValue(Val, i));
1104 return DAG.getMergeValues(Constants, getCurSDLoc());
1107 if (const ConstantDataSequential *CDS =
1108 dyn_cast<ConstantDataSequential>(C)) {
1109 SmallVector<SDValue, 4> Ops;
1110 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1111 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1112 // Add each leaf value from the operand to the Constants list
1113 // to form a flattened list of all the values.
1114 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1115 Ops.push_back(SDValue(Val, i));
1118 if (isa<ArrayType>(CDS->getType()))
1119 return DAG.getMergeValues(Ops, getCurSDLoc());
1120 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1124 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1125 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1126 "Unknown struct or array constant!");
1128 SmallVector<EVT, 4> ValueVTs;
1129 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1130 unsigned NumElts = ValueVTs.size();
1132 return SDValue(); // empty struct
1133 SmallVector<SDValue, 4> Constants(NumElts);
1134 for (unsigned i = 0; i != NumElts; ++i) {
1135 EVT EltVT = ValueVTs[i];
1136 if (isa<UndefValue>(C))
1137 Constants[i] = DAG.getUNDEF(EltVT);
1138 else if (EltVT.isFloatingPoint())
1139 Constants[i] = DAG.getConstantFP(0, EltVT);
1141 Constants[i] = DAG.getConstant(0, EltVT);
1144 return DAG.getMergeValues(Constants, getCurSDLoc());
1147 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1148 return DAG.getBlockAddress(BA, VT);
1150 VectorType *VecTy = cast<VectorType>(V->getType());
1151 unsigned NumElements = VecTy->getNumElements();
1153 // Now that we know the number and type of the elements, get that number of
1154 // elements into the Ops array based on what kind of constant it is.
1155 SmallVector<SDValue, 16> Ops;
1156 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1157 for (unsigned i = 0; i != NumElements; ++i)
1158 Ops.push_back(getValue(CV->getOperand(i)));
1160 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1161 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1164 if (EltVT.isFloatingPoint())
1165 Op = DAG.getConstantFP(0, EltVT);
1167 Op = DAG.getConstant(0, EltVT);
1168 Ops.assign(NumElements, Op);
1171 // Create a BUILD_VECTOR node.
1172 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1175 // If this is a static alloca, generate it as the frameindex instead of
1177 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1178 DenseMap<const AllocaInst*, int>::iterator SI =
1179 FuncInfo.StaticAllocaMap.find(AI);
1180 if (SI != FuncInfo.StaticAllocaMap.end())
1181 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1184 // If this is an instruction which fast-isel has deferred, select it now.
1185 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1186 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1187 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1188 SDValue Chain = DAG.getEntryNode();
1189 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1192 llvm_unreachable("Can't get register for value!");
1195 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1197 SDValue Chain = getControlRoot();
1198 SmallVector<ISD::OutputArg, 8> Outs;
1199 SmallVector<SDValue, 8> OutVals;
1201 if (!FuncInfo.CanLowerReturn) {
1202 unsigned DemoteReg = FuncInfo.DemoteRegister;
1203 const Function *F = I.getParent()->getParent();
1205 // Emit a store of the return value through the virtual register.
1206 // Leave Outs empty so that LowerReturn won't try to load return
1207 // registers the usual way.
1208 SmallVector<EVT, 1> PtrValueVTs;
1209 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1212 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1213 SDValue RetOp = getValue(I.getOperand(0));
1215 SmallVector<EVT, 4> ValueVTs;
1216 SmallVector<uint64_t, 4> Offsets;
1217 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1218 unsigned NumValues = ValueVTs.size();
1220 SmallVector<SDValue, 4> Chains(NumValues);
1221 for (unsigned i = 0; i != NumValues; ++i) {
1222 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1223 RetPtr.getValueType(), RetPtr,
1224 DAG.getIntPtrConstant(Offsets[i]));
1226 DAG.getStore(Chain, getCurSDLoc(),
1227 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1228 // FIXME: better loc info would be nice.
1229 Add, MachinePointerInfo(), false, false, 0);
1232 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1233 MVT::Other, Chains);
1234 } else if (I.getNumOperands() != 0) {
1235 SmallVector<EVT, 4> ValueVTs;
1236 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1237 unsigned NumValues = ValueVTs.size();
1239 SDValue RetOp = getValue(I.getOperand(0));
1240 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1241 EVT VT = ValueVTs[j];
1243 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1245 const Function *F = I.getParent()->getParent();
1246 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1248 ExtendKind = ISD::SIGN_EXTEND;
1249 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1251 ExtendKind = ISD::ZERO_EXTEND;
1253 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1254 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
1256 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1257 MVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1258 SmallVector<SDValue, 4> Parts(NumParts);
1259 getCopyToParts(DAG, getCurSDLoc(),
1260 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1261 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1263 // 'inreg' on function refers to return value
1264 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1265 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1269 // Propagate extension type if any
1270 if (ExtendKind == ISD::SIGN_EXTEND)
1272 else if (ExtendKind == ISD::ZERO_EXTEND)
1275 for (unsigned i = 0; i < NumParts; ++i) {
1276 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1277 VT, /*isfixed=*/true, 0, 0));
1278 OutVals.push_back(Parts[i]);
1284 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1285 CallingConv::ID CallConv =
1286 DAG.getMachineFunction().getFunction()->getCallingConv();
1287 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1288 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1290 // Verify that the target's LowerReturn behaved as expected.
1291 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1292 "LowerReturn didn't return a valid chain!");
1294 // Update the DAG with the new chain value resulting from return lowering.
1298 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1299 /// created for it, emit nodes to copy the value into the virtual
1301 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1303 if (V->getType()->isEmptyTy())
1306 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1307 if (VMI != FuncInfo.ValueMap.end()) {
1308 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1309 CopyValueToVirtualRegister(V, VMI->second);
1313 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1314 /// the current basic block, add it to ValueMap now so that we'll get a
1316 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1317 // No need to export constants.
1318 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1320 // Already exported?
1321 if (FuncInfo.isExportedInst(V)) return;
1323 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1324 CopyValueToVirtualRegister(V, Reg);
1327 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1328 const BasicBlock *FromBB) {
1329 // The operands of the setcc have to be in this block. We don't know
1330 // how to export them from some other block.
1331 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1332 // Can export from current BB.
1333 if (VI->getParent() == FromBB)
1336 // Is already exported, noop.
1337 return FuncInfo.isExportedInst(V);
1340 // If this is an argument, we can export it if the BB is the entry block or
1341 // if it is already exported.
1342 if (isa<Argument>(V)) {
1343 if (FromBB == &FromBB->getParent()->getEntryBlock())
1346 // Otherwise, can only export this if it is already exported.
1347 return FuncInfo.isExportedInst(V);
1350 // Otherwise, constants can always be exported.
1354 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1355 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1356 const MachineBasicBlock *Dst) const {
1357 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1360 const BasicBlock *SrcBB = Src->getBasicBlock();
1361 const BasicBlock *DstBB = Dst->getBasicBlock();
1362 return BPI->getEdgeWeight(SrcBB, DstBB);
1365 void SelectionDAGBuilder::
1366 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1367 uint32_t Weight /* = 0 */) {
1369 Weight = getEdgeWeight(Src, Dst);
1370 Src->addSuccessor(Dst, Weight);
1374 static bool InBlock(const Value *V, const BasicBlock *BB) {
1375 if (const Instruction *I = dyn_cast<Instruction>(V))
1376 return I->getParent() == BB;
1380 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1381 /// This function emits a branch and is used at the leaves of an OR or an
1382 /// AND operator tree.
1385 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1386 MachineBasicBlock *TBB,
1387 MachineBasicBlock *FBB,
1388 MachineBasicBlock *CurBB,
1389 MachineBasicBlock *SwitchBB,
1392 const BasicBlock *BB = CurBB->getBasicBlock();
1394 // If the leaf of the tree is a comparison, merge the condition into
1396 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1397 // The operands of the cmp have to be in this block. We don't know
1398 // how to export them from some other block. If this is the first block
1399 // of the sequence, no exporting is needed.
1400 if (CurBB == SwitchBB ||
1401 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1402 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1403 ISD::CondCode Condition;
1404 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1405 Condition = getICmpCondCode(IC->getPredicate());
1406 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1407 Condition = getFCmpCondCode(FC->getPredicate());
1408 if (TM.Options.NoNaNsFPMath)
1409 Condition = getFCmpCodeWithoutNaN(Condition);
1411 Condition = ISD::SETEQ; // silence warning.
1412 llvm_unreachable("Unknown compare instruction");
1415 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1416 TBB, FBB, CurBB, TWeight, FWeight);
1417 SwitchCases.push_back(CB);
1422 // Create a CaseBlock record representing this branch.
1423 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1424 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
1425 SwitchCases.push_back(CB);
1428 /// Scale down both weights to fit into uint32_t.
1429 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1430 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1431 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1432 NewTrue = NewTrue / Scale;
1433 NewFalse = NewFalse / Scale;
1436 /// FindMergedConditions - If Cond is an expression like
1437 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1438 MachineBasicBlock *TBB,
1439 MachineBasicBlock *FBB,
1440 MachineBasicBlock *CurBB,
1441 MachineBasicBlock *SwitchBB,
1442 unsigned Opc, uint32_t TWeight,
1444 // If this node is not part of the or/and tree, emit it as a branch.
1445 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1446 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1447 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1448 BOp->getParent() != CurBB->getBasicBlock() ||
1449 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1450 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1451 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1456 // Create TmpBB after CurBB.
1457 MachineFunction::iterator BBI = CurBB;
1458 MachineFunction &MF = DAG.getMachineFunction();
1459 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1460 CurBB->getParent()->insert(++BBI, TmpBB);
1462 if (Opc == Instruction::Or) {
1463 // Codegen X | Y as:
1472 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1473 // The requirement is that
1474 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1475 // = TrueProb for orignal BB.
1476 // Assuming the orignal weights are A and B, one choice is to set BB1's
1477 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1479 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1480 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1481 // TmpBB, but the math is more complicated.
1483 uint64_t NewTrueWeight = TWeight;
1484 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1485 ScaleWeights(NewTrueWeight, NewFalseWeight);
1486 // Emit the LHS condition.
1487 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1488 NewTrueWeight, NewFalseWeight);
1490 NewTrueWeight = TWeight;
1491 NewFalseWeight = 2 * (uint64_t)FWeight;
1492 ScaleWeights(NewTrueWeight, NewFalseWeight);
1493 // Emit the RHS condition into TmpBB.
1494 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1495 NewTrueWeight, NewFalseWeight);
1497 assert(Opc == Instruction::And && "Unknown merge op!");
1498 // Codegen X & Y as:
1506 // This requires creation of TmpBB after CurBB.
1508 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1509 // The requirement is that
1510 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1511 // = FalseProb for orignal BB.
1512 // Assuming the orignal weights are A and B, one choice is to set BB1's
1513 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1515 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1517 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1518 uint64_t NewFalseWeight = FWeight;
1519 ScaleWeights(NewTrueWeight, NewFalseWeight);
1520 // Emit the LHS condition.
1521 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1522 NewTrueWeight, NewFalseWeight);
1524 NewTrueWeight = 2 * (uint64_t)TWeight;
1525 NewFalseWeight = FWeight;
1526 ScaleWeights(NewTrueWeight, NewFalseWeight);
1527 // Emit the RHS condition into TmpBB.
1528 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1529 NewTrueWeight, NewFalseWeight);
1533 /// If the set of cases should be emitted as a series of branches, return true.
1534 /// If we should emit this as a bunch of and/or'd together conditions, return
1537 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1538 if (Cases.size() != 2) return true;
1540 // If this is two comparisons of the same values or'd or and'd together, they
1541 // will get folded into a single comparison, so don't emit two blocks.
1542 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1543 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1544 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1545 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1549 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1550 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1551 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1552 Cases[0].CC == Cases[1].CC &&
1553 isa<Constant>(Cases[0].CmpRHS) &&
1554 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1555 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1557 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1564 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1565 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1567 // Update machine-CFG edges.
1568 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1570 // Figure out which block is immediately after the current one.
1571 MachineBasicBlock *NextBlock = nullptr;
1572 MachineFunction::iterator BBI = BrMBB;
1573 if (++BBI != FuncInfo.MF->end())
1576 if (I.isUnconditional()) {
1577 // Update machine-CFG edges.
1578 BrMBB->addSuccessor(Succ0MBB);
1580 // If this is not a fall-through branch or optimizations are switched off,
1582 if (Succ0MBB != NextBlock || TM.getOptLevel() == CodeGenOpt::None)
1583 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1584 MVT::Other, getControlRoot(),
1585 DAG.getBasicBlock(Succ0MBB)));
1590 // If this condition is one of the special cases we handle, do special stuff
1592 const Value *CondVal = I.getCondition();
1593 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1595 // If this is a series of conditions that are or'd or and'd together, emit
1596 // this as a sequence of branches instead of setcc's with and/or operations.
1597 // As long as jumps are not expensive, this should improve performance.
1598 // For example, instead of something like:
1611 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1612 if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
1613 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1614 BOp->getOpcode() == Instruction::Or)) {
1615 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1616 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1617 getEdgeWeight(BrMBB, Succ1MBB));
1618 // If the compares in later blocks need to use values not currently
1619 // exported from this block, export them now. This block should always
1620 // be the first entry.
1621 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1623 // Allow some cases to be rejected.
1624 if (ShouldEmitAsBranches(SwitchCases)) {
1625 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1626 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1627 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1630 // Emit the branch for this block.
1631 visitSwitchCase(SwitchCases[0], BrMBB);
1632 SwitchCases.erase(SwitchCases.begin());
1636 // Okay, we decided not to do this, remove any inserted MBB's and clear
1638 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1639 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1641 SwitchCases.clear();
1645 // Create a CaseBlock record representing this branch.
1646 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1647 nullptr, Succ0MBB, Succ1MBB, BrMBB);
1649 // Use visitSwitchCase to actually insert the fast branch sequence for this
1651 visitSwitchCase(CB, BrMBB);
1654 /// visitSwitchCase - Emits the necessary code to represent a single node in
1655 /// the binary search tree resulting from lowering a switch instruction.
1656 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1657 MachineBasicBlock *SwitchBB) {
1659 SDValue CondLHS = getValue(CB.CmpLHS);
1660 SDLoc dl = getCurSDLoc();
1662 // Build the setcc now.
1664 // Fold "(X == true)" to X and "(X == false)" to !X to
1665 // handle common cases produced by branch lowering.
1666 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1667 CB.CC == ISD::SETEQ)
1669 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1670 CB.CC == ISD::SETEQ) {
1671 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1672 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1674 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1676 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1678 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1679 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1681 SDValue CmpOp = getValue(CB.CmpMHS);
1682 EVT VT = CmpOp.getValueType();
1684 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1685 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1688 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1689 VT, CmpOp, DAG.getConstant(Low, VT));
1690 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1691 DAG.getConstant(High-Low, VT), ISD::SETULE);
1695 // Update successor info
1696 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1697 // TrueBB and FalseBB are always different unless the incoming IR is
1698 // degenerate. This only happens when running llc on weird IR.
1699 if (CB.TrueBB != CB.FalseBB)
1700 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1702 // Set NextBlock to be the MBB immediately after the current one, if any.
1703 // This is used to avoid emitting unnecessary branches to the next block.
1704 MachineBasicBlock *NextBlock = nullptr;
1705 MachineFunction::iterator BBI = SwitchBB;
1706 if (++BBI != FuncInfo.MF->end())
1709 // If the lhs block is the next block, invert the condition so that we can
1710 // fall through to the lhs instead of the rhs block.
1711 if (CB.TrueBB == NextBlock) {
1712 std::swap(CB.TrueBB, CB.FalseBB);
1713 SDValue True = DAG.getConstant(1, Cond.getValueType());
1714 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1717 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1718 MVT::Other, getControlRoot(), Cond,
1719 DAG.getBasicBlock(CB.TrueBB));
1721 // Insert the false branch. Do this even if it's a fall through branch,
1722 // this makes it easier to do DAG optimizations which require inverting
1723 // the branch condition.
1724 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1725 DAG.getBasicBlock(CB.FalseBB));
1727 DAG.setRoot(BrCond);
1730 /// visitJumpTable - Emit JumpTable node in the current MBB
1731 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1732 // Emit the code for the jump table
1733 assert(JT.Reg != -1U && "Should lower JT Header first!");
1734 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
1735 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1737 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1738 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1739 MVT::Other, Index.getValue(1),
1741 DAG.setRoot(BrJumpTable);
1744 /// visitJumpTableHeader - This function emits necessary code to produce index
1745 /// in the JumpTable from switch case.
1746 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1747 JumpTableHeader &JTH,
1748 MachineBasicBlock *SwitchBB) {
1749 // Subtract the lowest switch case value from the value being switched on and
1750 // conditional branch to default mbb if the result is greater than the
1751 // difference between smallest and largest cases.
1752 SDValue SwitchOp = getValue(JTH.SValue);
1753 EVT VT = SwitchOp.getValueType();
1754 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1755 DAG.getConstant(JTH.First, VT));
1757 // The SDNode we just created, which holds the value being switched on minus
1758 // the smallest case value, needs to be copied to a virtual register so it
1759 // can be used as an index into the jump table in a subsequent basic block.
1760 // This value may be smaller or larger than the target's pointer type, and
1761 // therefore require extension or truncating.
1762 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1763 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI.getPointerTy());
1765 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1766 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1767 JumpTableReg, SwitchOp);
1768 JT.Reg = JumpTableReg;
1770 // Emit the range check for the jump table, and branch to the default block
1771 // for the switch statement if the value being switched on exceeds the largest
1772 // case in the switch.
1774 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1775 Sub.getValueType()),
1776 Sub, DAG.getConstant(JTH.Last - JTH.First, VT), ISD::SETUGT);
1778 // Set NextBlock to be the MBB immediately after the current one, if any.
1779 // This is used to avoid emitting unnecessary branches to the next block.
1780 MachineBasicBlock *NextBlock = nullptr;
1781 MachineFunction::iterator BBI = SwitchBB;
1783 if (++BBI != FuncInfo.MF->end())
1786 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1787 MVT::Other, CopyTo, CMP,
1788 DAG.getBasicBlock(JT.Default));
1790 if (JT.MBB != NextBlock)
1791 BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
1792 DAG.getBasicBlock(JT.MBB));
1794 DAG.setRoot(BrCond);
1797 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1798 /// tail spliced into a stack protector check success bb.
1800 /// For a high level explanation of how this fits into the stack protector
1801 /// generation see the comment on the declaration of class
1802 /// StackProtectorDescriptor.
1803 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1804 MachineBasicBlock *ParentBB) {
1806 // First create the loads to the guard/stack slot for the comparison.
1807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1808 EVT PtrTy = TLI.getPointerTy();
1810 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1811 int FI = MFI->getStackProtectorIndex();
1813 const Value *IRGuard = SPD.getGuard();
1814 SDValue GuardPtr = getValue(IRGuard);
1815 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1818 TLI.getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
1822 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1823 // guard value from the virtual register holding the value. Otherwise, emit a
1824 // volatile load to retrieve the stack guard value.
1825 unsigned GuardReg = SPD.getGuardReg();
1827 if (GuardReg && TLI.useLoadStackGuardNode())
1828 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), GuardReg,
1831 Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1832 GuardPtr, MachinePointerInfo(IRGuard, 0),
1833 true, false, false, Align);
1835 SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
1837 MachinePointerInfo::getFixedStack(FI),
1838 true, false, false, Align);
1840 // Perform the comparison via a subtract/getsetcc.
1841 EVT VT = Guard.getValueType();
1842 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
1845 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1846 Sub.getValueType()),
1847 Sub, DAG.getConstant(0, VT), ISD::SETNE);
1849 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1850 // branch to failure MBB.
1851 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1852 MVT::Other, StackSlot.getOperand(0),
1853 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1854 // Otherwise branch to success MBB.
1855 SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
1857 DAG.getBasicBlock(SPD.getSuccessMBB()));
1862 /// Codegen the failure basic block for a stack protector check.
1864 /// A failure stack protector machine basic block consists simply of a call to
1865 /// __stack_chk_fail().
1867 /// For a high level explanation of how this fits into the stack protector
1868 /// generation see the comment on the declaration of class
1869 /// StackProtectorDescriptor.
1871 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1872 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1874 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1875 nullptr, 0, false, getCurSDLoc(), false, false).second;
1879 /// visitBitTestHeader - This function emits necessary code to produce value
1880 /// suitable for "bit tests"
1881 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1882 MachineBasicBlock *SwitchBB) {
1883 // Subtract the minimum value
1884 SDValue SwitchOp = getValue(B.SValue);
1885 EVT VT = SwitchOp.getValueType();
1886 SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
1887 DAG.getConstant(B.First, VT));
1890 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1892 DAG.getSetCC(getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(),
1893 Sub.getValueType()),
1894 Sub, DAG.getConstant(B.Range, VT), ISD::SETUGT);
1896 // Determine the type of the test operands.
1897 bool UsePtrType = false;
1898 if (!TLI.isTypeLegal(VT))
1901 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1902 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1903 // Switch table case range are encoded into series of masks.
1904 // Just use pointer type, it's guaranteed to fit.
1910 VT = TLI.getPointerTy();
1911 Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
1914 B.RegVT = VT.getSimpleVT();
1915 B.Reg = FuncInfo.CreateReg(B.RegVT);
1916 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
1919 // Set NextBlock to be the MBB immediately after the current one, if any.
1920 // This is used to avoid emitting unnecessary branches to the next block.
1921 MachineBasicBlock *NextBlock = nullptr;
1922 MachineFunction::iterator BBI = SwitchBB;
1923 if (++BBI != FuncInfo.MF->end())
1926 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1928 addSuccessorWithWeight(SwitchBB, B.Default);
1929 addSuccessorWithWeight(SwitchBB, MBB);
1931 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1932 MVT::Other, CopyTo, RangeCmp,
1933 DAG.getBasicBlock(B.Default));
1935 if (MBB != NextBlock)
1936 BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
1937 DAG.getBasicBlock(MBB));
1939 DAG.setRoot(BrRange);
1942 /// visitBitTestCase - this function produces one "bit test"
1943 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1944 MachineBasicBlock* NextMBB,
1945 uint32_t BranchWeightToNext,
1948 MachineBasicBlock *SwitchBB) {
1950 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1953 unsigned PopCount = CountPopulation_64(B.Mask);
1954 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1955 if (PopCount == 1) {
1956 // Testing for a single bit; just compare the shift count with what it
1957 // would need to be to shift a 1 bit in that position.
1959 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1960 DAG.getConstant(countTrailingZeros(B.Mask), VT), ISD::SETEQ);
1961 } else if (PopCount == BB.Range) {
1962 // There is only one zero bit in the range, test for it directly.
1964 getCurSDLoc(), TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1965 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT), ISD::SETNE);
1967 // Make desired shift
1968 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
1969 DAG.getConstant(1, VT), ShiftOp);
1971 // Emit bit tests and jumps
1972 SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
1973 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1974 Cmp = DAG.getSetCC(getCurSDLoc(),
1975 TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1976 DAG.getConstant(0, VT), ISD::SETNE);
1979 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1980 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1981 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1982 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1984 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
1985 MVT::Other, getControlRoot(),
1986 Cmp, DAG.getBasicBlock(B.TargetBB));
1988 // Set NextBlock to be the MBB immediately after the current one, if any.
1989 // This is used to avoid emitting unnecessary branches to the next block.
1990 MachineBasicBlock *NextBlock = nullptr;
1991 MachineFunction::iterator BBI = SwitchBB;
1992 if (++BBI != FuncInfo.MF->end())
1995 if (NextMBB != NextBlock)
1996 BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
1997 DAG.getBasicBlock(NextMBB));
2002 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2003 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2005 // Retrieve successors.
2006 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2007 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
2009 const Value *Callee(I.getCalledValue());
2010 const Function *Fn = dyn_cast<Function>(Callee);
2011 if (isa<InlineAsm>(Callee))
2013 else if (Fn && Fn->isIntrinsic()) {
2014 switch (Fn->getIntrinsicID()) {
2016 llvm_unreachable("Cannot invoke this intrinsic");
2017 case Intrinsic::donothing:
2018 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2020 case Intrinsic::experimental_patchpoint_void:
2021 case Intrinsic::experimental_patchpoint_i64:
2022 visitPatchpoint(&I, LandingPad);
2026 LowerCallTo(&I, getValue(Callee), false, LandingPad);
2028 // If the value of the invoke is used outside of its defining block, make it
2029 // available as a virtual register.
2030 CopyToExportRegsIfNeeded(&I);
2032 // Update successor info
2033 addSuccessorWithWeight(InvokeMBB, Return);
2034 addSuccessorWithWeight(InvokeMBB, LandingPad);
2036 // Drop into normal successor.
2037 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2038 MVT::Other, getControlRoot(),
2039 DAG.getBasicBlock(Return)));
2042 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2043 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2046 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2047 assert(FuncInfo.MBB->isLandingPad() &&
2048 "Call to landingpad not in landing pad!");
2050 MachineBasicBlock *MBB = FuncInfo.MBB;
2051 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2052 AddLandingPadInfo(LP, MMI, MBB);
2054 // If there aren't registers to copy the values into (e.g., during SjLj
2055 // exceptions), then don't bother to create these DAG nodes.
2056 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2057 if (TLI.getExceptionPointerRegister() == 0 &&
2058 TLI.getExceptionSelectorRegister() == 0)
2061 SmallVector<EVT, 2> ValueVTs;
2062 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
2063 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2065 // Get the two live-in registers as SDValues. The physregs have already been
2066 // copied into virtual registers.
2068 Ops[0] = DAG.getZExtOrTrunc(
2069 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2070 FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2071 getCurSDLoc(), ValueVTs[0]);
2072 Ops[1] = DAG.getZExtOrTrunc(
2073 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
2074 FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
2075 getCurSDLoc(), ValueVTs[1]);
2078 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2079 DAG.getVTList(ValueVTs), Ops);
2083 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
2084 /// small case ranges).
2085 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
2086 CaseRecVector& WorkList,
2088 MachineBasicBlock *Default,
2089 MachineBasicBlock *SwitchBB) {
2090 // Size is the number of Cases represented by this range.
2091 size_t Size = CR.Range.second - CR.Range.first;
2095 // Get the MachineFunction which holds the current MBB. This is used when
2096 // inserting any additional MBBs necessary to represent the switch.
2097 MachineFunction *CurMF = FuncInfo.MF;
2099 // Figure out which block is immediately after the current one.
2100 MachineBasicBlock *NextBlock = nullptr;
2101 MachineFunction::iterator BBI = CR.CaseBB;
2103 if (++BBI != FuncInfo.MF->end())
2106 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2107 // If any two of the cases has the same destination, and if one value
2108 // is the same as the other, but has one bit unset that the other has set,
2109 // use bit manipulation to do two compares at once. For example:
2110 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2111 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
2112 // TODO: Handle cases where CR.CaseBB != SwitchBB.
2113 if (Size == 2 && CR.CaseBB == SwitchBB) {
2114 Case &Small = *CR.Range.first;
2115 Case &Big = *(CR.Range.second-1);
2117 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
2118 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
2119 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
2121 // Check that there is only one bit different.
2122 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
2123 (SmallValue | BigValue) == BigValue) {
2124 // Isolate the common bit.
2125 APInt CommonBit = BigValue & ~SmallValue;
2126 assert((SmallValue | CommonBit) == BigValue &&
2127 CommonBit.countPopulation() == 1 && "Not a common bit?");
2129 SDValue CondLHS = getValue(SV);
2130 EVT VT = CondLHS.getValueType();
2131 SDLoc DL = getCurSDLoc();
2133 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
2134 DAG.getConstant(CommonBit, VT));
2135 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
2136 Or, DAG.getConstant(BigValue, VT),
2139 // Update successor info.
2140 // Both Small and Big will jump to Small.BB, so we sum up the weights.
2141 addSuccessorWithWeight(SwitchBB, Small.BB,
2142 Small.ExtraWeight + Big.ExtraWeight);
2143 addSuccessorWithWeight(SwitchBB, Default,
2144 // The default destination is the first successor in IR.
2145 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
2147 // Insert the true branch.
2148 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
2149 getControlRoot(), Cond,
2150 DAG.getBasicBlock(Small.BB));
2152 // Insert the false branch.
2153 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2154 DAG.getBasicBlock(Default));
2156 DAG.setRoot(BrCond);
2162 // Order cases by weight so the most likely case will be checked first.
2163 uint32_t UnhandledWeights = 0;
2165 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
2166 uint32_t IWeight = I->ExtraWeight;
2167 UnhandledWeights += IWeight;
2168 for (CaseItr J = CR.Range.first; J < I; ++J) {
2169 uint32_t JWeight = J->ExtraWeight;
2170 if (IWeight > JWeight)
2175 // Rearrange the case blocks so that the last one falls through if possible.
2176 Case &BackCase = *(CR.Range.second-1);
2178 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
2179 // The last case block won't fall through into 'NextBlock' if we emit the
2180 // branches in this order. See if rearranging a case value would help.
2181 // We start at the bottom as it's the case with the least weight.
2182 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
2183 if (I->BB == NextBlock) {
2184 std::swap(*I, BackCase);
2189 // Create a CaseBlock record representing a conditional branch to
2190 // the Case's target mbb if the value being switched on SV is equal
2192 MachineBasicBlock *CurBlock = CR.CaseBB;
2193 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2194 MachineBasicBlock *FallThrough;
2196 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2197 CurMF->insert(BBI, FallThrough);
2199 // Put SV in a virtual register to make it available from the new blocks.
2200 ExportFromCurrentBlock(SV);
2202 // If the last case doesn't match, go to the default block.
2203 FallThrough = Default;
2206 const Value *RHS, *LHS, *MHS;
2208 if (I->High == I->Low) {
2209 // This is just small small case range :) containing exactly 1 case
2211 LHS = SV; RHS = I->High; MHS = nullptr;
2214 LHS = I->Low; MHS = SV; RHS = I->High;
2217 // The false weight should be sum of all un-handled cases.
2218 UnhandledWeights -= I->ExtraWeight;
2219 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2221 /* trueweight */ I->ExtraWeight,
2222 /* falseweight */ UnhandledWeights);
2224 // If emitting the first comparison, just call visitSwitchCase to emit the
2225 // code into the current block. Otherwise, push the CaseBlock onto the
2226 // vector to be later processed by SDISel, and insert the node's MBB
2227 // before the next MBB.
2228 if (CurBlock == SwitchBB)
2229 visitSwitchCase(CB, SwitchBB);
2231 SwitchCases.push_back(CB);
2233 CurBlock = FallThrough;
2239 static inline bool areJTsAllowed(const TargetLowering &TLI) {
2240 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2241 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
2244 static APInt ComputeRange(const APInt &First, const APInt &Last) {
2245 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
2246 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
2247 return (LastExt - FirstExt + 1ULL);
2250 /// handleJTSwitchCase - Emit jumptable for current switch case range
2251 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2252 CaseRecVector &WorkList,
2254 MachineBasicBlock *Default,
2255 MachineBasicBlock *SwitchBB) {
2256 Case& FrontCase = *CR.Range.first;
2257 Case& BackCase = *(CR.Range.second-1);
2259 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2260 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2262 APInt TSize(First.getBitWidth(), 0);
2263 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
2266 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2267 if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
2270 APInt Range = ComputeRange(First, Last);
2271 // The density is TSize / Range. Require at least 40%.
2272 // It should not be possible for IntTSize to saturate for sane code, but make
2273 // sure we handle Range saturation correctly.
2274 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2275 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2276 if (IntTSize * 10 < IntRange * 4)
2279 DEBUG(dbgs() << "Lowering jump table\n"
2280 << "First entry: " << First << ". Last entry: " << Last << '\n'
2281 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
2283 // Get the MachineFunction which holds the current MBB. This is used when
2284 // inserting any additional MBBs necessary to represent the switch.
2285 MachineFunction *CurMF = FuncInfo.MF;
2287 // Figure out which block is immediately after the current one.
2288 MachineFunction::iterator BBI = CR.CaseBB;
2291 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2293 // Create a new basic block to hold the code for loading the address
2294 // of the jump table, and jumping to it. Update successor information;
2295 // we will either branch to the default case for the switch, or the jump
2297 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2298 CurMF->insert(BBI, JumpTableBB);
2300 addSuccessorWithWeight(CR.CaseBB, Default);
2301 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
2303 // Build a vector of destination BBs, corresponding to each target
2304 // of the jump table. If the value of the jump table slot corresponds to
2305 // a case statement, push the case's BB onto the vector, otherwise, push
2307 std::vector<MachineBasicBlock*> DestBBs;
2309 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2310 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2311 const APInt &High = cast<ConstantInt>(I->High)->getValue();
2313 if (Low.sle(TEI) && TEI.sle(High)) {
2314 DestBBs.push_back(I->BB);
2318 DestBBs.push_back(Default);
2322 // Calculate weight for each unique destination in CR.
2323 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2325 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2326 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2327 DestWeights.find(I->BB);
2328 if (Itr != DestWeights.end())
2329 Itr->second += I->ExtraWeight;
2331 DestWeights[I->BB] = I->ExtraWeight;
2334 // Update successor info. Add one edge to each unique successor.
2335 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2336 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2337 E = DestBBs.end(); I != E; ++I) {
2338 if (!SuccsHandled[(*I)->getNumber()]) {
2339 SuccsHandled[(*I)->getNumber()] = true;
2340 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2341 DestWeights.find(*I);
2342 addSuccessorWithWeight(JumpTableBB, *I,
2343 Itr != DestWeights.end() ? Itr->second : 0);
2347 // Create a jump table index for this jump table.
2348 unsigned JTEncoding = TLI.getJumpTableEncoding();
2349 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2350 ->createJumpTableIndex(DestBBs);
2352 // Set the jump table information so that we can codegen it as a second
2353 // MachineBasicBlock
2354 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2355 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2356 if (CR.CaseBB == SwitchBB)
2357 visitJumpTableHeader(JT, JTH, SwitchBB);
2359 JTCases.push_back(JumpTableBlock(JTH, JT));
2363 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2365 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2366 CaseRecVector& WorkList,
2368 MachineBasicBlock* SwitchBB) {
2369 // Get the MachineFunction which holds the current MBB. This is used when
2370 // inserting any additional MBBs necessary to represent the switch.
2371 MachineFunction *CurMF = FuncInfo.MF;
2373 // Figure out which block is immediately after the current one.
2374 MachineFunction::iterator BBI = CR.CaseBB;
2377 Case& FrontCase = *CR.Range.first;
2378 Case& BackCase = *(CR.Range.second-1);
2379 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2381 // Size is the number of Cases represented by this range.
2382 unsigned Size = CR.Range.second - CR.Range.first;
2384 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2385 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2387 CaseItr Pivot = CR.Range.first + Size/2;
2389 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2390 // (heuristically) allow us to emit JumpTable's later.
2391 APInt TSize(First.getBitWidth(), 0);
2392 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2396 APInt LSize = FrontCase.size();
2397 APInt RSize = TSize-LSize;
2398 DEBUG(dbgs() << "Selecting best pivot: \n"
2399 << "First: " << First << ", Last: " << Last <<'\n'
2400 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2401 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2403 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2404 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2405 APInt Range = ComputeRange(LEnd, RBegin);
2406 assert((Range - 2ULL).isNonNegative() &&
2407 "Invalid case distance");
2408 // Use volatile double here to avoid excess precision issues on some hosts,
2409 // e.g. that use 80-bit X87 registers.
2410 volatile double LDensity =
2411 (double)LSize.roundToDouble() /
2412 (LEnd - First + 1ULL).roundToDouble();
2413 volatile double RDensity =
2414 (double)RSize.roundToDouble() /
2415 (Last - RBegin + 1ULL).roundToDouble();
2416 volatile double Metric = Range.logBase2()*(LDensity+RDensity);
2417 // Should always split in some non-trivial place
2418 DEBUG(dbgs() <<"=>Step\n"
2419 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2420 << "LDensity: " << LDensity
2421 << ", RDensity: " << RDensity << '\n'
2422 << "Metric: " << Metric << '\n');
2423 if (FMetric < Metric) {
2426 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2434 if (areJTsAllowed(TLI)) {
2435 // If our case is dense we *really* should handle it earlier!
2436 assert((FMetric > 0) && "Should handle dense range earlier!");
2438 Pivot = CR.Range.first + Size/2;
2441 CaseRange LHSR(CR.Range.first, Pivot);
2442 CaseRange RHSR(Pivot, CR.Range.second);
2443 const Constant *C = Pivot->Low;
2444 MachineBasicBlock *FalseBB = nullptr, *TrueBB = nullptr;
2446 // We know that we branch to the LHS if the Value being switched on is
2447 // less than the Pivot value, C. We use this to optimize our binary
2448 // tree a bit, by recognizing that if SV is greater than or equal to the
2449 // LHS's Case Value, and that Case Value is exactly one less than the
2450 // Pivot's Value, then we can branch directly to the LHS's Target,
2451 // rather than creating a leaf node for it.
2452 if ((LHSR.second - LHSR.first) == 1 &&
2453 LHSR.first->High == CR.GE &&
2454 cast<ConstantInt>(C)->getValue() ==
2455 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2456 TrueBB = LHSR.first->BB;
2458 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2459 CurMF->insert(BBI, TrueBB);
2460 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2462 // Put SV in a virtual register to make it available from the new blocks.
2463 ExportFromCurrentBlock(SV);
2466 // Similar to the optimization above, if the Value being switched on is
2467 // known to be less than the Constant CR.LT, and the current Case Value
2468 // is CR.LT - 1, then we can branch directly to the target block for
2469 // the current Case Value, rather than emitting a RHS leaf node for it.
2470 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2471 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2472 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2473 FalseBB = RHSR.first->BB;
2475 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2476 CurMF->insert(BBI, FalseBB);
2477 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2479 // Put SV in a virtual register to make it available from the new blocks.
2480 ExportFromCurrentBlock(SV);
2483 // Create a CaseBlock record representing a conditional branch to
2484 // the LHS node if the value being switched on SV is less than C.
2485 // Otherwise, branch to LHS.
2486 CaseBlock CB(ISD::SETLT, SV, C, nullptr, TrueBB, FalseBB, CR.CaseBB);
2488 if (CR.CaseBB == SwitchBB)
2489 visitSwitchCase(CB, SwitchBB);
2491 SwitchCases.push_back(CB);
2496 /// handleBitTestsSwitchCase - if current case range has few destination and
2497 /// range span less, than machine word bitwidth, encode case range into series
2498 /// of masks and emit bit tests with these masks.
2499 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2500 CaseRecVector& WorkList,
2502 MachineBasicBlock* Default,
2503 MachineBasicBlock* SwitchBB) {
2504 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2505 EVT PTy = TLI.getPointerTy();
2506 unsigned IntPtrBits = PTy.getSizeInBits();
2508 Case& FrontCase = *CR.Range.first;
2509 Case& BackCase = *(CR.Range.second-1);
2511 // Get the MachineFunction which holds the current MBB. This is used when
2512 // inserting any additional MBBs necessary to represent the switch.
2513 MachineFunction *CurMF = FuncInfo.MF;
2515 // If target does not have legal shift left, do not emit bit tests at all.
2516 if (!TLI.isOperationLegal(ISD::SHL, PTy))
2520 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2521 // Single case counts one, case range - two.
2522 numCmps += (I->Low == I->High ? 1 : 2);
2525 // Count unique destinations
2526 SmallSet<MachineBasicBlock*, 4> Dests;
2527 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2528 Dests.insert(I->BB);
2529 if (Dests.size() > 3)
2530 // Don't bother the code below, if there are too much unique destinations
2533 DEBUG(dbgs() << "Total number of unique destinations: "
2534 << Dests.size() << '\n'
2535 << "Total number of comparisons: " << numCmps << '\n');
2537 // Compute span of values.
2538 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2539 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2540 APInt cmpRange = maxValue - minValue;
2542 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2543 << "Low bound: " << minValue << '\n'
2544 << "High bound: " << maxValue << '\n');
2546 if (cmpRange.uge(IntPtrBits) ||
2547 (!(Dests.size() == 1 && numCmps >= 3) &&
2548 !(Dests.size() == 2 && numCmps >= 5) &&
2549 !(Dests.size() >= 3 && numCmps >= 6)))
2552 DEBUG(dbgs() << "Emitting bit tests\n");
2553 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2555 // Optimize the case where all the case values fit in a
2556 // word without having to subtract minValue. In this case,
2557 // we can optimize away the subtraction.
2558 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2559 cmpRange = maxValue;
2561 lowBound = minValue;
2564 CaseBitsVector CasesBits;
2565 unsigned i, count = 0;
2567 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2568 MachineBasicBlock* Dest = I->BB;
2569 for (i = 0; i < count; ++i)
2570 if (Dest == CasesBits[i].BB)
2574 assert((count < 3) && "Too much destinations to test!");
2575 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
2579 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2580 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2582 uint64_t lo = (lowValue - lowBound).getZExtValue();
2583 uint64_t hi = (highValue - lowBound).getZExtValue();
2584 CasesBits[i].ExtraWeight += I->ExtraWeight;
2586 for (uint64_t j = lo; j <= hi; j++) {
2587 CasesBits[i].Mask |= 1ULL << j;
2588 CasesBits[i].Bits++;
2592 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2596 // Figure out which block is immediately after the current one.
2597 MachineFunction::iterator BBI = CR.CaseBB;
2600 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2602 DEBUG(dbgs() << "Cases:\n");
2603 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2604 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2605 << ", Bits: " << CasesBits[i].Bits
2606 << ", BB: " << CasesBits[i].BB << '\n');
2608 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2609 CurMF->insert(BBI, CaseBB);
2610 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2612 CasesBits[i].BB, CasesBits[i].ExtraWeight));
2614 // Put SV in a virtual register to make it available from the new blocks.
2615 ExportFromCurrentBlock(SV);
2618 BitTestBlock BTB(lowBound, cmpRange, SV,
2619 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2620 CR.CaseBB, Default, std::move(BTC));
2622 if (CR.CaseBB == SwitchBB)
2623 visitBitTestHeader(BTB, SwitchBB);
2625 BitTestCases.push_back(std::move(BTB));
2630 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2631 void SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2632 const SwitchInst& SI) {
2633 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2634 // Start with "simple" cases.
2635 for (SwitchInst::ConstCaseIt i : SI.cases()) {
2636 const BasicBlock *SuccBB = i.getCaseSuccessor();
2637 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2639 uint32_t ExtraWeight =
2640 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
2642 Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
2643 SMBB, ExtraWeight));
2645 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2647 // Merge case into clusters
2648 if (Cases.size() >= 2)
2649 // Must recompute end() each iteration because it may be
2650 // invalidated by erase if we hold on to it
2651 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
2652 J != Cases.end(); ) {
2653 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2654 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2655 MachineBasicBlock* nextBB = J->BB;
2656 MachineBasicBlock* currentBB = I->BB;
2658 // If the two neighboring cases go to the same destination, merge them
2659 // into a single case.
2660 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2662 I->ExtraWeight += J->ExtraWeight;
2671 for (auto &I : Cases)
2672 // A range counts double, since it requires two compares.
2673 numCmps += I.Low != I.High ? 2 : 1;
2675 dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2676 << ". Total compares: " << numCmps << '\n';
2680 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2681 MachineBasicBlock *Last) {
2683 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2684 if (JTCases[i].first.HeaderBB == First)
2685 JTCases[i].first.HeaderBB = Last;
2687 // Update BitTestCases.
2688 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2689 if (BitTestCases[i].Parent == First)
2690 BitTestCases[i].Parent = Last;
2693 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2694 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2696 // Figure out which block is immediately after the current one.
2697 MachineBasicBlock *NextBlock = nullptr;
2698 if (SwitchMBB + 1 != FuncInfo.MF->end())
2699 NextBlock = SwitchMBB + 1;
2702 // Create a vector of Cases, sorted so that we can efficiently create a binary
2703 // search tree from them.
2705 Clusterify(Cases, SI);
2707 // Get the default destination MBB.
2708 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2710 if (isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg()) &&
2712 // Replace an unreachable default destination with the most popular case
2714 DenseMap<const BasicBlock *, uint64_t> Popularity;
2715 uint64_t MaxPop = 0;
2716 const BasicBlock *MaxBB = nullptr;
2717 for (auto I : SI.cases()) {
2718 const BasicBlock *BB = I.getCaseSuccessor();
2719 if (++Popularity[BB] > MaxPop) {
2720 MaxPop = Popularity[BB];
2728 Default = FuncInfo.MBBMap[MaxBB];
2730 // Remove cases that were pointing to the destination that is now the default.
2731 Cases.erase(std::remove_if(Cases.begin(), Cases.end(),
2732 [&](const Case &C) { return C.BB == Default; }),
2736 // If there is only the default destination, go there directly.
2737 if (Cases.empty()) {
2738 // Update machine-CFG edges.
2739 SwitchMBB->addSuccessor(Default);
2741 // If this is not a fall-through branch, emit the branch.
2742 if (Default != NextBlock) {
2743 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2744 getControlRoot(), DAG.getBasicBlock(Default)));
2749 // Get the Value to be switched on.
2750 const Value *SV = SI.getCondition();
2752 // Push the initial CaseRec onto the worklist
2753 CaseRecVector WorkList;
2754 WorkList.push_back(CaseRec(SwitchMBB,nullptr,nullptr,
2755 CaseRange(Cases.begin(),Cases.end())));
2757 while (!WorkList.empty()) {
2758 // Grab a record representing a case range to process off the worklist
2759 CaseRec CR = WorkList.back();
2760 WorkList.pop_back();
2762 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2765 // If the range has few cases (two or less) emit a series of specific
2767 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2770 // If the switch has more than N blocks, and is at least 40% dense, and the
2771 // target supports indirect branches, then emit a jump table rather than
2772 // lowering the switch to a binary tree of conditional branches.
2773 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
2774 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2777 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2778 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2779 handleBTSplitSwitchCase(CR, WorkList, SV, SwitchMBB);
2783 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2784 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2786 // Update machine-CFG edges with unique successors.
2787 SmallSet<BasicBlock*, 32> Done;
2788 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2789 BasicBlock *BB = I.getSuccessor(i);
2790 bool Inserted = Done.insert(BB).second;
2794 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2795 addSuccessorWithWeight(IndirectBrMBB, Succ);
2798 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2799 MVT::Other, getControlRoot(),
2800 getValue(I.getAddress())));
2803 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2804 if (DAG.getTarget().Options.TrapUnreachable)
2805 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2808 void SelectionDAGBuilder::visitFSub(const User &I) {
2809 // -0.0 - X --> fneg
2810 Type *Ty = I.getType();
2811 if (isa<Constant>(I.getOperand(0)) &&
2812 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2813 SDValue Op2 = getValue(I.getOperand(1));
2814 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2815 Op2.getValueType(), Op2));
2819 visitBinary(I, ISD::FSUB);
2822 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2823 SDValue Op1 = getValue(I.getOperand(0));
2824 SDValue Op2 = getValue(I.getOperand(1));
2829 if (const OverflowingBinaryOperator *OFBinOp =
2830 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2831 nuw = OFBinOp->hasNoUnsignedWrap();
2832 nsw = OFBinOp->hasNoSignedWrap();
2834 if (const PossiblyExactOperator *ExactOp =
2835 dyn_cast<const PossiblyExactOperator>(&I))
2836 exact = ExactOp->isExact();
2838 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2839 Op1, Op2, nuw, nsw, exact);
2840 setValue(&I, BinNodeValue);
2843 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2844 SDValue Op1 = getValue(I.getOperand(0));
2845 SDValue Op2 = getValue(I.getOperand(1));
2848 DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
2850 // Coerce the shift amount to the right type if we can.
2851 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2852 unsigned ShiftSize = ShiftTy.getSizeInBits();
2853 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2854 SDLoc DL = getCurSDLoc();
2856 // If the operand is smaller than the shift count type, promote it.
2857 if (ShiftSize > Op2Size)
2858 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2860 // If the operand is larger than the shift count type but the shift
2861 // count type has enough bits to represent any shift value, truncate
2862 // it now. This is a common case and it exposes the truncate to
2863 // optimization early.
2864 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2865 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2866 // Otherwise we'll need to temporarily settle for some other convenient
2867 // type. Type legalization will make adjustments once the shiftee is split.
2869 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2876 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2878 if (const OverflowingBinaryOperator *OFBinOp =
2879 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2880 nuw = OFBinOp->hasNoUnsignedWrap();
2881 nsw = OFBinOp->hasNoSignedWrap();
2883 if (const PossiblyExactOperator *ExactOp =
2884 dyn_cast<const PossiblyExactOperator>(&I))
2885 exact = ExactOp->isExact();
2888 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2893 void SelectionDAGBuilder::visitSDiv(const User &I) {
2894 SDValue Op1 = getValue(I.getOperand(0));
2895 SDValue Op2 = getValue(I.getOperand(1));
2897 // Turn exact SDivs into multiplications.
2898 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2900 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2901 !isa<ConstantSDNode>(Op1) &&
2902 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2903 setValue(&I, DAG.getTargetLoweringInfo()
2904 .BuildExactSDIV(Op1, Op2, getCurSDLoc(), DAG));
2906 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
2910 void SelectionDAGBuilder::visitICmp(const User &I) {
2911 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2912 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2913 predicate = IC->getPredicate();
2914 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2915 predicate = ICmpInst::Predicate(IC->getPredicate());
2916 SDValue Op1 = getValue(I.getOperand(0));
2917 SDValue Op2 = getValue(I.getOperand(1));
2918 ISD::CondCode Opcode = getICmpCondCode(predicate);
2920 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2921 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2924 void SelectionDAGBuilder::visitFCmp(const User &I) {
2925 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2926 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2927 predicate = FC->getPredicate();
2928 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2929 predicate = FCmpInst::Predicate(FC->getPredicate());
2930 SDValue Op1 = getValue(I.getOperand(0));
2931 SDValue Op2 = getValue(I.getOperand(1));
2932 ISD::CondCode Condition = getFCmpCondCode(predicate);
2933 if (TM.Options.NoNaNsFPMath)
2934 Condition = getFCmpCodeWithoutNaN(Condition);
2935 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2936 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2939 void SelectionDAGBuilder::visitSelect(const User &I) {
2940 SmallVector<EVT, 4> ValueVTs;
2941 ComputeValueVTs(DAG.getTargetLoweringInfo(), I.getType(), ValueVTs);
2942 unsigned NumValues = ValueVTs.size();
2943 if (NumValues == 0) return;
2945 SmallVector<SDValue, 4> Values(NumValues);
2946 SDValue Cond = getValue(I.getOperand(0));
2947 SDValue TrueVal = getValue(I.getOperand(1));
2948 SDValue FalseVal = getValue(I.getOperand(2));
2949 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2950 ISD::VSELECT : ISD::SELECT;
2952 for (unsigned i = 0; i != NumValues; ++i)
2953 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2954 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2956 SDValue(TrueVal.getNode(),
2957 TrueVal.getResNo() + i),
2958 SDValue(FalseVal.getNode(),
2959 FalseVal.getResNo() + i));
2961 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2962 DAG.getVTList(ValueVTs), Values));
2965 void SelectionDAGBuilder::visitTrunc(const User &I) {
2966 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2967 SDValue N = getValue(I.getOperand(0));
2968 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2969 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2972 void SelectionDAGBuilder::visitZExt(const User &I) {
2973 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2974 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2975 SDValue N = getValue(I.getOperand(0));
2976 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2977 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2980 void SelectionDAGBuilder::visitSExt(const User &I) {
2981 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2982 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2983 SDValue N = getValue(I.getOperand(0));
2984 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2985 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2988 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2989 // FPTrunc is never a no-op cast, no need to check
2990 SDValue N = getValue(I.getOperand(0));
2991 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2992 EVT DestVT = TLI.getValueType(I.getType());
2993 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(), DestVT, N,
2994 DAG.getTargetConstant(0, TLI.getPointerTy())));
2997 void SelectionDAGBuilder::visitFPExt(const User &I) {
2998 // FPExt is never a no-op cast, no need to check
2999 SDValue N = getValue(I.getOperand(0));
3000 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3001 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3004 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3005 // FPToUI is never a no-op cast, no need to check
3006 SDValue N = getValue(I.getOperand(0));
3007 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3008 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3011 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3012 // FPToSI is never a no-op cast, no need to check
3013 SDValue N = getValue(I.getOperand(0));
3014 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3015 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3018 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3019 // UIToFP is never a no-op cast, no need to check
3020 SDValue N = getValue(I.getOperand(0));
3021 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3022 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3025 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3026 // SIToFP is never a no-op cast, no need to check
3027 SDValue N = getValue(I.getOperand(0));
3028 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3029 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3032 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3033 // What to do depends on the size of the integer and the size of the pointer.
3034 // We can either truncate, zero extend, or no-op, accordingly.
3035 SDValue N = getValue(I.getOperand(0));
3036 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3037 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3040 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3041 // What to do depends on the size of the integer and the size of the pointer.
3042 // We can either truncate, zero extend, or no-op, accordingly.
3043 SDValue N = getValue(I.getOperand(0));
3044 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3045 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3048 void SelectionDAGBuilder::visitBitCast(const User &I) {
3049 SDValue N = getValue(I.getOperand(0));
3050 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
3052 // BitCast assures us that source and destination are the same size so this is
3053 // either a BITCAST or a no-op.
3054 if (DestVT != N.getValueType())
3055 setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
3056 DestVT, N)); // convert types.
3057 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3058 // might fold any kind of constant expression to an integer constant and that
3059 // is not what we are looking for. Only regcognize a bitcast of a genuine
3060 // constant integer as an opaque constant.
3061 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3062 setValue(&I, DAG.getConstant(C->getValue(), DestVT, /*isTarget=*/false,
3065 setValue(&I, N); // noop cast.
3068 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3069 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3070 const Value *SV = I.getOperand(0);
3071 SDValue N = getValue(SV);
3072 EVT DestVT = TLI.getValueType(I.getType());
3074 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3075 unsigned DestAS = I.getType()->getPointerAddressSpace();
3077 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3078 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3083 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3084 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3085 SDValue InVec = getValue(I.getOperand(0));
3086 SDValue InVal = getValue(I.getOperand(1));
3087 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
3088 getCurSDLoc(), TLI.getVectorIdxTy());
3089 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3090 TLI.getValueType(I.getType()), InVec, InVal, InIdx));
3093 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3094 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3095 SDValue InVec = getValue(I.getOperand(0));
3096 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
3097 getCurSDLoc(), TLI.getVectorIdxTy());
3098 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3099 TLI.getValueType(I.getType()), InVec, InIdx));
3102 // Utility for visitShuffleVector - Return true if every element in Mask,
3103 // beginning from position Pos and ending in Pos+Size, falls within the
3104 // specified sequential range [L, L+Pos). or is undef.
3105 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
3106 unsigned Pos, unsigned Size, int Low) {
3107 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3108 if (Mask[i] >= 0 && Mask[i] != Low)
3113 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3114 SDValue Src1 = getValue(I.getOperand(0));
3115 SDValue Src2 = getValue(I.getOperand(1));
3117 SmallVector<int, 8> Mask;
3118 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3119 unsigned MaskNumElts = Mask.size();
3121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3122 EVT VT = TLI.getValueType(I.getType());
3123 EVT SrcVT = Src1.getValueType();
3124 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3126 if (SrcNumElts == MaskNumElts) {
3127 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3132 // Normalize the shuffle vector since mask and vector length don't match.
3133 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
3134 // Mask is longer than the source vectors and is a multiple of the source
3135 // vectors. We can use concatenate vector to make the mask and vectors
3137 if (SrcNumElts*2 == MaskNumElts) {
3138 // First check for Src1 in low and Src2 in high
3139 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
3140 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
3141 // The shuffle is concatenating two vectors together.
3142 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3146 // Then check for Src2 in low and Src1 in high
3147 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
3148 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
3149 // The shuffle is concatenating two vectors together.
3150 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
3156 // Pad both vectors with undefs to make them the same length as the mask.
3157 unsigned NumConcat = MaskNumElts / SrcNumElts;
3158 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
3159 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
3160 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3162 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3163 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3167 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3168 getCurSDLoc(), VT, MOps1);
3169 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
3170 getCurSDLoc(), VT, MOps2);
3172 // Readjust mask for new input vector length.
3173 SmallVector<int, 8> MappedOps;
3174 for (unsigned i = 0; i != MaskNumElts; ++i) {
3176 if (Idx >= (int)SrcNumElts)
3177 Idx -= SrcNumElts - MaskNumElts;
3178 MappedOps.push_back(Idx);
3181 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3186 if (SrcNumElts > MaskNumElts) {
3187 // Analyze the access pattern of the vector to see if we can extract
3188 // two subvectors and do the shuffle. The analysis is done by calculating
3189 // the range of elements the mask access on both vectors.
3190 int MinRange[2] = { static_cast<int>(SrcNumElts),
3191 static_cast<int>(SrcNumElts)};
3192 int MaxRange[2] = {-1, -1};
3194 for (unsigned i = 0; i != MaskNumElts; ++i) {
3200 if (Idx >= (int)SrcNumElts) {
3204 if (Idx > MaxRange[Input])
3205 MaxRange[Input] = Idx;
3206 if (Idx < MinRange[Input])
3207 MinRange[Input] = Idx;
3210 // Check if the access is smaller than the vector size and can we find
3211 // a reasonable extract index.
3212 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
3214 int StartIdx[2]; // StartIdx to extract from
3215 for (unsigned Input = 0; Input < 2; ++Input) {
3216 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
3217 RangeUse[Input] = 0; // Unused
3218 StartIdx[Input] = 0;
3222 // Find a good start index that is a multiple of the mask length. Then
3223 // see if the rest of the elements are in range.
3224 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
3225 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
3226 StartIdx[Input] + MaskNumElts <= SrcNumElts)
3227 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
3230 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
3231 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3234 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
3235 // Extract appropriate subvector and generate a vector shuffle
3236 for (unsigned Input = 0; Input < 2; ++Input) {
3237 SDValue &Src = Input == 0 ? Src1 : Src2;
3238 if (RangeUse[Input] == 0)
3239 Src = DAG.getUNDEF(VT);
3242 ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT, Src,
3243 DAG.getConstant(StartIdx[Input], TLI.getVectorIdxTy()));
3246 // Calculate new mask.
3247 SmallVector<int, 8> MappedOps;
3248 for (unsigned i = 0; i != MaskNumElts; ++i) {
3251 if (Idx < (int)SrcNumElts)
3254 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3256 MappedOps.push_back(Idx);
3259 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
3265 // We can't use either concat vectors or extract subvectors so fall back to
3266 // replacing the shuffle with extract and build vector.
3267 // to insert and build vector.
3268 EVT EltVT = VT.getVectorElementType();
3269 EVT IdxVT = TLI.getVectorIdxTy();
3270 SmallVector<SDValue,8> Ops;
3271 for (unsigned i = 0; i != MaskNumElts; ++i) {
3276 Res = DAG.getUNDEF(EltVT);
3278 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3279 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3281 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3282 EltVT, Src, DAG.getConstant(Idx, IdxVT));
3288 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops));
3291 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3292 const Value *Op0 = I.getOperand(0);
3293 const Value *Op1 = I.getOperand(1);
3294 Type *AggTy = I.getType();
3295 Type *ValTy = Op1->getType();
3296 bool IntoUndef = isa<UndefValue>(Op0);
3297 bool FromUndef = isa<UndefValue>(Op1);
3299 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3301 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3302 SmallVector<EVT, 4> AggValueVTs;
3303 ComputeValueVTs(TLI, AggTy, AggValueVTs);
3304 SmallVector<EVT, 4> ValValueVTs;
3305 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3307 unsigned NumAggValues = AggValueVTs.size();
3308 unsigned NumValValues = ValValueVTs.size();
3309 SmallVector<SDValue, 4> Values(NumAggValues);
3311 // Ignore an insertvalue that produces an empty object
3312 if (!NumAggValues) {
3313 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3317 SDValue Agg = getValue(Op0);
3319 // Copy the beginning value(s) from the original aggregate.
3320 for (; i != LinearIndex; ++i)
3321 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3322 SDValue(Agg.getNode(), Agg.getResNo() + i);
3323 // Copy values from the inserted value(s).
3325 SDValue Val = getValue(Op1);
3326 for (; i != LinearIndex + NumValValues; ++i)
3327 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3328 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3330 // Copy remaining value(s) from the original aggregate.
3331 for (; i != NumAggValues; ++i)
3332 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3333 SDValue(Agg.getNode(), Agg.getResNo() + i);
3335 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3336 DAG.getVTList(AggValueVTs), Values));
3339 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3340 const Value *Op0 = I.getOperand(0);
3341 Type *AggTy = Op0->getType();
3342 Type *ValTy = I.getType();
3343 bool OutOfUndef = isa<UndefValue>(Op0);
3345 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
3347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3348 SmallVector<EVT, 4> ValValueVTs;
3349 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3351 unsigned NumValValues = ValValueVTs.size();
3353 // Ignore a extractvalue that produces an empty object
3354 if (!NumValValues) {
3355 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3359 SmallVector<SDValue, 4> Values(NumValValues);
3361 SDValue Agg = getValue(Op0);
3362 // Copy out the selected value(s).
3363 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3364 Values[i - LinearIndex] =
3366 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3367 SDValue(Agg.getNode(), Agg.getResNo() + i);
3369 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3370 DAG.getVTList(ValValueVTs), Values));
3373 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3374 Value *Op0 = I.getOperand(0);
3375 // Note that the pointer operand may be a vector of pointers. Take the scalar
3376 // element which holds a pointer.
3377 Type *Ty = Op0->getType()->getScalarType();
3378 unsigned AS = Ty->getPointerAddressSpace();
3379 SDValue N = getValue(Op0);
3381 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
3383 const Value *Idx = *OI;
3384 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
3385 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3388 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3389 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3390 DAG.getConstant(Offset, N.getValueType()));
3393 Ty = StTy->getElementType(Field);
3395 Ty = cast<SequentialType>(Ty)->getElementType();
3397 // If this is a constant subscript, handle it quickly.
3398 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3399 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3400 if (CI->isZero()) continue;
3402 DL->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
3404 EVT PTy = TLI.getPointerTy(AS);
3405 unsigned PtrBits = PTy.getSizeInBits();
3407 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
3408 DAG.getConstant(Offs, MVT::i64));
3410 OffsVal = DAG.getConstant(Offs, PTy);
3412 N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
3417 // N = N + Idx * ElementSize;
3419 APInt(TLI.getPointerSizeInBits(AS), DL->getTypeAllocSize(Ty));
3420 SDValue IdxN = getValue(Idx);
3422 // If the index is smaller or larger than intptr_t, truncate or extend
3424 IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
3426 // If this is a multiply by a power of two, turn it into a shl
3427 // immediately. This is a very common case.
3428 if (ElementSize != 1) {
3429 if (ElementSize.isPowerOf2()) {
3430 unsigned Amt = ElementSize.logBase2();
3431 IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
3432 N.getValueType(), IdxN,
3433 DAG.getConstant(Amt, IdxN.getValueType()));
3435 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
3436 IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
3437 N.getValueType(), IdxN, Scale);
3441 N = DAG.getNode(ISD::ADD, getCurSDLoc(),
3442 N.getValueType(), N, IdxN);
3449 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3450 // If this is a fixed sized alloca in the entry block of the function,
3451 // allocate it statically on the stack.
3452 if (FuncInfo.StaticAllocaMap.count(&I))
3453 return; // getValue will auto-populate this.
3455 Type *Ty = I.getAllocatedType();
3456 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3457 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
3459 std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
3462 SDValue AllocSize = getValue(I.getArraySize());
3464 EVT IntPtr = TLI.getPointerTy();
3465 if (AllocSize.getValueType() != IntPtr)
3466 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
3468 AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
3470 DAG.getConstant(TySize, IntPtr));
3472 // Handle alignment. If the requested alignment is less than or equal to
3473 // the stack alignment, ignore it. If the size is greater than or equal to
3474 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3475 unsigned StackAlign =
3476 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3477 if (Align <= StackAlign)
3480 // Round the size of the allocation up to the stack alignment size
3481 // by add SA-1 to the size.
3482 AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
3483 AllocSize.getValueType(), AllocSize,
3484 DAG.getIntPtrConstant(StackAlign-1));
3486 // Mask out the low bits for alignment purposes.
3487 AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
3488 AllocSize.getValueType(), AllocSize,
3489 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3491 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3492 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3493 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(), VTs, Ops);
3495 DAG.setRoot(DSA.getValue(1));
3497 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
3500 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3502 return visitAtomicLoad(I);
3504 const Value *SV = I.getOperand(0);
3505 SDValue Ptr = getValue(SV);
3507 Type *Ty = I.getType();
3509 bool isVolatile = I.isVolatile();
3510 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3511 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3512 unsigned Alignment = I.getAlignment();
3515 I.getAAMetadata(AAInfo);
3516 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3518 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3519 SmallVector<EVT, 4> ValueVTs;
3520 SmallVector<uint64_t, 4> Offsets;
3521 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3522 unsigned NumValues = ValueVTs.size();
3527 bool ConstantMemory = false;
3528 if (isVolatile || NumValues > MaxParallelChains)
3529 // Serialize volatile loads with other side effects.
3531 else if (AA->pointsToConstantMemory(
3532 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
3533 // Do not serialize (non-volatile) loads of constant memory with anything.
3534 Root = DAG.getEntryNode();
3535 ConstantMemory = true;
3537 // Do not serialize non-volatile loads against each other.
3538 Root = DAG.getRoot();
3542 Root = TLI.prepareVolatileOrAtomicLoad(Root, getCurSDLoc(), DAG);
3544 SmallVector<SDValue, 4> Values(NumValues);
3545 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3547 EVT PtrVT = Ptr.getValueType();
3548 unsigned ChainI = 0;
3549 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3550 // Serializing loads here may result in excessive register pressure, and
3551 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3552 // could recover a bit by hoisting nodes upward in the chain by recognizing
3553 // they are side-effect free or do not alias. The optimizer should really
3554 // avoid this case by converting large object/array copies to llvm.memcpy
3555 // (MaxParallelChains should always remain as failsafe).
3556 if (ChainI == MaxParallelChains) {
3557 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3558 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3559 makeArrayRef(Chains.data(), ChainI));
3563 SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
3565 DAG.getConstant(Offsets[i], PtrVT));
3566 SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
3567 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3568 isNonTemporal, isInvariant, Alignment, AAInfo,
3572 Chains[ChainI] = L.getValue(1);
3575 if (!ConstantMemory) {
3576 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3577 makeArrayRef(Chains.data(), ChainI));
3581 PendingLoads.push_back(Chain);
3584 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3585 DAG.getVTList(ValueVTs), Values));
3588 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3590 return visitAtomicStore(I);
3592 const Value *SrcV = I.getOperand(0);
3593 const Value *PtrV = I.getOperand(1);
3595 SmallVector<EVT, 4> ValueVTs;
3596 SmallVector<uint64_t, 4> Offsets;
3597 ComputeValueVTs(DAG.getTargetLoweringInfo(), SrcV->getType(),
3598 ValueVTs, &Offsets);
3599 unsigned NumValues = ValueVTs.size();
3603 // Get the lowered operands. Note that we do this after
3604 // checking if NumResults is zero, because with zero results
3605 // the operands won't have values in the map.
3606 SDValue Src = getValue(SrcV);
3607 SDValue Ptr = getValue(PtrV);
3609 SDValue Root = getRoot();
3610 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3612 EVT PtrVT = Ptr.getValueType();
3613 bool isVolatile = I.isVolatile();
3614 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3615 unsigned Alignment = I.getAlignment();
3618 I.getAAMetadata(AAInfo);
3620 unsigned ChainI = 0;
3621 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3622 // See visitLoad comments.
3623 if (ChainI == MaxParallelChains) {
3624 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3625 makeArrayRef(Chains.data(), ChainI));
3629 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
3630 DAG.getConstant(Offsets[i], PtrVT));
3631 SDValue St = DAG.getStore(Root, getCurSDLoc(),
3632 SDValue(Src.getNode(), Src.getResNo() + i),
3633 Add, MachinePointerInfo(PtrV, Offsets[i]),
3634 isVolatile, isNonTemporal, Alignment, AAInfo);
3635 Chains[ChainI] = St;
3638 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
3639 makeArrayRef(Chains.data(), ChainI));
3640 DAG.setRoot(StoreNode);
3643 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
3644 SDLoc sdl = getCurSDLoc();
3646 Value *PtrOperand = I.getArgOperand(0);
3647 SDValue Ptr = getValue(PtrOperand);
3648 SDValue Src0 = getValue(I.getArgOperand(1));
3649 SDValue Mask = getValue(I.getArgOperand(3));
3650 EVT VT = Src0.getValueType();
3651 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3653 Alignment = DAG.getEVTAlignment(VT);
3656 I.getAAMetadata(AAInfo);
3658 MachineMemOperand *MMO =
3659 DAG.getMachineFunction().
3660 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3661 MachineMemOperand::MOStore, VT.getStoreSize(),
3663 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, MMO);
3664 DAG.setRoot(StoreNode);
3665 setValue(&I, StoreNode);
3668 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
3669 SDLoc sdl = getCurSDLoc();
3671 Value *PtrOperand = I.getArgOperand(0);
3672 SDValue Ptr = getValue(PtrOperand);
3673 SDValue Src0 = getValue(I.getArgOperand(1));
3674 SDValue Mask = getValue(I.getArgOperand(3));
3676 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3677 EVT VT = TLI.getValueType(I.getType());
3678 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3680 Alignment = DAG.getEVTAlignment(VT);
3683 I.getAAMetadata(AAInfo);
3684 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3686 SDValue InChain = DAG.getRoot();
3687 if (AA->pointsToConstantMemory(
3688 AliasAnalysis::Location(PtrOperand,
3689 AA->getTypeStoreSize(I.getType()),
3691 // Do not serialize (non-volatile) loads of constant memory with anything.
3692 InChain = DAG.getEntryNode();
3695 MachineMemOperand *MMO =
3696 DAG.getMachineFunction().
3697 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3698 MachineMemOperand::MOLoad, VT.getStoreSize(),
3699 Alignment, AAInfo, Ranges);
3701 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, MMO);
3702 SDValue OutChain = Load.getValue(1);
3703 DAG.setRoot(OutChain);
3707 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3708 SDLoc dl = getCurSDLoc();
3709 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3710 AtomicOrdering FailureOrder = I.getFailureOrdering();
3711 SynchronizationScope Scope = I.getSynchScope();
3713 SDValue InChain = getRoot();
3715 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3716 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3717 SDValue L = DAG.getAtomicCmpSwap(
3718 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3719 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3720 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3721 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3723 SDValue OutChain = L.getValue(2);
3726 DAG.setRoot(OutChain);
3729 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3730 SDLoc dl = getCurSDLoc();
3732 switch (I.getOperation()) {
3733 default: llvm_unreachable("Unknown atomicrmw operation");
3734 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3735 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3736 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3737 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3738 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3739 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3740 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3741 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3742 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3743 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3744 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3746 AtomicOrdering Order = I.getOrdering();
3747 SynchronizationScope Scope = I.getSynchScope();
3749 SDValue InChain = getRoot();
3752 DAG.getAtomic(NT, dl,
3753 getValue(I.getValOperand()).getSimpleValueType(),
3755 getValue(I.getPointerOperand()),
3756 getValue(I.getValOperand()),
3757 I.getPointerOperand(),
3758 /* Alignment=*/ 0, Order, Scope);
3760 SDValue OutChain = L.getValue(1);
3763 DAG.setRoot(OutChain);
3766 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3767 SDLoc dl = getCurSDLoc();
3768 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3771 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3772 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
3773 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3776 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3777 SDLoc dl = getCurSDLoc();
3778 AtomicOrdering Order = I.getOrdering();
3779 SynchronizationScope Scope = I.getSynchScope();
3781 SDValue InChain = getRoot();
3783 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3784 EVT VT = TLI.getValueType(I.getType());
3786 if (I.getAlignment() < VT.getSizeInBits() / 8)
3787 report_fatal_error("Cannot generate unaligned atomic load");
3789 MachineMemOperand *MMO =
3790 DAG.getMachineFunction().
3791 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3792 MachineMemOperand::MOVolatile |
3793 MachineMemOperand::MOLoad,
3795 I.getAlignment() ? I.getAlignment() :
3796 DAG.getEVTAlignment(VT));
3798 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3800 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3801 getValue(I.getPointerOperand()), MMO,
3804 SDValue OutChain = L.getValue(1);
3807 DAG.setRoot(OutChain);
3810 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3811 SDLoc dl = getCurSDLoc();
3813 AtomicOrdering Order = I.getOrdering();
3814 SynchronizationScope Scope = I.getSynchScope();
3816 SDValue InChain = getRoot();
3818 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3819 EVT VT = TLI.getValueType(I.getValueOperand()->getType());
3821 if (I.getAlignment() < VT.getSizeInBits() / 8)
3822 report_fatal_error("Cannot generate unaligned atomic store");
3825 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3827 getValue(I.getPointerOperand()),
3828 getValue(I.getValueOperand()),
3829 I.getPointerOperand(), I.getAlignment(),
3832 DAG.setRoot(OutChain);
3835 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3837 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3838 unsigned Intrinsic) {
3839 bool HasChain = !I.doesNotAccessMemory();
3840 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3842 // Build the operand list.
3843 SmallVector<SDValue, 8> Ops;
3844 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3846 // We don't need to serialize loads against other loads.
3847 Ops.push_back(DAG.getRoot());
3849 Ops.push_back(getRoot());
3853 // Info is set by getTgtMemInstrinsic
3854 TargetLowering::IntrinsicInfo Info;
3855 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3856 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3858 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3859 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3860 Info.opc == ISD::INTRINSIC_W_CHAIN)
3861 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI.getPointerTy()));
3863 // Add all operands of the call to the operand list.
3864 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3865 SDValue Op = getValue(I.getArgOperand(i));
3869 SmallVector<EVT, 4> ValueVTs;
3870 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3873 ValueVTs.push_back(MVT::Other);
3875 SDVTList VTs = DAG.getVTList(ValueVTs);
3879 if (IsTgtIntrinsic) {
3880 // This is target intrinsic that touches memory
3881 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3882 VTs, Ops, Info.memVT,
3883 MachinePointerInfo(Info.ptrVal, Info.offset),
3884 Info.align, Info.vol,
3885 Info.readMem, Info.writeMem, Info.size);
3886 } else if (!HasChain) {
3887 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
3888 } else if (!I.getType()->isVoidTy()) {
3889 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
3891 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
3895 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3897 PendingLoads.push_back(Chain);
3902 if (!I.getType()->isVoidTy()) {
3903 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3904 EVT VT = TLI.getValueType(PTy);
3905 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3908 setValue(&I, Result);
3912 /// GetSignificand - Get the significand and build it into a floating-point
3913 /// number with exponent of 1:
3915 /// Op = (Op & 0x007fffff) | 0x3f800000;
3917 /// where Op is the hexadecimal representation of floating point value.
3919 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3920 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3921 DAG.getConstant(0x007fffff, MVT::i32));
3922 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3923 DAG.getConstant(0x3f800000, MVT::i32));
3924 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3927 /// GetExponent - Get the exponent:
3929 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3931 /// where Op is the hexadecimal representation of floating point value.
3933 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3935 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3936 DAG.getConstant(0x7f800000, MVT::i32));
3937 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3938 DAG.getConstant(23, TLI.getPointerTy()));
3939 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3940 DAG.getConstant(127, MVT::i32));
3941 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3944 /// getF32Constant - Get 32-bit floating point constant.
3946 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3947 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
3951 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
3952 /// limited-precision mode.
3953 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3954 const TargetLowering &TLI) {
3955 if (Op.getValueType() == MVT::f32 &&
3956 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3958 // Put the exponent in the right bit position for later addition to the
3961 // #define LOG2OFe 1.4426950f
3962 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3963 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3964 getF32Constant(DAG, 0x3fb8aa3b));
3965 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3967 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3968 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3969 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3971 // IntegerPartOfX <<= 23;
3972 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3973 DAG.getConstant(23, TLI.getPointerTy()));
3975 SDValue TwoToFracPartOfX;
3976 if (LimitFloatPrecision <= 6) {
3977 // For floating-point precision of 6:
3979 // TwoToFractionalPartOfX =
3981 // (0.735607626f + 0.252464424f * x) * x;
3983 // error 0.0144103317, which is 6 bits
3984 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3985 getF32Constant(DAG, 0x3e814304));
3986 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3987 getF32Constant(DAG, 0x3f3c50c8));
3988 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3989 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3990 getF32Constant(DAG, 0x3f7f5e7e));
3991 } else if (LimitFloatPrecision <= 12) {
3992 // For floating-point precision of 12:
3994 // TwoToFractionalPartOfX =
3997 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3999 // 0.000107046256 error, which is 13 to 14 bits
4000 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4001 getF32Constant(DAG, 0x3da235e3));
4002 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4003 getF32Constant(DAG, 0x3e65b8f3));
4004 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4005 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4006 getF32Constant(DAG, 0x3f324b07));
4007 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4008 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4009 getF32Constant(DAG, 0x3f7ff8fd));
4010 } else { // LimitFloatPrecision <= 18
4011 // For floating-point precision of 18:
4013 // TwoToFractionalPartOfX =
4017 // (0.554906021e-1f +
4018 // (0.961591928e-2f +
4019 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4021 // error 2.47208000*10^(-7), which is better than 18 bits
4022 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4023 getF32Constant(DAG, 0x3924b03e));
4024 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4025 getF32Constant(DAG, 0x3ab24b87));
4026 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4027 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4028 getF32Constant(DAG, 0x3c1d8c17));
4029 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4030 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4031 getF32Constant(DAG, 0x3d634a1d));
4032 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4033 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4034 getF32Constant(DAG, 0x3e75fe14));
4035 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4036 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4037 getF32Constant(DAG, 0x3f317234));
4038 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4039 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4040 getF32Constant(DAG, 0x3f800000));
4043 // Add the exponent into the result in integer domain.
4044 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
4045 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4046 DAG.getNode(ISD::ADD, dl, MVT::i32,
4047 t13, IntegerPartOfX));
4050 // No special expansion.
4051 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4054 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4055 /// limited-precision mode.
4056 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4057 const TargetLowering &TLI) {
4058 if (Op.getValueType() == MVT::f32 &&
4059 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4060 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4062 // Scale the exponent by log(2) [0.69314718f].
4063 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4064 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4065 getF32Constant(DAG, 0x3f317218));
4067 // Get the significand and build it into a floating-point number with
4069 SDValue X = GetSignificand(DAG, Op1, dl);
4071 SDValue LogOfMantissa;
4072 if (LimitFloatPrecision <= 6) {
4073 // For floating-point precision of 6:
4077 // (1.4034025f - 0.23903021f * x) * x;
4079 // error 0.0034276066, which is better than 8 bits
4080 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4081 getF32Constant(DAG, 0xbe74c456));
4082 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4083 getF32Constant(DAG, 0x3fb3a2b1));
4084 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4085 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4086 getF32Constant(DAG, 0x3f949a29));
4087 } else if (LimitFloatPrecision <= 12) {
4088 // For floating-point precision of 12:
4094 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4096 // error 0.000061011436, which is 14 bits
4097 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4098 getF32Constant(DAG, 0xbd67b6d6));
4099 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4100 getF32Constant(DAG, 0x3ee4f4b8));
4101 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4102 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4103 getF32Constant(DAG, 0x3fbc278b));
4104 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4105 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4106 getF32Constant(DAG, 0x40348e95));
4107 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4108 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4109 getF32Constant(DAG, 0x3fdef31a));
4110 } else { // LimitFloatPrecision <= 18
4111 // For floating-point precision of 18:
4119 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4121 // error 0.0000023660568, which is better than 18 bits
4122 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4123 getF32Constant(DAG, 0xbc91e5ac));
4124 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4125 getF32Constant(DAG, 0x3e4350aa));
4126 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4127 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4128 getF32Constant(DAG, 0x3f60d3e3));
4129 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4130 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4131 getF32Constant(DAG, 0x4011cdf0));
4132 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4133 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4134 getF32Constant(DAG, 0x406cfd1c));
4135 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4136 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4137 getF32Constant(DAG, 0x408797cb));
4138 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4139 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4140 getF32Constant(DAG, 0x4006dcab));
4143 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4146 // No special expansion.
4147 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4150 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4151 /// limited-precision mode.
4152 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4153 const TargetLowering &TLI) {
4154 if (Op.getValueType() == MVT::f32 &&
4155 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4156 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4158 // Get the exponent.
4159 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4161 // Get the significand and build it into a floating-point number with
4163 SDValue X = GetSignificand(DAG, Op1, dl);
4165 // Different possible minimax approximations of significand in
4166 // floating-point for various degrees of accuracy over [1,2].
4167 SDValue Log2ofMantissa;
4168 if (LimitFloatPrecision <= 6) {
4169 // For floating-point precision of 6:
4171 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4173 // error 0.0049451742, which is more than 7 bits
4174 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4175 getF32Constant(DAG, 0xbeb08fe0));
4176 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4177 getF32Constant(DAG, 0x40019463));
4178 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4179 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4180 getF32Constant(DAG, 0x3fd6633d));
4181 } else if (LimitFloatPrecision <= 12) {
4182 // For floating-point precision of 12:
4188 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4190 // error 0.0000876136000, which is better than 13 bits
4191 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4192 getF32Constant(DAG, 0xbda7262e));
4193 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4194 getF32Constant(DAG, 0x3f25280b));
4195 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4196 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4197 getF32Constant(DAG, 0x4007b923));
4198 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4199 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4200 getF32Constant(DAG, 0x40823e2f));
4201 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4202 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4203 getF32Constant(DAG, 0x4020d29c));
4204 } else { // LimitFloatPrecision <= 18
4205 // For floating-point precision of 18:
4214 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4216 // error 0.0000018516, which is better than 18 bits
4217 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4218 getF32Constant(DAG, 0xbcd2769e));
4219 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4220 getF32Constant(DAG, 0x3e8ce0b9));
4221 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4222 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4223 getF32Constant(DAG, 0x3fa22ae7));
4224 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4225 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4226 getF32Constant(DAG, 0x40525723));
4227 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4228 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4229 getF32Constant(DAG, 0x40aaf200));
4230 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4231 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4232 getF32Constant(DAG, 0x40c39dad));
4233 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4234 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4235 getF32Constant(DAG, 0x4042902c));
4238 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4241 // No special expansion.
4242 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4245 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4246 /// limited-precision mode.
4247 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4248 const TargetLowering &TLI) {
4249 if (Op.getValueType() == MVT::f32 &&
4250 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4251 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4253 // Scale the exponent by log10(2) [0.30102999f].
4254 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4255 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4256 getF32Constant(DAG, 0x3e9a209a));
4258 // Get the significand and build it into a floating-point number with
4260 SDValue X = GetSignificand(DAG, Op1, dl);
4262 SDValue Log10ofMantissa;
4263 if (LimitFloatPrecision <= 6) {
4264 // For floating-point precision of 6:
4266 // Log10ofMantissa =
4268 // (0.60948995f - 0.10380950f * x) * x;
4270 // error 0.0014886165, which is 6 bits
4271 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4272 getF32Constant(DAG, 0xbdd49a13));
4273 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4274 getF32Constant(DAG, 0x3f1c0789));
4275 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4276 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4277 getF32Constant(DAG, 0x3f011300));
4278 } else if (LimitFloatPrecision <= 12) {
4279 // For floating-point precision of 12:
4281 // Log10ofMantissa =
4284 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4286 // error 0.00019228036, which is better than 12 bits
4287 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4288 getF32Constant(DAG, 0x3d431f31));
4289 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4290 getF32Constant(DAG, 0x3ea21fb2));
4291 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4292 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4293 getF32Constant(DAG, 0x3f6ae232));
4294 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4295 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4296 getF32Constant(DAG, 0x3f25f7c3));
4297 } else { // LimitFloatPrecision <= 18
4298 // For floating-point precision of 18:
4300 // Log10ofMantissa =
4305 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4307 // error 0.0000037995730, which is better than 18 bits
4308 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4309 getF32Constant(DAG, 0x3c5d51ce));
4310 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4311 getF32Constant(DAG, 0x3e00685a));
4312 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4313 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4314 getF32Constant(DAG, 0x3efb6798));
4315 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4316 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4317 getF32Constant(DAG, 0x3f88d192));
4318 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4319 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4320 getF32Constant(DAG, 0x3fc4316c));
4321 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4322 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4323 getF32Constant(DAG, 0x3f57ce70));
4326 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4329 // No special expansion.
4330 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4333 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4334 /// limited-precision mode.
4335 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4336 const TargetLowering &TLI) {
4337 if (Op.getValueType() == MVT::f32 &&
4338 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4339 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
4341 // FractionalPartOfX = x - (float)IntegerPartOfX;
4342 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4343 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
4345 // IntegerPartOfX <<= 23;
4346 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4347 DAG.getConstant(23, TLI.getPointerTy()));
4349 SDValue TwoToFractionalPartOfX;
4350 if (LimitFloatPrecision <= 6) {
4351 // For floating-point precision of 6:
4353 // TwoToFractionalPartOfX =
4355 // (0.735607626f + 0.252464424f * x) * x;
4357 // error 0.0144103317, which is 6 bits
4358 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4359 getF32Constant(DAG, 0x3e814304));
4360 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4361 getF32Constant(DAG, 0x3f3c50c8));
4362 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4363 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4364 getF32Constant(DAG, 0x3f7f5e7e));
4365 } else if (LimitFloatPrecision <= 12) {
4366 // For floating-point precision of 12:
4368 // TwoToFractionalPartOfX =
4371 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4373 // error 0.000107046256, which is 13 to 14 bits
4374 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4375 getF32Constant(DAG, 0x3da235e3));
4376 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4377 getF32Constant(DAG, 0x3e65b8f3));
4378 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4379 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4380 getF32Constant(DAG, 0x3f324b07));
4381 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4382 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4383 getF32Constant(DAG, 0x3f7ff8fd));
4384 } else { // LimitFloatPrecision <= 18
4385 // For floating-point precision of 18:
4387 // TwoToFractionalPartOfX =
4391 // (0.554906021e-1f +
4392 // (0.961591928e-2f +
4393 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4394 // error 2.47208000*10^(-7), which is better than 18 bits
4395 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4396 getF32Constant(DAG, 0x3924b03e));
4397 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4398 getF32Constant(DAG, 0x3ab24b87));
4399 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4400 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4401 getF32Constant(DAG, 0x3c1d8c17));
4402 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4403 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4404 getF32Constant(DAG, 0x3d634a1d));
4405 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4406 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4407 getF32Constant(DAG, 0x3e75fe14));
4408 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4409 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4410 getF32Constant(DAG, 0x3f317234));
4411 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4412 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4413 getF32Constant(DAG, 0x3f800000));
4416 // Add the exponent into the result in integer domain.
4417 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4418 TwoToFractionalPartOfX);
4419 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4420 DAG.getNode(ISD::ADD, dl, MVT::i32,
4421 t13, IntegerPartOfX));
4424 // No special expansion.
4425 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4428 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4429 /// limited-precision mode with x == 10.0f.
4430 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4431 SelectionDAG &DAG, const TargetLowering &TLI) {
4432 bool IsExp10 = false;
4433 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4434 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4435 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4437 IsExp10 = LHSC->isExactlyValue(Ten);
4442 // Put the exponent in the right bit position for later addition to the
4445 // #define LOG2OF10 3.3219281f
4446 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
4447 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4448 getF32Constant(DAG, 0x40549a78));
4449 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4451 // FractionalPartOfX = x - (float)IntegerPartOfX;
4452 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4453 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4455 // IntegerPartOfX <<= 23;
4456 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4457 DAG.getConstant(23, TLI.getPointerTy()));
4459 SDValue TwoToFractionalPartOfX;
4460 if (LimitFloatPrecision <= 6) {
4461 // For floating-point precision of 6:
4463 // twoToFractionalPartOfX =
4465 // (0.735607626f + 0.252464424f * x) * x;
4467 // error 0.0144103317, which is 6 bits
4468 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4469 getF32Constant(DAG, 0x3e814304));
4470 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4471 getF32Constant(DAG, 0x3f3c50c8));
4472 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4473 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4474 getF32Constant(DAG, 0x3f7f5e7e));
4475 } else if (LimitFloatPrecision <= 12) {
4476 // For floating-point precision of 12:
4478 // TwoToFractionalPartOfX =
4481 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4483 // error 0.000107046256, which is 13 to 14 bits
4484 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4485 getF32Constant(DAG, 0x3da235e3));
4486 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4487 getF32Constant(DAG, 0x3e65b8f3));
4488 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4489 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4490 getF32Constant(DAG, 0x3f324b07));
4491 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4492 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4493 getF32Constant(DAG, 0x3f7ff8fd));
4494 } else { // LimitFloatPrecision <= 18
4495 // For floating-point precision of 18:
4497 // TwoToFractionalPartOfX =
4501 // (0.554906021e-1f +
4502 // (0.961591928e-2f +
4503 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4504 // error 2.47208000*10^(-7), which is better than 18 bits
4505 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4506 getF32Constant(DAG, 0x3924b03e));
4507 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4508 getF32Constant(DAG, 0x3ab24b87));
4509 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4510 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4511 getF32Constant(DAG, 0x3c1d8c17));
4512 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4513 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4514 getF32Constant(DAG, 0x3d634a1d));
4515 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4516 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4517 getF32Constant(DAG, 0x3e75fe14));
4518 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4519 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4520 getF32Constant(DAG, 0x3f317234));
4521 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4522 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4523 getF32Constant(DAG, 0x3f800000));
4526 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
4527 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4528 DAG.getNode(ISD::ADD, dl, MVT::i32,
4529 t13, IntegerPartOfX));
4532 // No special expansion.
4533 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4537 /// ExpandPowI - Expand a llvm.powi intrinsic.
4538 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4539 SelectionDAG &DAG) {
4540 // If RHS is a constant, we can expand this out to a multiplication tree,
4541 // otherwise we end up lowering to a call to __powidf2 (for example). When
4542 // optimizing for size, we only want to do this if the expansion would produce
4543 // a small number of multiplies, otherwise we do the full expansion.
4544 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4545 // Get the exponent as a positive value.
4546 unsigned Val = RHSC->getSExtValue();
4547 if ((int)Val < 0) Val = -Val;
4549 // powi(x, 0) -> 1.0
4551 return DAG.getConstantFP(1.0, LHS.getValueType());
4553 const Function *F = DAG.getMachineFunction().getFunction();
4554 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
4555 Attribute::OptimizeForSize) ||
4556 // If optimizing for size, don't insert too many multiplies. This
4557 // inserts up to 5 multiplies.
4558 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4559 // We use the simple binary decomposition method to generate the multiply
4560 // sequence. There are more optimal ways to do this (for example,
4561 // powi(x,15) generates one more multiply than it should), but this has
4562 // the benefit of being both really simple and much better than a libcall.
4563 SDValue Res; // Logically starts equal to 1.0
4564 SDValue CurSquare = LHS;
4568 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4570 Res = CurSquare; // 1.0*CurSquare.
4573 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4574 CurSquare, CurSquare);
4578 // If the original was negative, invert the result, producing 1/(x*x*x).
4579 if (RHSC->getSExtValue() < 0)
4580 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4581 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4586 // Otherwise, expand to a libcall.
4587 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4590 // getTruncatedArgReg - Find underlying register used for an truncated
4592 static unsigned getTruncatedArgReg(const SDValue &N) {
4593 if (N.getOpcode() != ISD::TRUNCATE)
4596 const SDValue &Ext = N.getOperand(0);
4597 if (Ext.getOpcode() == ISD::AssertZext ||
4598 Ext.getOpcode() == ISD::AssertSext) {
4599 const SDValue &CFR = Ext.getOperand(0);
4600 if (CFR.getOpcode() == ISD::CopyFromReg)
4601 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4602 if (CFR.getOpcode() == ISD::TRUNCATE)
4603 return getTruncatedArgReg(CFR);
4608 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4609 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4610 /// At the end of instruction selection, they will be inserted to the entry BB.
4611 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V,
4613 MDNode *Expr, int64_t Offset,
4616 const Argument *Arg = dyn_cast<Argument>(V);
4620 MachineFunction &MF = DAG.getMachineFunction();
4621 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4623 // Ignore inlined function arguments here.
4624 DIVariable DV(Variable);
4625 if (DV.isInlinedFnArgument(MF.getFunction()))
4628 Optional<MachineOperand> Op;
4629 // Some arguments' frame index is recorded during argument lowering.
4630 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4631 Op = MachineOperand::CreateFI(FI);
4633 if (!Op && N.getNode()) {
4635 if (N.getOpcode() == ISD::CopyFromReg)
4636 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4638 Reg = getTruncatedArgReg(N);
4639 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4640 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4641 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4646 Op = MachineOperand::CreateReg(Reg, false);
4650 // Check if ValueMap has reg number.
4651 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4652 if (VMI != FuncInfo.ValueMap.end())
4653 Op = MachineOperand::CreateReg(VMI->second, false);
4656 if (!Op && N.getNode())
4657 // Check if frame index is available.
4658 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4659 if (FrameIndexSDNode *FINode =
4660 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4661 Op = MachineOperand::CreateFI(FINode->getIndex());
4667 FuncInfo.ArgDbgValues.push_back(
4668 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE),
4669 IsIndirect, Op->getReg(), Offset, Variable, Expr));
4671 FuncInfo.ArgDbgValues.push_back(
4672 BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
4675 .addMetadata(Variable)
4676 .addMetadata(Expr));
4681 // VisualStudio defines setjmp as _setjmp
4682 #if defined(_MSC_VER) && defined(setjmp) && \
4683 !defined(setjmp_undefined_for_msvc)
4684 # pragma push_macro("setjmp")
4686 # define setjmp_undefined_for_msvc
4689 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4690 /// we want to emit this as a call to a named external function, return the name
4691 /// otherwise lower it and return null.
4693 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4694 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4695 SDLoc sdl = getCurSDLoc();
4696 DebugLoc dl = getCurDebugLoc();
4699 switch (Intrinsic) {
4701 // By default, turn this into a target intrinsic node.
4702 visitTargetIntrinsic(I, Intrinsic);
4704 case Intrinsic::vastart: visitVAStart(I); return nullptr;
4705 case Intrinsic::vaend: visitVAEnd(I); return nullptr;
4706 case Intrinsic::vacopy: visitVACopy(I); return nullptr;
4707 case Intrinsic::returnaddress:
4708 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI.getPointerTy(),
4709 getValue(I.getArgOperand(0))));
4711 case Intrinsic::frameaddress:
4712 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4713 getValue(I.getArgOperand(0))));
4715 case Intrinsic::read_register: {
4716 Value *Reg = I.getArgOperand(0);
4717 SDValue RegName = DAG.getMDNode(cast<MDNode>(Reg));
4718 EVT VT = TLI.getValueType(I.getType());
4719 setValue(&I, DAG.getNode(ISD::READ_REGISTER, sdl, VT, RegName));
4722 case Intrinsic::write_register: {
4723 Value *Reg = I.getArgOperand(0);
4724 Value *RegValue = I.getArgOperand(1);
4725 SDValue Chain = getValue(RegValue).getOperand(0);
4726 SDValue RegName = DAG.getMDNode(cast<MDNode>(Reg));
4727 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4728 RegName, getValue(RegValue)));
4731 case Intrinsic::setjmp:
4732 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
4733 case Intrinsic::longjmp:
4734 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
4735 case Intrinsic::memcpy: {
4736 // Assert for address < 256 since we support only user defined address
4738 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4740 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4742 "Unknown address space");
4743 SDValue Op1 = getValue(I.getArgOperand(0));
4744 SDValue Op2 = getValue(I.getArgOperand(1));
4745 SDValue Op3 = getValue(I.getArgOperand(2));
4746 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4748 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4749 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4750 DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
4751 MachinePointerInfo(I.getArgOperand(0)),
4752 MachinePointerInfo(I.getArgOperand(1))));
4755 case Intrinsic::memset: {
4756 // Assert for address < 256 since we support only user defined address
4758 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4760 "Unknown address space");
4761 SDValue Op1 = getValue(I.getArgOperand(0));
4762 SDValue Op2 = getValue(I.getArgOperand(1));
4763 SDValue Op3 = getValue(I.getArgOperand(2));
4764 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4766 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4767 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4768 DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4769 MachinePointerInfo(I.getArgOperand(0))));
4772 case Intrinsic::memmove: {
4773 // Assert for address < 256 since we support only user defined address
4775 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4777 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4779 "Unknown address space");
4780 SDValue Op1 = getValue(I.getArgOperand(0));
4781 SDValue Op2 = getValue(I.getArgOperand(1));
4782 SDValue Op3 = getValue(I.getArgOperand(2));
4783 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4785 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4786 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4787 DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4788 MachinePointerInfo(I.getArgOperand(0)),
4789 MachinePointerInfo(I.getArgOperand(1))));
4792 case Intrinsic::dbg_declare: {
4793 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4794 MDNode *Variable = DI.getVariable();
4795 MDNode *Expression = DI.getExpression();
4796 const Value *Address = DI.getAddress();
4797 DIVariable DIVar(Variable);
4798 assert((!DIVar || DIVar.isVariable()) &&
4799 "Variable in DbgDeclareInst should be either null or a DIVariable.");
4800 if (!Address || !DIVar) {
4801 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4805 // Check if address has undef value.
4806 if (isa<UndefValue>(Address) ||
4807 (Address->use_empty() && !isa<Argument>(Address))) {
4808 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4812 SDValue &N = NodeMap[Address];
4813 if (!N.getNode() && isa<Argument>(Address))
4814 // Check unused arguments map.
4815 N = UnusedArgNodeMap[Address];
4818 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4819 Address = BCI->getOperand(0);
4820 // Parameters are handled specially.
4822 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4823 isa<Argument>(Address));
4825 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4827 if (isParameter && !AI) {
4828 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4830 // Byval parameter. We have a frame index at this point.
4831 SDV = DAG.getFrameIndexDbgValue(
4832 Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
4834 // Address is an argument, so try to emit its dbg value using
4835 // virtual register info from the FuncInfo.ValueMap.
4836 EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false, N);
4840 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4841 true, 0, dl, SDNodeOrder);
4843 // Can't do anything with other non-AI cases yet.
4844 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4845 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4846 DEBUG(Address->dump());
4849 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4851 // If Address is an argument then try to emit its dbg value using
4852 // virtual register info from the FuncInfo.ValueMap.
4853 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, 0, false,
4855 // If variable is pinned by a alloca in dominating bb then
4856 // use StaticAllocaMap.
4857 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4858 if (AI->getParent() != DI.getParent()) {
4859 DenseMap<const AllocaInst*, int>::iterator SI =
4860 FuncInfo.StaticAllocaMap.find(AI);
4861 if (SI != FuncInfo.StaticAllocaMap.end()) {
4862 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
4863 0, dl, SDNodeOrder);
4864 DAG.AddDbgValue(SDV, nullptr, false);
4869 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4874 case Intrinsic::dbg_value: {
4875 const DbgValueInst &DI = cast<DbgValueInst>(I);
4876 DIVariable DIVar(DI.getVariable());
4877 assert((!DIVar || DIVar.isVariable()) &&
4878 "Variable in DbgValueInst should be either null or a DIVariable.");
4882 MDNode *Variable = DI.getVariable();
4883 MDNode *Expression = DI.getExpression();
4884 uint64_t Offset = DI.getOffset();
4885 const Value *V = DI.getValue();
4890 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4891 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4893 DAG.AddDbgValue(SDV, nullptr, false);
4895 // Do not use getValue() in here; we don't want to generate code at
4896 // this point if it hasn't been done yet.
4897 SDValue N = NodeMap[V];
4898 if (!N.getNode() && isa<Argument>(V))
4899 // Check unused arguments map.
4900 N = UnusedArgNodeMap[V];
4902 // A dbg.value for an alloca is always indirect.
4903 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
4904 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, Offset,
4906 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4907 IsIndirect, Offset, dl, SDNodeOrder);
4908 DAG.AddDbgValue(SDV, N.getNode(), false);
4910 } else if (!V->use_empty() ) {
4911 // Do not call getValue(V) yet, as we don't want to generate code.
4912 // Remember it for later.
4913 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4914 DanglingDebugInfoMap[V] = DDI;
4916 // We may expand this to cover more cases. One case where we have no
4917 // data available is an unreferenced parameter.
4918 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4922 // Build a debug info table entry.
4923 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4924 V = BCI->getOperand(0);
4925 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4926 // Don't handle byval struct arguments or VLAs, for example.
4928 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4929 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
4932 DenseMap<const AllocaInst*, int>::iterator SI =
4933 FuncInfo.StaticAllocaMap.find(AI);
4934 if (SI == FuncInfo.StaticAllocaMap.end())
4935 return nullptr; // VLAs.
4939 case Intrinsic::eh_typeid_for: {
4940 // Find the type id for the given typeinfo.
4941 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
4942 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4943 Res = DAG.getConstant(TypeID, MVT::i32);
4948 case Intrinsic::eh_return_i32:
4949 case Intrinsic::eh_return_i64:
4950 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4951 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4954 getValue(I.getArgOperand(0)),
4955 getValue(I.getArgOperand(1))));
4957 case Intrinsic::eh_unwind_init:
4958 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4960 case Intrinsic::eh_dwarf_cfa: {
4961 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4962 TLI.getPointerTy());
4963 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4964 CfaArg.getValueType(),
4965 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4966 CfaArg.getValueType()),
4968 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4969 DAG.getConstant(0, TLI.getPointerTy()));
4970 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4974 case Intrinsic::eh_sjlj_callsite: {
4975 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4976 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4977 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4978 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4980 MMI.setCurrentCallSite(CI->getZExtValue());
4983 case Intrinsic::eh_sjlj_functioncontext: {
4984 // Get and store the index of the function context.
4985 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4987 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4988 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4989 MFI->setFunctionContextIndex(FI);
4992 case Intrinsic::eh_sjlj_setjmp: {
4995 Ops[1] = getValue(I.getArgOperand(0));
4996 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4997 DAG.getVTList(MVT::i32, MVT::Other), Ops);
4998 setValue(&I, Op.getValue(0));
4999 DAG.setRoot(Op.getValue(1));
5002 case Intrinsic::eh_sjlj_longjmp: {
5003 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5004 getRoot(), getValue(I.getArgOperand(0))));
5008 case Intrinsic::masked_load:
5011 case Intrinsic::masked_store:
5012 visitMaskedStore(I);
5014 case Intrinsic::x86_mmx_pslli_w:
5015 case Intrinsic::x86_mmx_pslli_d:
5016 case Intrinsic::x86_mmx_pslli_q:
5017 case Intrinsic::x86_mmx_psrli_w:
5018 case Intrinsic::x86_mmx_psrli_d:
5019 case Intrinsic::x86_mmx_psrli_q:
5020 case Intrinsic::x86_mmx_psrai_w:
5021 case Intrinsic::x86_mmx_psrai_d: {
5022 SDValue ShAmt = getValue(I.getArgOperand(1));
5023 if (isa<ConstantSDNode>(ShAmt)) {
5024 visitTargetIntrinsic(I, Intrinsic);
5027 unsigned NewIntrinsic = 0;
5028 EVT ShAmtVT = MVT::v2i32;
5029 switch (Intrinsic) {
5030 case Intrinsic::x86_mmx_pslli_w:
5031 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5033 case Intrinsic::x86_mmx_pslli_d:
5034 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5036 case Intrinsic::x86_mmx_pslli_q:
5037 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5039 case Intrinsic::x86_mmx_psrli_w:
5040 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5042 case Intrinsic::x86_mmx_psrli_d:
5043 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5045 case Intrinsic::x86_mmx_psrli_q:
5046 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5048 case Intrinsic::x86_mmx_psrai_w:
5049 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5051 case Intrinsic::x86_mmx_psrai_d:
5052 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5054 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5057 // The vector shift intrinsics with scalars uses 32b shift amounts but
5058 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5060 // We must do this early because v2i32 is not a legal type.
5063 ShOps[1] = DAG.getConstant(0, MVT::i32);
5064 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
5065 EVT DestVT = TLI.getValueType(I.getType());
5066 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5067 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5068 DAG.getConstant(NewIntrinsic, MVT::i32),
5069 getValue(I.getArgOperand(0)), ShAmt);
5073 case Intrinsic::x86_avx_vinsertf128_pd_256:
5074 case Intrinsic::x86_avx_vinsertf128_ps_256:
5075 case Intrinsic::x86_avx_vinsertf128_si_256:
5076 case Intrinsic::x86_avx2_vinserti128: {
5077 EVT DestVT = TLI.getValueType(I.getType());
5078 EVT ElVT = TLI.getValueType(I.getArgOperand(1)->getType());
5079 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
5080 ElVT.getVectorNumElements();
5082 DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
5083 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
5084 DAG.getConstant(Idx, TLI.getVectorIdxTy()));
5088 case Intrinsic::x86_avx_vextractf128_pd_256:
5089 case Intrinsic::x86_avx_vextractf128_ps_256:
5090 case Intrinsic::x86_avx_vextractf128_si_256:
5091 case Intrinsic::x86_avx2_vextracti128: {
5092 EVT DestVT = TLI.getValueType(I.getType());
5093 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
5094 DestVT.getVectorNumElements();
5095 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
5096 getValue(I.getArgOperand(0)),
5097 DAG.getConstant(Idx, TLI.getVectorIdxTy()));
5101 case Intrinsic::convertff:
5102 case Intrinsic::convertfsi:
5103 case Intrinsic::convertfui:
5104 case Intrinsic::convertsif:
5105 case Intrinsic::convertuif:
5106 case Intrinsic::convertss:
5107 case Intrinsic::convertsu:
5108 case Intrinsic::convertus:
5109 case Intrinsic::convertuu: {
5110 ISD::CvtCode Code = ISD::CVT_INVALID;
5111 switch (Intrinsic) {
5112 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5113 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
5114 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
5115 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
5116 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
5117 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
5118 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
5119 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
5120 case Intrinsic::convertus: Code = ISD::CVT_US; break;
5121 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
5123 EVT DestVT = TLI.getValueType(I.getType());
5124 const Value *Op1 = I.getArgOperand(0);
5125 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
5126 DAG.getValueType(DestVT),
5127 DAG.getValueType(getValue(Op1).getValueType()),
5128 getValue(I.getArgOperand(1)),
5129 getValue(I.getArgOperand(2)),
5134 case Intrinsic::powi:
5135 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5136 getValue(I.getArgOperand(1)), DAG));
5138 case Intrinsic::log:
5139 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5141 case Intrinsic::log2:
5142 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5144 case Intrinsic::log10:
5145 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5147 case Intrinsic::exp:
5148 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5150 case Intrinsic::exp2:
5151 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5153 case Intrinsic::pow:
5154 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5155 getValue(I.getArgOperand(1)), DAG, TLI));
5157 case Intrinsic::sqrt:
5158 case Intrinsic::fabs:
5159 case Intrinsic::sin:
5160 case Intrinsic::cos:
5161 case Intrinsic::floor:
5162 case Intrinsic::ceil:
5163 case Intrinsic::trunc:
5164 case Intrinsic::rint:
5165 case Intrinsic::nearbyint:
5166 case Intrinsic::round: {
5168 switch (Intrinsic) {
5169 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5170 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
5171 case Intrinsic::fabs: Opcode = ISD::FABS; break;
5172 case Intrinsic::sin: Opcode = ISD::FSIN; break;
5173 case Intrinsic::cos: Opcode = ISD::FCOS; break;
5174 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
5175 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
5176 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
5177 case Intrinsic::rint: Opcode = ISD::FRINT; break;
5178 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5179 case Intrinsic::round: Opcode = ISD::FROUND; break;
5182 setValue(&I, DAG.getNode(Opcode, sdl,
5183 getValue(I.getArgOperand(0)).getValueType(),
5184 getValue(I.getArgOperand(0))));
5187 case Intrinsic::minnum:
5188 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
5189 getValue(I.getArgOperand(0)).getValueType(),
5190 getValue(I.getArgOperand(0)),
5191 getValue(I.getArgOperand(1))));
5193 case Intrinsic::maxnum:
5194 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
5195 getValue(I.getArgOperand(0)).getValueType(),
5196 getValue(I.getArgOperand(0)),
5197 getValue(I.getArgOperand(1))));
5199 case Intrinsic::copysign:
5200 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5201 getValue(I.getArgOperand(0)).getValueType(),
5202 getValue(I.getArgOperand(0)),
5203 getValue(I.getArgOperand(1))));
5205 case Intrinsic::fma:
5206 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5207 getValue(I.getArgOperand(0)).getValueType(),
5208 getValue(I.getArgOperand(0)),
5209 getValue(I.getArgOperand(1)),
5210 getValue(I.getArgOperand(2))));
5212 case Intrinsic::fmuladd: {
5213 EVT VT = TLI.getValueType(I.getType());
5214 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5215 TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5216 setValue(&I, DAG.getNode(ISD::FMA, sdl,
5217 getValue(I.getArgOperand(0)).getValueType(),
5218 getValue(I.getArgOperand(0)),
5219 getValue(I.getArgOperand(1)),
5220 getValue(I.getArgOperand(2))));
5222 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5223 getValue(I.getArgOperand(0)).getValueType(),
5224 getValue(I.getArgOperand(0)),
5225 getValue(I.getArgOperand(1)));
5226 SDValue Add = DAG.getNode(ISD::FADD, sdl,
5227 getValue(I.getArgOperand(0)).getValueType(),
5229 getValue(I.getArgOperand(2)));
5234 case Intrinsic::convert_to_fp16:
5235 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5236 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5237 getValue(I.getArgOperand(0)),
5238 DAG.getTargetConstant(0, MVT::i32))));
5240 case Intrinsic::convert_from_fp16:
5242 DAG.getNode(ISD::FP_EXTEND, sdl, TLI.getValueType(I.getType()),
5243 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5244 getValue(I.getArgOperand(0)))));
5246 case Intrinsic::pcmarker: {
5247 SDValue Tmp = getValue(I.getArgOperand(0));
5248 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5251 case Intrinsic::readcyclecounter: {
5252 SDValue Op = getRoot();
5253 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5254 DAG.getVTList(MVT::i64, MVT::Other), Op);
5256 DAG.setRoot(Res.getValue(1));
5259 case Intrinsic::bswap:
5260 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5261 getValue(I.getArgOperand(0)).getValueType(),
5262 getValue(I.getArgOperand(0))));
5264 case Intrinsic::cttz: {
5265 SDValue Arg = getValue(I.getArgOperand(0));
5266 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5267 EVT Ty = Arg.getValueType();
5268 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5272 case Intrinsic::ctlz: {
5273 SDValue Arg = getValue(I.getArgOperand(0));
5274 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5275 EVT Ty = Arg.getValueType();
5276 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5280 case Intrinsic::ctpop: {
5281 SDValue Arg = getValue(I.getArgOperand(0));
5282 EVT Ty = Arg.getValueType();
5283 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5286 case Intrinsic::stacksave: {
5287 SDValue Op = getRoot();
5288 Res = DAG.getNode(ISD::STACKSAVE, sdl,
5289 DAG.getVTList(TLI.getPointerTy(), MVT::Other), Op);
5291 DAG.setRoot(Res.getValue(1));
5294 case Intrinsic::stackrestore: {
5295 Res = getValue(I.getArgOperand(0));
5296 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5299 case Intrinsic::stackprotector: {
5300 // Emit code into the DAG to store the stack guard onto the stack.
5301 MachineFunction &MF = DAG.getMachineFunction();
5302 MachineFrameInfo *MFI = MF.getFrameInfo();
5303 EVT PtrTy = TLI.getPointerTy();
5304 SDValue Src, Chain = getRoot();
5305 const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
5306 const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
5308 // See if Ptr is a bitcast. If it is, look through it and see if we can get
5309 // global variable __stack_chk_guard.
5311 if (const Operator *BC = dyn_cast<Operator>(Ptr))
5312 if (BC->getOpcode() == Instruction::BitCast)
5313 GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
5315 if (GV && TLI.useLoadStackGuardNode()) {
5316 // Emit a LOAD_STACK_GUARD node.
5317 MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
5319 MachinePointerInfo MPInfo(GV);
5320 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
5321 unsigned Flags = MachineMemOperand::MOLoad |
5322 MachineMemOperand::MOInvariant;
5323 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
5324 PtrTy.getSizeInBits() / 8,
5325 DAG.getEVTAlignment(PtrTy));
5326 Node->setMemRefs(MemRefs, MemRefs + 1);
5328 // Copy the guard value to a virtual register so that it can be
5329 // retrieved in the epilogue.
5330 Src = SDValue(Node, 0);
5331 const TargetRegisterClass *RC =
5332 TLI.getRegClassFor(Src.getSimpleValueType());
5333 unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
5335 SPDescriptor.setGuardReg(Reg);
5336 Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
5338 Src = getValue(I.getArgOperand(0)); // The guard's value.
5341 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5343 int FI = FuncInfo.StaticAllocaMap[Slot];
5344 MFI->setStackProtectorIndex(FI);
5346 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5348 // Store the stack protector onto the stack.
5349 Res = DAG.getStore(Chain, sdl, Src, FIN,
5350 MachinePointerInfo::getFixedStack(FI),
5356 case Intrinsic::objectsize: {
5357 // If we don't know by now, we're never going to know.
5358 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5360 assert(CI && "Non-constant type in __builtin_object_size?");
5362 SDValue Arg = getValue(I.getCalledValue());
5363 EVT Ty = Arg.getValueType();
5366 Res = DAG.getConstant(-1ULL, Ty);
5368 Res = DAG.getConstant(0, Ty);
5373 case Intrinsic::annotation:
5374 case Intrinsic::ptr_annotation:
5375 // Drop the intrinsic, but forward the value
5376 setValue(&I, getValue(I.getOperand(0)));
5378 case Intrinsic::assume:
5379 case Intrinsic::var_annotation:
5380 // Discard annotate attributes and assumptions
5383 case Intrinsic::init_trampoline: {
5384 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5388 Ops[1] = getValue(I.getArgOperand(0));
5389 Ops[2] = getValue(I.getArgOperand(1));
5390 Ops[3] = getValue(I.getArgOperand(2));
5391 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5392 Ops[5] = DAG.getSrcValue(F);
5394 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5399 case Intrinsic::adjust_trampoline: {
5400 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5402 getValue(I.getArgOperand(0))));
5405 case Intrinsic::gcroot:
5407 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5408 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5410 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5411 GFI->addStackRoot(FI->getIndex(), TypeMap);
5414 case Intrinsic::gcread:
5415 case Intrinsic::gcwrite:
5416 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
5417 case Intrinsic::flt_rounds:
5418 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
5421 case Intrinsic::expect: {
5422 // Just replace __builtin_expect(exp, c) with EXP.
5423 setValue(&I, getValue(I.getArgOperand(0)));
5427 case Intrinsic::debugtrap:
5428 case Intrinsic::trap: {
5429 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
5430 if (TrapFuncName.empty()) {
5431 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5432 ISD::TRAP : ISD::DEBUGTRAP;
5433 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
5436 TargetLowering::ArgListTy Args;
5438 TargetLowering::CallLoweringInfo CLI(DAG);
5439 CLI.setDebugLoc(sdl).setChain(getRoot())
5440 .setCallee(CallingConv::C, I.getType(),
5441 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
5442 std::move(Args), 0);
5444 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5445 DAG.setRoot(Result.second);
5449 case Intrinsic::uadd_with_overflow:
5450 case Intrinsic::sadd_with_overflow:
5451 case Intrinsic::usub_with_overflow:
5452 case Intrinsic::ssub_with_overflow:
5453 case Intrinsic::umul_with_overflow:
5454 case Intrinsic::smul_with_overflow: {
5456 switch (Intrinsic) {
5457 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5458 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5459 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5460 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5461 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5462 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5463 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5465 SDValue Op1 = getValue(I.getArgOperand(0));
5466 SDValue Op2 = getValue(I.getArgOperand(1));
5468 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5469 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5472 case Intrinsic::prefetch: {
5474 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5476 Ops[1] = getValue(I.getArgOperand(0));
5477 Ops[2] = getValue(I.getArgOperand(1));
5478 Ops[3] = getValue(I.getArgOperand(2));
5479 Ops[4] = getValue(I.getArgOperand(3));
5480 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5481 DAG.getVTList(MVT::Other), Ops,
5482 EVT::getIntegerVT(*Context, 8),
5483 MachinePointerInfo(I.getArgOperand(0)),
5485 false, /* volatile */
5487 rw==1)); /* write */
5490 case Intrinsic::lifetime_start:
5491 case Intrinsic::lifetime_end: {
5492 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5493 // Stack coloring is not enabled in O0, discard region information.
5494 if (TM.getOptLevel() == CodeGenOpt::None)
5497 SmallVector<Value *, 4> Allocas;
5498 GetUnderlyingObjects(I.getArgOperand(1), Allocas, DL);
5500 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5501 E = Allocas.end(); Object != E; ++Object) {
5502 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5504 // Could not find an Alloca.
5505 if (!LifetimeObject)
5508 // First check that the Alloca is static, otherwise it won't have a
5509 // valid frame index.
5510 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5511 if (SI == FuncInfo.StaticAllocaMap.end())
5514 int FI = SI->second;
5518 Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
5519 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5521 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5526 case Intrinsic::invariant_start:
5527 // Discard region information.
5528 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
5530 case Intrinsic::invariant_end:
5531 // Discard region information.
5533 case Intrinsic::stackprotectorcheck: {
5534 // Do not actually emit anything for this basic block. Instead we initialize
5535 // the stack protector descriptor and export the guard variable so we can
5536 // access it in FinishBasicBlock.
5537 const BasicBlock *BB = I.getParent();
5538 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5539 ExportFromCurrentBlock(SPDescriptor.getGuard());
5541 // Flush our exports since we are going to process a terminator.
5542 (void)getControlRoot();
5545 case Intrinsic::clear_cache:
5546 return TLI.getClearCacheBuiltinName();
5547 case Intrinsic::donothing:
5550 case Intrinsic::experimental_stackmap: {
5554 case Intrinsic::experimental_patchpoint_void:
5555 case Intrinsic::experimental_patchpoint_i64: {
5556 visitPatchpoint(&I);
5559 case Intrinsic::experimental_gc_statepoint: {
5563 case Intrinsic::experimental_gc_result_int:
5564 case Intrinsic::experimental_gc_result_float:
5565 case Intrinsic::experimental_gc_result_ptr: {
5569 case Intrinsic::experimental_gc_relocate: {
5576 std::pair<SDValue, SDValue>
5577 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5578 MachineBasicBlock *LandingPad) {
5579 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5580 MCSymbol *BeginLabel = nullptr;
5583 // Insert a label before the invoke call to mark the try range. This can be
5584 // used to detect deletion of the invoke via the MachineModuleInfo.
5585 BeginLabel = MMI.getContext().CreateTempSymbol();
5587 // For SjLj, keep track of which landing pads go with which invokes
5588 // so as to maintain the ordering of pads in the LSDA.
5589 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5590 if (CallSiteIndex) {
5591 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5592 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5594 // Now that the call site is handled, stop tracking it.
5595 MMI.setCurrentCallSite(0);
5598 // Both PendingLoads and PendingExports must be flushed here;
5599 // this call might not return.
5601 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5603 CLI.setChain(getRoot());
5606 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
5607 std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
5609 assert((CLI.IsTailCall || Result.second.getNode()) &&
5610 "Non-null chain expected with non-tail call!");
5611 assert((Result.second.getNode() || !Result.first.getNode()) &&
5612 "Null value expected with tail call!");
5614 if (!Result.second.getNode()) {
5615 // As a special case, a null chain means that a tail call has been emitted
5616 // and the DAG root is already updated.
5619 // Since there's no actual continuation from this block, nothing can be
5620 // relying on us setting vregs for them.
5621 PendingExports.clear();
5623 DAG.setRoot(Result.second);
5627 // Insert a label at the end of the invoke call to mark the try range. This
5628 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5629 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5630 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5632 // Inform MachineModuleInfo of range.
5633 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5639 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5641 MachineBasicBlock *LandingPad) {
5642 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5643 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5644 Type *RetTy = FTy->getReturnType();
5646 TargetLowering::ArgListTy Args;
5647 TargetLowering::ArgListEntry Entry;
5648 Args.reserve(CS.arg_size());
5650 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5652 const Value *V = *i;
5655 if (V->getType()->isEmptyTy())
5658 SDValue ArgNode = getValue(V);
5659 Entry.Node = ArgNode; Entry.Ty = V->getType();
5661 // Skip the first return-type Attribute to get to params.
5662 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5663 Args.push_back(Entry);
5666 // Check if target-independent constraints permit a tail call here.
5667 // Target-dependent constraints are checked within TLI->LowerCallTo.
5668 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5671 TargetLowering::CallLoweringInfo CLI(DAG);
5672 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
5673 .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5674 .setTailCall(isTailCall);
5675 std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad);
5677 if (Result.first.getNode())
5678 setValue(CS.getInstruction(), Result.first);
5681 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5682 /// value is equal or not-equal to zero.
5683 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5684 for (const User *U : V->users()) {
5685 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5686 if (IC->isEquality())
5687 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5688 if (C->isNullValue())
5690 // Unknown instruction.
5696 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5698 SelectionDAGBuilder &Builder) {
5700 // Check to see if this load can be trivially constant folded, e.g. if the
5701 // input is from a string literal.
5702 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5703 // Cast pointer to the type we really want to load.
5704 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5705 PointerType::getUnqual(LoadTy));
5707 if (const Constant *LoadCst =
5708 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5710 return Builder.getValue(LoadCst);
5713 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5714 // still constant memory, the input chain can be the entry node.
5716 bool ConstantMemory = false;
5718 // Do not serialize (non-volatile) loads of constant memory with anything.
5719 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5720 Root = Builder.DAG.getEntryNode();
5721 ConstantMemory = true;
5723 // Do not serialize non-volatile loads against each other.
5724 Root = Builder.DAG.getRoot();
5727 SDValue Ptr = Builder.getValue(PtrVal);
5728 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5729 Ptr, MachinePointerInfo(PtrVal),
5731 false /*nontemporal*/,
5732 false /*isinvariant*/, 1 /* align=1 */);
5734 if (!ConstantMemory)
5735 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5739 /// processIntegerCallValue - Record the value for an instruction that
5740 /// produces an integer result, converting the type where necessary.
5741 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5744 EVT VT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
5746 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5748 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5749 setValue(&I, Value);
5752 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5753 /// If so, return true and lower it, otherwise return false and it will be
5754 /// lowered like a normal call.
5755 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5756 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5757 if (I.getNumArgOperands() != 3)
5760 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5761 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5762 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5763 !I.getType()->isIntegerTy())
5766 const Value *Size = I.getArgOperand(2);
5767 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5768 if (CSize && CSize->getZExtValue() == 0) {
5769 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
5770 setValue(&I, DAG.getConstant(0, CallVT));
5774 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5775 std::pair<SDValue, SDValue> Res =
5776 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5777 getValue(LHS), getValue(RHS), getValue(Size),
5778 MachinePointerInfo(LHS),
5779 MachinePointerInfo(RHS));
5780 if (Res.first.getNode()) {
5781 processIntegerCallValue(I, Res.first, true);
5782 PendingLoads.push_back(Res.second);
5786 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5787 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5788 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5789 bool ActuallyDoIt = true;
5792 switch (CSize->getZExtValue()) {
5794 LoadVT = MVT::Other;
5796 ActuallyDoIt = false;
5800 LoadTy = Type::getInt16Ty(CSize->getContext());
5804 LoadTy = Type::getInt32Ty(CSize->getContext());
5808 LoadTy = Type::getInt64Ty(CSize->getContext());
5812 LoadVT = MVT::v4i32;
5813 LoadTy = Type::getInt32Ty(CSize->getContext());
5814 LoadTy = VectorType::get(LoadTy, 4);
5819 // This turns into unaligned loads. We only do this if the target natively
5820 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5821 // we'll only produce a small number of byte loads.
5823 // Require that we can find a legal MVT, and only do this if the target
5824 // supports unaligned loads of that type. Expanding into byte loads would
5826 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5827 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5828 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5829 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5830 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5831 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5832 // TODO: Check alignment of src and dest ptrs.
5833 if (!TLI.isTypeLegal(LoadVT) ||
5834 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5835 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
5836 ActuallyDoIt = false;
5840 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5841 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5843 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5845 processIntegerCallValue(I, Res, false);
5854 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5855 /// form. If so, return true and lower it, otherwise return false and it
5856 /// will be lowered like a normal call.
5857 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5858 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5859 if (I.getNumArgOperands() != 3)
5862 const Value *Src = I.getArgOperand(0);
5863 const Value *Char = I.getArgOperand(1);
5864 const Value *Length = I.getArgOperand(2);
5865 if (!Src->getType()->isPointerTy() ||
5866 !Char->getType()->isIntegerTy() ||
5867 !Length->getType()->isIntegerTy() ||
5868 !I.getType()->isPointerTy())
5871 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5872 std::pair<SDValue, SDValue> Res =
5873 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5874 getValue(Src), getValue(Char), getValue(Length),
5875 MachinePointerInfo(Src));
5876 if (Res.first.getNode()) {
5877 setValue(&I, Res.first);
5878 PendingLoads.push_back(Res.second);
5885 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5886 /// optimized form. If so, return true and lower it, otherwise return false
5887 /// and it will be lowered like a normal call.
5888 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5889 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5890 if (I.getNumArgOperands() != 2)
5893 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5894 if (!Arg0->getType()->isPointerTy() ||
5895 !Arg1->getType()->isPointerTy() ||
5896 !I.getType()->isPointerTy())
5899 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5900 std::pair<SDValue, SDValue> Res =
5901 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5902 getValue(Arg0), getValue(Arg1),
5903 MachinePointerInfo(Arg0),
5904 MachinePointerInfo(Arg1), isStpcpy);
5905 if (Res.first.getNode()) {
5906 setValue(&I, Res.first);
5907 DAG.setRoot(Res.second);
5914 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5915 /// If so, return true and lower it, otherwise return false and it will be
5916 /// lowered like a normal call.
5917 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5918 // Verify that the prototype makes sense. int strcmp(void*,void*)
5919 if (I.getNumArgOperands() != 2)
5922 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5923 if (!Arg0->getType()->isPointerTy() ||
5924 !Arg1->getType()->isPointerTy() ||
5925 !I.getType()->isIntegerTy())
5928 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5929 std::pair<SDValue, SDValue> Res =
5930 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5931 getValue(Arg0), getValue(Arg1),
5932 MachinePointerInfo(Arg0),
5933 MachinePointerInfo(Arg1));
5934 if (Res.first.getNode()) {
5935 processIntegerCallValue(I, Res.first, true);
5936 PendingLoads.push_back(Res.second);
5943 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5944 /// form. If so, return true and lower it, otherwise return false and it
5945 /// will be lowered like a normal call.
5946 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5947 // Verify that the prototype makes sense. size_t strlen(char *)
5948 if (I.getNumArgOperands() != 1)
5951 const Value *Arg0 = I.getArgOperand(0);
5952 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5955 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5956 std::pair<SDValue, SDValue> Res =
5957 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5958 getValue(Arg0), MachinePointerInfo(Arg0));
5959 if (Res.first.getNode()) {
5960 processIntegerCallValue(I, Res.first, false);
5961 PendingLoads.push_back(Res.second);
5968 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5969 /// form. If so, return true and lower it, otherwise return false and it
5970 /// will be lowered like a normal call.
5971 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5972 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5973 if (I.getNumArgOperands() != 2)
5976 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5977 if (!Arg0->getType()->isPointerTy() ||
5978 !Arg1->getType()->isIntegerTy() ||
5979 !I.getType()->isIntegerTy())
5982 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5983 std::pair<SDValue, SDValue> Res =
5984 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5985 getValue(Arg0), getValue(Arg1),
5986 MachinePointerInfo(Arg0));
5987 if (Res.first.getNode()) {
5988 processIntegerCallValue(I, Res.first, false);
5989 PendingLoads.push_back(Res.second);
5996 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5997 /// operation (as expected), translate it to an SDNode with the specified opcode
5998 /// and return true.
5999 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6001 // Sanity check that it really is a unary floating-point call.
6002 if (I.getNumArgOperands() != 1 ||
6003 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
6004 I.getType() != I.getArgOperand(0)->getType() ||
6005 !I.onlyReadsMemory())
6008 SDValue Tmp = getValue(I.getArgOperand(0));
6009 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6013 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
6014 /// operation (as expected), translate it to an SDNode with the specified opcode
6015 /// and return true.
6016 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6018 // Sanity check that it really is a binary floating-point call.
6019 if (I.getNumArgOperands() != 2 ||
6020 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
6021 I.getType() != I.getArgOperand(0)->getType() ||
6022 I.getType() != I.getArgOperand(1)->getType() ||
6023 !I.onlyReadsMemory())
6026 SDValue Tmp0 = getValue(I.getArgOperand(0));
6027 SDValue Tmp1 = getValue(I.getArgOperand(1));
6028 EVT VT = Tmp0.getValueType();
6029 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6033 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6034 // Handle inline assembly differently.
6035 if (isa<InlineAsm>(I.getCalledValue())) {
6040 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6041 ComputeUsesVAFloatArgument(I, &MMI);
6043 const char *RenameFn = nullptr;
6044 if (Function *F = I.getCalledFunction()) {
6045 if (F->isDeclaration()) {
6046 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
6047 if (unsigned IID = II->getIntrinsicID(F)) {
6048 RenameFn = visitIntrinsicCall(I, IID);
6053 if (unsigned IID = F->getIntrinsicID()) {
6054 RenameFn = visitIntrinsicCall(I, IID);
6060 // Check for well-known libc/libm calls. If the function is internal, it
6061 // can't be a library call.
6063 if (!F->hasLocalLinkage() && F->hasName() &&
6064 LibInfo->getLibFunc(F->getName(), Func) &&
6065 LibInfo->hasOptimizedCodeGen(Func)) {
6068 case LibFunc::copysign:
6069 case LibFunc::copysignf:
6070 case LibFunc::copysignl:
6071 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
6072 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
6073 I.getType() == I.getArgOperand(0)->getType() &&
6074 I.getType() == I.getArgOperand(1)->getType() &&
6075 I.onlyReadsMemory()) {
6076 SDValue LHS = getValue(I.getArgOperand(0));
6077 SDValue RHS = getValue(I.getArgOperand(1));
6078 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
6079 LHS.getValueType(), LHS, RHS));
6084 case LibFunc::fabsf:
6085 case LibFunc::fabsl:
6086 if (visitUnaryFloatCall(I, ISD::FABS))
6090 case LibFunc::fminf:
6091 case LibFunc::fminl:
6092 if (visitBinaryFloatCall(I, ISD::FMINNUM))
6096 case LibFunc::fmaxf:
6097 case LibFunc::fmaxl:
6098 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
6104 if (visitUnaryFloatCall(I, ISD::FSIN))
6110 if (visitUnaryFloatCall(I, ISD::FCOS))
6114 case LibFunc::sqrtf:
6115 case LibFunc::sqrtl:
6116 case LibFunc::sqrt_finite:
6117 case LibFunc::sqrtf_finite:
6118 case LibFunc::sqrtl_finite:
6119 if (visitUnaryFloatCall(I, ISD::FSQRT))
6122 case LibFunc::floor:
6123 case LibFunc::floorf:
6124 case LibFunc::floorl:
6125 if (visitUnaryFloatCall(I, ISD::FFLOOR))
6128 case LibFunc::nearbyint:
6129 case LibFunc::nearbyintf:
6130 case LibFunc::nearbyintl:
6131 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
6135 case LibFunc::ceilf:
6136 case LibFunc::ceill:
6137 if (visitUnaryFloatCall(I, ISD::FCEIL))
6141 case LibFunc::rintf:
6142 case LibFunc::rintl:
6143 if (visitUnaryFloatCall(I, ISD::FRINT))
6146 case LibFunc::round:
6147 case LibFunc::roundf:
6148 case LibFunc::roundl:
6149 if (visitUnaryFloatCall(I, ISD::FROUND))
6152 case LibFunc::trunc:
6153 case LibFunc::truncf:
6154 case LibFunc::truncl:
6155 if (visitUnaryFloatCall(I, ISD::FTRUNC))
6159 case LibFunc::log2f:
6160 case LibFunc::log2l:
6161 if (visitUnaryFloatCall(I, ISD::FLOG2))
6165 case LibFunc::exp2f:
6166 case LibFunc::exp2l:
6167 if (visitUnaryFloatCall(I, ISD::FEXP2))
6170 case LibFunc::memcmp:
6171 if (visitMemCmpCall(I))
6174 case LibFunc::memchr:
6175 if (visitMemChrCall(I))
6178 case LibFunc::strcpy:
6179 if (visitStrCpyCall(I, false))
6182 case LibFunc::stpcpy:
6183 if (visitStrCpyCall(I, true))
6186 case LibFunc::strcmp:
6187 if (visitStrCmpCall(I))
6190 case LibFunc::strlen:
6191 if (visitStrLenCall(I))
6194 case LibFunc::strnlen:
6195 if (visitStrNLenCall(I))
6204 Callee = getValue(I.getCalledValue());
6206 Callee = DAG.getExternalSymbol(RenameFn,
6207 DAG.getTargetLoweringInfo().getPointerTy());
6209 // Check if we can potentially perform a tail call. More detailed checking is
6210 // be done within LowerCallTo, after more information about the call is known.
6211 LowerCallTo(&I, Callee, I.isTailCall());
6216 /// AsmOperandInfo - This contains information for each constraint that we are
6218 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
6220 /// CallOperand - If this is the result output operand or a clobber
6221 /// this is null, otherwise it is the incoming operand to the CallInst.
6222 /// This gets modified as the asm is processed.
6223 SDValue CallOperand;
6225 /// AssignedRegs - If this is a register or register class operand, this
6226 /// contains the set of register corresponding to the operand.
6227 RegsForValue AssignedRegs;
6229 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
6230 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
6233 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
6234 /// corresponds to. If there is no Value* for this operand, it returns
6236 EVT getCallOperandValEVT(LLVMContext &Context,
6237 const TargetLowering &TLI,
6238 const DataLayout *DL) const {
6239 if (!CallOperandVal) return MVT::Other;
6241 if (isa<BasicBlock>(CallOperandVal))
6242 return TLI.getPointerTy();
6244 llvm::Type *OpTy = CallOperandVal->getType();
6246 // FIXME: code duplicated from TargetLowering::ParseConstraints().
6247 // If this is an indirect operand, the operand is a pointer to the
6250 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
6252 report_fatal_error("Indirect operand for inline asm not a pointer!");
6253 OpTy = PtrTy->getElementType();
6256 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
6257 if (StructType *STy = dyn_cast<StructType>(OpTy))
6258 if (STy->getNumElements() == 1)
6259 OpTy = STy->getElementType(0);
6261 // If OpTy is not a single value, it may be a struct/union that we
6262 // can tile with integers.
6263 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
6264 unsigned BitSize = DL->getTypeSizeInBits(OpTy);
6273 OpTy = IntegerType::get(Context, BitSize);
6278 return TLI.getValueType(OpTy, true);
6282 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
6284 } // end anonymous namespace
6286 /// GetRegistersForValue - Assign registers (virtual or physical) for the
6287 /// specified operand. We prefer to assign virtual registers, to allow the
6288 /// register allocator to handle the assignment process. However, if the asm
6289 /// uses features that we can't model on machineinstrs, we have SDISel do the
6290 /// allocation. This produces generally horrible, but correct, code.
6292 /// OpInfo describes the operand.
6294 static void GetRegistersForValue(SelectionDAG &DAG,
6295 const TargetLowering &TLI,
6297 SDISelAsmOperandInfo &OpInfo) {
6298 LLVMContext &Context = *DAG.getContext();
6300 MachineFunction &MF = DAG.getMachineFunction();
6301 SmallVector<unsigned, 4> Regs;
6303 // If this is a constraint for a single physreg, or a constraint for a
6304 // register class, find it.
6305 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
6306 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6307 OpInfo.ConstraintVT);
6309 unsigned NumRegs = 1;
6310 if (OpInfo.ConstraintVT != MVT::Other) {
6311 // If this is a FP input in an integer register (or visa versa) insert a bit
6312 // cast of the input value. More generally, handle any case where the input
6313 // value disagrees with the register class we plan to stick this in.
6314 if (OpInfo.Type == InlineAsm::isInput &&
6315 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
6316 // Try to convert to the first EVT that the reg class contains. If the
6317 // types are identical size, use a bitcast to convert (e.g. two differing
6319 MVT RegVT = *PhysReg.second->vt_begin();
6320 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
6321 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6322 RegVT, OpInfo.CallOperand);
6323 OpInfo.ConstraintVT = RegVT;
6324 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
6325 // If the input is a FP value and we want it in FP registers, do a
6326 // bitcast to the corresponding integer type. This turns an f64 value
6327 // into i64, which can be passed with two i32 values on a 32-bit
6329 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
6330 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
6331 RegVT, OpInfo.CallOperand);
6332 OpInfo.ConstraintVT = RegVT;
6336 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
6340 EVT ValueVT = OpInfo.ConstraintVT;
6342 // If this is a constraint for a specific physical register, like {r17},
6344 if (unsigned AssignedReg = PhysReg.first) {
6345 const TargetRegisterClass *RC = PhysReg.second;
6346 if (OpInfo.ConstraintVT == MVT::Other)
6347 ValueVT = *RC->vt_begin();
6349 // Get the actual register value type. This is important, because the user
6350 // may have asked for (e.g.) the AX register in i32 type. We need to
6351 // remember that AX is actually i16 to get the right extension.
6352 RegVT = *RC->vt_begin();
6354 // This is a explicit reference to a physical register.
6355 Regs.push_back(AssignedReg);
6357 // If this is an expanded reference, add the rest of the regs to Regs.
6359 TargetRegisterClass::iterator I = RC->begin();
6360 for (; *I != AssignedReg; ++I)
6361 assert(I != RC->end() && "Didn't find reg!");
6363 // Already added the first reg.
6365 for (; NumRegs; --NumRegs, ++I) {
6366 assert(I != RC->end() && "Ran out of registers to allocate!");
6371 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6375 // Otherwise, if this was a reference to an LLVM register class, create vregs
6376 // for this reference.
6377 if (const TargetRegisterClass *RC = PhysReg.second) {
6378 RegVT = *RC->vt_begin();
6379 if (OpInfo.ConstraintVT == MVT::Other)
6382 // Create the appropriate number of virtual registers.
6383 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6384 for (; NumRegs; --NumRegs)
6385 Regs.push_back(RegInfo.createVirtualRegister(RC));
6387 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6391 // Otherwise, we couldn't allocate enough registers for this.
6394 /// visitInlineAsm - Handle a call to an InlineAsm object.
6396 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6397 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6399 /// ConstraintOperands - Information about all of the constraints.
6400 SDISelAsmOperandInfoVector ConstraintOperands;
6402 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6403 TargetLowering::AsmOperandInfoVector
6404 TargetConstraints = TLI.ParseConstraints(CS);
6406 bool hasMemory = false;
6408 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6409 unsigned ResNo = 0; // ResNo - The result number of the next output.
6410 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6411 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6412 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6414 MVT OpVT = MVT::Other;
6416 // Compute the value type for each operand.
6417 switch (OpInfo.Type) {
6418 case InlineAsm::isOutput:
6419 // Indirect outputs just consume an argument.
6420 if (OpInfo.isIndirect) {
6421 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6425 // The return value of the call is this value. As such, there is no
6426 // corresponding argument.
6427 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6428 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6429 OpVT = TLI.getSimpleValueType(STy->getElementType(ResNo));
6431 assert(ResNo == 0 && "Asm only has one result!");
6432 OpVT = TLI.getSimpleValueType(CS.getType());
6436 case InlineAsm::isInput:
6437 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6439 case InlineAsm::isClobber:
6444 // If this is an input or an indirect output, process the call argument.
6445 // BasicBlocks are labels, currently appearing only in asm's.
6446 if (OpInfo.CallOperandVal) {
6447 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6448 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6450 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6454 OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, DL).getSimpleVT();
6457 OpInfo.ConstraintVT = OpVT;
6459 // Indirect operand accesses access memory.
6460 if (OpInfo.isIndirect)
6463 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6464 TargetLowering::ConstraintType
6465 CType = TLI.getConstraintType(OpInfo.Codes[j]);
6466 if (CType == TargetLowering::C_Memory) {
6474 SDValue Chain, Flag;
6476 // We won't need to flush pending loads if this asm doesn't touch
6477 // memory and is nonvolatile.
6478 if (hasMemory || IA->hasSideEffects())
6481 Chain = DAG.getRoot();
6483 // Second pass over the constraints: compute which constraint option to use
6484 // and assign registers to constraints that want a specific physreg.
6485 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6486 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6488 // If this is an output operand with a matching input operand, look up the
6489 // matching input. If their types mismatch, e.g. one is an integer, the
6490 // other is floating point, or their sizes are different, flag it as an
6492 if (OpInfo.hasMatchingInput()) {
6493 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6495 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6496 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
6497 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
6498 OpInfo.ConstraintVT);
6499 std::pair<unsigned, const TargetRegisterClass*> InputRC =
6500 TLI.getRegForInlineAsmConstraint(Input.ConstraintCode,
6501 Input.ConstraintVT);
6502 if ((OpInfo.ConstraintVT.isInteger() !=
6503 Input.ConstraintVT.isInteger()) ||
6504 (MatchRC.second != InputRC.second)) {
6505 report_fatal_error("Unsupported asm: input constraint"
6506 " with a matching output constraint of"
6507 " incompatible type!");
6509 Input.ConstraintVT = OpInfo.ConstraintVT;
6513 // Compute the constraint code and ConstraintType to use.
6514 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6516 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6517 OpInfo.Type == InlineAsm::isClobber)
6520 // If this is a memory input, and if the operand is not indirect, do what we
6521 // need to to provide an address for the memory input.
6522 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6523 !OpInfo.isIndirect) {
6524 assert((OpInfo.isMultipleAlternative ||
6525 (OpInfo.Type == InlineAsm::isInput)) &&
6526 "Can only indirectify direct input operands!");
6528 // Memory operands really want the address of the value. If we don't have
6529 // an indirect input, put it in the constpool if we can, otherwise spill
6530 // it to a stack slot.
6531 // TODO: This isn't quite right. We need to handle these according to
6532 // the addressing mode that the constraint wants. Also, this may take
6533 // an additional register for the computation and we don't want that
6536 // If the operand is a float, integer, or vector constant, spill to a
6537 // constant pool entry to get its address.
6538 const Value *OpVal = OpInfo.CallOperandVal;
6539 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6540 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6541 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6542 TLI.getPointerTy());
6544 // Otherwise, create a stack slot and emit a store to it before the
6546 Type *Ty = OpVal->getType();
6547 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
6548 unsigned Align = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
6549 MachineFunction &MF = DAG.getMachineFunction();
6550 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6551 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
6552 Chain = DAG.getStore(Chain, getCurSDLoc(),
6553 OpInfo.CallOperand, StackSlot,
6554 MachinePointerInfo::getFixedStack(SSFI),
6556 OpInfo.CallOperand = StackSlot;
6559 // There is no longer a Value* corresponding to this operand.
6560 OpInfo.CallOperandVal = nullptr;
6562 // It is now an indirect operand.
6563 OpInfo.isIndirect = true;
6566 // If this constraint is for a specific register, allocate it before
6568 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6569 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6572 // Second pass - Loop over all of the operands, assigning virtual or physregs
6573 // to register class operands.
6574 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6575 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6577 // C_Register operands have already been allocated, Other/Memory don't need
6579 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6580 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6583 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6584 std::vector<SDValue> AsmNodeOperands;
6585 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6586 AsmNodeOperands.push_back(
6587 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6588 TLI.getPointerTy()));
6590 // If we have a !srcloc metadata node associated with it, we want to attach
6591 // this to the ultimately generated inline asm machineinstr. To do this, we
6592 // pass in the third operand as this (potentially null) inline asm MDNode.
6593 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6594 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6596 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6597 // bits as operand 3.
6598 unsigned ExtraInfo = 0;
6599 if (IA->hasSideEffects())
6600 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6601 if (IA->isAlignStack())
6602 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6603 // Set the asm dialect.
6604 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6606 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6607 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6608 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6610 // Compute the constraint code and ConstraintType to use.
6611 TLI.ComputeConstraintToUse(OpInfo, SDValue());
6613 // Ideally, we would only check against memory constraints. However, the
6614 // meaning of an other constraint can be target-specific and we can't easily
6615 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6616 // for other constriants as well.
6617 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6618 OpInfo.ConstraintType == TargetLowering::C_Other) {
6619 if (OpInfo.Type == InlineAsm::isInput)
6620 ExtraInfo |= InlineAsm::Extra_MayLoad;
6621 else if (OpInfo.Type == InlineAsm::isOutput)
6622 ExtraInfo |= InlineAsm::Extra_MayStore;
6623 else if (OpInfo.Type == InlineAsm::isClobber)
6624 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6628 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6629 TLI.getPointerTy()));
6631 // Loop over all of the inputs, copying the operand values into the
6632 // appropriate registers and processing the output regs.
6633 RegsForValue RetValRegs;
6635 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6636 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6638 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6639 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6641 switch (OpInfo.Type) {
6642 case InlineAsm::isOutput: {
6643 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6644 OpInfo.ConstraintType != TargetLowering::C_Register) {
6645 // Memory output, or 'other' output (e.g. 'X' constraint).
6646 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6648 // Add information to the INLINEASM node to know about this output.
6649 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6650 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
6651 TLI.getPointerTy()));
6652 AsmNodeOperands.push_back(OpInfo.CallOperand);
6656 // Otherwise, this is a register or register class output.
6658 // Copy the output from the appropriate register. Find a register that
6660 if (OpInfo.AssignedRegs.Regs.empty()) {
6661 LLVMContext &Ctx = *DAG.getContext();
6662 Ctx.emitError(CS.getInstruction(),
6663 "couldn't allocate output register for constraint '" +
6664 Twine(OpInfo.ConstraintCode) + "'");
6668 // If this is an indirect operand, store through the pointer after the
6670 if (OpInfo.isIndirect) {
6671 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6672 OpInfo.CallOperandVal));
6674 // This is the result value of the call.
6675 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6676 // Concatenate this output onto the outputs list.
6677 RetValRegs.append(OpInfo.AssignedRegs);
6680 // Add information to the INLINEASM node to know that this register is
6683 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6684 ? InlineAsm::Kind_RegDefEarlyClobber
6685 : InlineAsm::Kind_RegDef,
6686 false, 0, DAG, AsmNodeOperands);
6689 case InlineAsm::isInput: {
6690 SDValue InOperandVal = OpInfo.CallOperand;
6692 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6693 // If this is required to match an output register we have already set,
6694 // just use its register.
6695 unsigned OperandNo = OpInfo.getMatchedOperand();
6697 // Scan until we find the definition we already emitted of this operand.
6698 // When we find it, create a RegsForValue operand.
6699 unsigned CurOp = InlineAsm::Op_FirstOperand;
6700 for (; OperandNo; --OperandNo) {
6701 // Advance to the next operand.
6703 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6704 assert((InlineAsm::isRegDefKind(OpFlag) ||
6705 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6706 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6707 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6711 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6712 if (InlineAsm::isRegDefKind(OpFlag) ||
6713 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6714 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6715 if (OpInfo.isIndirect) {
6716 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6717 LLVMContext &Ctx = *DAG.getContext();
6718 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6719 " don't know how to handle tied "
6720 "indirect register inputs");
6724 RegsForValue MatchedRegs;
6725 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6726 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6727 MatchedRegs.RegVTs.push_back(RegVT);
6728 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6729 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6731 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6732 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6734 LLVMContext &Ctx = *DAG.getContext();
6735 Ctx.emitError(CS.getInstruction(),
6736 "inline asm error: This value"
6737 " type register class is not natively supported!");
6741 // Use the produced MatchedRegs object to
6742 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6743 Chain, &Flag, CS.getInstruction());
6744 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6745 true, OpInfo.getMatchedOperand(),
6746 DAG, AsmNodeOperands);
6750 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6751 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6752 "Unexpected number of operands");
6753 // Add information to the INLINEASM node to know about this input.
6754 // See InlineAsm.h isUseOperandTiedToDef.
6755 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6756 OpInfo.getMatchedOperand());
6757 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6758 TLI.getPointerTy()));
6759 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6763 // Treat indirect 'X' constraint as memory.
6764 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6766 OpInfo.ConstraintType = TargetLowering::C_Memory;
6768 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6769 std::vector<SDValue> Ops;
6770 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6773 LLVMContext &Ctx = *DAG.getContext();
6774 Ctx.emitError(CS.getInstruction(),
6775 "invalid operand for inline asm constraint '" +
6776 Twine(OpInfo.ConstraintCode) + "'");
6780 // Add information to the INLINEASM node to know about this input.
6781 unsigned ResOpType =
6782 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6783 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6784 TLI.getPointerTy()));
6785 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6789 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6790 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6791 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6792 "Memory operands expect pointer values");
6794 // Add information to the INLINEASM node to know about this input.
6795 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6796 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6797 TLI.getPointerTy()));
6798 AsmNodeOperands.push_back(InOperandVal);
6802 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6803 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6804 "Unknown constraint type!");
6806 // TODO: Support this.
6807 if (OpInfo.isIndirect) {
6808 LLVMContext &Ctx = *DAG.getContext();
6809 Ctx.emitError(CS.getInstruction(),
6810 "Don't know how to handle indirect register inputs yet "
6811 "for constraint '" +
6812 Twine(OpInfo.ConstraintCode) + "'");
6816 // Copy the input into the appropriate registers.
6817 if (OpInfo.AssignedRegs.Regs.empty()) {
6818 LLVMContext &Ctx = *DAG.getContext();
6819 Ctx.emitError(CS.getInstruction(),
6820 "couldn't allocate input reg for constraint '" +
6821 Twine(OpInfo.ConstraintCode) + "'");
6825 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
6826 Chain, &Flag, CS.getInstruction());
6828 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6829 DAG, AsmNodeOperands);
6832 case InlineAsm::isClobber: {
6833 // Add the clobbered value to the operand list, so that the register
6834 // allocator is aware that the physreg got clobbered.
6835 if (!OpInfo.AssignedRegs.Regs.empty())
6836 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6844 // Finish up input operands. Set the input chain and add the flag last.
6845 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6846 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6848 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6849 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
6850 Flag = Chain.getValue(1);
6852 // If this asm returns a register value, copy the result from that register
6853 // and set it as the value of the call.
6854 if (!RetValRegs.Regs.empty()) {
6855 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6856 Chain, &Flag, CS.getInstruction());
6858 // FIXME: Why don't we do this for inline asms with MRVs?
6859 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6860 EVT ResultType = TLI.getValueType(CS.getType());
6862 // If any of the results of the inline asm is a vector, it may have the
6863 // wrong width/num elts. This can happen for register classes that can
6864 // contain multiple different value types. The preg or vreg allocated may
6865 // not have the same VT as was expected. Convert it to the right type
6866 // with bit_convert.
6867 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6868 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6871 } else if (ResultType != Val.getValueType() &&
6872 ResultType.isInteger() && Val.getValueType().isInteger()) {
6873 // If a result value was tied to an input value, the computed result may
6874 // have a wider width than the expected result. Extract the relevant
6876 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6879 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6882 setValue(CS.getInstruction(), Val);
6883 // Don't need to use this as a chain in this case.
6884 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6888 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6890 // Process indirect outputs, first output all of the flagged copies out of
6892 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6893 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6894 const Value *Ptr = IndirectStoresToEmit[i].second;
6895 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6897 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6900 // Emit the non-flagged stores from the physregs.
6901 SmallVector<SDValue, 8> OutChains;
6902 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6903 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6904 StoresToEmit[i].first,
6905 getValue(StoresToEmit[i].second),
6906 MachinePointerInfo(StoresToEmit[i].second),
6908 OutChains.push_back(Val);
6911 if (!OutChains.empty())
6912 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
6917 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6918 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6919 MVT::Other, getRoot(),
6920 getValue(I.getArgOperand(0)),
6921 DAG.getSrcValue(I.getArgOperand(0))));
6924 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6925 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6926 const DataLayout &DL = *TLI.getDataLayout();
6927 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurSDLoc(),
6928 getRoot(), getValue(I.getOperand(0)),
6929 DAG.getSrcValue(I.getOperand(0)),
6930 DL.getABITypeAlignment(I.getType()));
6932 DAG.setRoot(V.getValue(1));
6935 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6936 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6937 MVT::Other, getRoot(),
6938 getValue(I.getArgOperand(0)),
6939 DAG.getSrcValue(I.getArgOperand(0))));
6942 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6943 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6944 MVT::Other, getRoot(),
6945 getValue(I.getArgOperand(0)),
6946 getValue(I.getArgOperand(1)),
6947 DAG.getSrcValue(I.getArgOperand(0)),
6948 DAG.getSrcValue(I.getArgOperand(1))));
6951 /// \brief Lower an argument list according to the target calling convention.
6953 /// \return A tuple of <return-value, token-chain>
6955 /// This is a helper for lowering intrinsics that follow a target calling
6956 /// convention or require stack pointer adjustment. Only a subset of the
6957 /// intrinsic's operands need to participate in the calling convention.
6958 std::pair<SDValue, SDValue>
6959 SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx,
6960 unsigned NumArgs, SDValue Callee,
6962 MachineBasicBlock *LandingPad) {
6963 TargetLowering::ArgListTy Args;
6964 Args.reserve(NumArgs);
6966 // Populate the argument list.
6967 // Attributes for args start at offset 1, after the return attribute.
6968 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6969 ArgI != ArgE; ++ArgI) {
6970 const Value *V = CS->getOperand(ArgI);
6972 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6974 TargetLowering::ArgListEntry Entry;
6975 Entry.Node = getValue(V);
6976 Entry.Ty = V->getType();
6977 Entry.setAttributes(&CS, AttrI);
6978 Args.push_back(Entry);
6981 Type *retTy = UseVoidTy ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
6982 TargetLowering::CallLoweringInfo CLI(DAG);
6983 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
6984 .setCallee(CS.getCallingConv(), retTy, Callee, std::move(Args), NumArgs)
6985 .setDiscardResult(CS->use_empty());
6987 return lowerInvokable(CLI, LandingPad);
6990 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6991 /// or patchpoint target node's operand list.
6993 /// Constants are converted to TargetConstants purely as an optimization to
6994 /// avoid constant materialization and register allocation.
6996 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6997 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6998 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6999 /// address materialization and register allocation, but may also be required
7000 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
7001 /// alloca in the entry block, then the runtime may assume that the alloca's
7002 /// StackMap location can be read immediately after compilation and that the
7003 /// location is valid at any point during execution (this is similar to the
7004 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
7005 /// only available in a register, then the runtime would need to trap when
7006 /// execution reaches the StackMap in order to read the alloca's location.
7007 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
7008 SmallVectorImpl<SDValue> &Ops,
7009 SelectionDAGBuilder &Builder) {
7010 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
7011 SDValue OpVal = Builder.getValue(CS.getArgument(i));
7012 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
7014 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
7016 Builder.DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
7017 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
7018 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
7020 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
7022 Ops.push_back(OpVal);
7026 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
7027 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
7028 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
7029 // [live variables...])
7031 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
7033 SDValue Chain, InFlag, Callee, NullPtr;
7034 SmallVector<SDValue, 32> Ops;
7036 SDLoc DL = getCurSDLoc();
7037 Callee = getValue(CI.getCalledValue());
7038 NullPtr = DAG.getIntPtrConstant(0, true);
7040 // The stackmap intrinsic only records the live variables (the arguemnts
7041 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
7042 // intrinsic, this won't be lowered to a function call. This means we don't
7043 // have to worry about calling conventions and target specific lowering code.
7044 // Instead we perform the call lowering right here.
7046 // chain, flag = CALLSEQ_START(chain, 0)
7047 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
7048 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
7050 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
7051 InFlag = Chain.getValue(1);
7053 // Add the <id> and <numBytes> constants.
7054 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
7055 Ops.push_back(DAG.getTargetConstant(
7056 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
7057 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
7058 Ops.push_back(DAG.getTargetConstant(
7059 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
7061 // Push live variables for the stack map.
7062 addStackMapLiveVars(&CI, 2, Ops, *this);
7064 // We are not pushing any register mask info here on the operands list,
7065 // because the stackmap doesn't clobber anything.
7067 // Push the chain and the glue flag.
7068 Ops.push_back(Chain);
7069 Ops.push_back(InFlag);
7071 // Create the STACKMAP node.
7072 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7073 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
7074 Chain = SDValue(SM, 0);
7075 InFlag = Chain.getValue(1);
7077 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
7079 // Stackmaps don't generate values, so nothing goes into the NodeMap.
7081 // Set the root to the target-lowered call chain.
7084 // Inform the Frame Information that we have a stackmap in this function.
7085 FuncInfo.MF->getFrameInfo()->setHasStackMap();
7088 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
7089 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
7090 MachineBasicBlock *LandingPad) {
7091 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
7096 // [live variables...])
7098 CallingConv::ID CC = CS.getCallingConv();
7099 bool IsAnyRegCC = CC == CallingConv::AnyReg;
7100 bool HasDef = !CS->getType()->isVoidTy();
7101 SDValue Callee = getValue(CS->getOperand(2)); // <target>
7103 // Get the real number of arguments participating in the call <numArgs>
7104 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
7105 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
7107 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
7108 // Intrinsics include all meta-operands up to but not including CC.
7109 unsigned NumMetaOpers = PatchPointOpers::CCPos;
7110 assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
7111 "Not enough arguments provided to the patchpoint intrinsic");
7113 // For AnyRegCC the arguments are lowered later on manually.
7114 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
7115 std::pair<SDValue, SDValue> Result =
7116 lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC,
7119 SDNode *CallEnd = Result.second.getNode();
7120 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
7121 CallEnd = CallEnd->getOperand(0).getNode();
7123 /// Get a call instruction from the call sequence chain.
7124 /// Tail calls are not allowed.
7125 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
7126 "Expected a callseq node.");
7127 SDNode *Call = CallEnd->getOperand(0).getNode();
7128 bool HasGlue = Call->getGluedNode();
7130 // Replace the target specific call node with the patchable intrinsic.
7131 SmallVector<SDValue, 8> Ops;
7133 // Add the <id> and <numBytes> constants.
7134 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
7135 Ops.push_back(DAG.getTargetConstant(
7136 cast<ConstantSDNode>(IDVal)->getZExtValue(), MVT::i64));
7137 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
7138 Ops.push_back(DAG.getTargetConstant(
7139 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), MVT::i32));
7141 // Assume that the Callee is a constant address.
7142 // FIXME: handle function symbols in the future.
7144 DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue(),
7145 /*isTarget=*/true));
7147 // Adjust <numArgs> to account for any arguments that have been passed on the
7149 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
7150 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
7151 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
7152 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, MVT::i32));
7154 // Add the calling convention
7155 Ops.push_back(DAG.getTargetConstant((unsigned)CC, MVT::i32));
7157 // Add the arguments we omitted previously. The register allocator should
7158 // place these in any free register.
7160 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
7161 Ops.push_back(getValue(CS.getArgument(i)));
7163 // Push the arguments from the call instruction up to the register mask.
7164 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
7165 for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
7168 // Push live variables for the stack map.
7169 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, Ops, *this);
7171 // Push the register mask info.
7173 Ops.push_back(*(Call->op_end()-2));
7175 Ops.push_back(*(Call->op_end()-1));
7177 // Push the chain (this is originally the first operand of the call, but
7178 // becomes now the last or second to last operand).
7179 Ops.push_back(*(Call->op_begin()));
7181 // Push the glue flag (last operand).
7183 Ops.push_back(*(Call->op_end()-1));
7186 if (IsAnyRegCC && HasDef) {
7187 // Create the return types based on the intrinsic definition
7188 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7189 SmallVector<EVT, 3> ValueVTs;
7190 ComputeValueVTs(TLI, CS->getType(), ValueVTs);
7191 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
7193 // There is always a chain and a glue type at the end
7194 ValueVTs.push_back(MVT::Other);
7195 ValueVTs.push_back(MVT::Glue);
7196 NodeTys = DAG.getVTList(ValueVTs);
7198 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7200 // Replace the target specific call node with a PATCHPOINT node.
7201 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
7202 getCurSDLoc(), NodeTys, Ops);
7204 // Update the NodeMap.
7207 setValue(CS.getInstruction(), SDValue(MN, 0));
7209 setValue(CS.getInstruction(), Result.first);
7212 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
7213 // call sequence. Furthermore the location of the chain and glue can change
7214 // when the AnyReg calling convention is used and the intrinsic returns a
7216 if (IsAnyRegCC && HasDef) {
7217 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
7218 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
7219 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7221 DAG.ReplaceAllUsesWith(Call, MN);
7222 DAG.DeleteNode(Call);
7224 // Inform the Frame Information that we have a patchpoint in this function.
7225 FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
7228 /// Returns an AttributeSet representing the attributes applied to the return
7229 /// value of the given call.
7230 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
7231 SmallVector<Attribute::AttrKind, 2> Attrs;
7233 Attrs.push_back(Attribute::SExt);
7235 Attrs.push_back(Attribute::ZExt);
7237 Attrs.push_back(Attribute::InReg);
7239 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
7243 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
7244 /// implementation, which just calls LowerCall.
7245 /// FIXME: When all targets are
7246 /// migrated to using LowerCall, this hook should be integrated into SDISel.
7247 std::pair<SDValue, SDValue>
7248 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
7249 // Handle the incoming return values from the call.
7251 Type *OrigRetTy = CLI.RetTy;
7252 SmallVector<EVT, 4> RetTys;
7253 SmallVector<uint64_t, 4> Offsets;
7254 ComputeValueVTs(*this, CLI.RetTy, RetTys, &Offsets);
7256 SmallVector<ISD::OutputArg, 4> Outs;
7257 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this);
7259 bool CanLowerReturn =
7260 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
7261 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
7263 SDValue DemoteStackSlot;
7264 int DemoteStackIdx = -100;
7265 if (!CanLowerReturn) {
7266 // FIXME: equivalent assert?
7267 // assert(!CS.hasInAllocaArgument() &&
7268 // "sret demotion is incompatible with inalloca");
7269 uint64_t TySize = getDataLayout()->getTypeAllocSize(CLI.RetTy);
7270 unsigned Align = getDataLayout()->getPrefTypeAlignment(CLI.RetTy);
7271 MachineFunction &MF = CLI.DAG.getMachineFunction();
7272 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
7273 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
7275 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy());
7277 Entry.Node = DemoteStackSlot;
7278 Entry.Ty = StackSlotPtrType;
7279 Entry.isSExt = false;
7280 Entry.isZExt = false;
7281 Entry.isInReg = false;
7282 Entry.isSRet = true;
7283 Entry.isNest = false;
7284 Entry.isByVal = false;
7285 Entry.isReturned = false;
7286 Entry.Alignment = Align;
7287 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
7288 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
7290 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7292 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7293 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7294 for (unsigned i = 0; i != NumRegs; ++i) {
7295 ISD::InputArg MyFlags;
7296 MyFlags.VT = RegisterVT;
7298 MyFlags.Used = CLI.IsReturnValueUsed;
7300 MyFlags.Flags.setSExt();
7302 MyFlags.Flags.setZExt();
7304 MyFlags.Flags.setInReg();
7305 CLI.Ins.push_back(MyFlags);
7310 // Handle all of the outgoing arguments.
7312 CLI.OutVals.clear();
7313 ArgListTy &Args = CLI.getArgs();
7314 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7315 SmallVector<EVT, 4> ValueVTs;
7316 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
7317 Type *FinalType = Args[i].Ty;
7318 if (Args[i].isByVal)
7319 FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7320 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7321 FinalType, CLI.CallConv, CLI.IsVarArg);
7322 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7324 EVT VT = ValueVTs[Value];
7325 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7326 SDValue Op = SDValue(Args[i].Node.getNode(),
7327 Args[i].Node.getResNo() + Value);
7328 ISD::ArgFlagsTy Flags;
7329 unsigned OriginalAlignment = getDataLayout()->getABITypeAlignment(ArgTy);
7335 if (Args[i].isInReg)
7339 if (Args[i].isByVal)
7341 if (Args[i].isInAlloca) {
7342 Flags.setInAlloca();
7343 // Set the byval flag for CCAssignFn callbacks that don't know about
7344 // inalloca. This way we can know how many bytes we should've allocated
7345 // and how many bytes a callee cleanup function will pop. If we port
7346 // inalloca to more targets, we'll have to add custom inalloca handling
7347 // in the various CC lowering callbacks.
7350 if (Args[i].isByVal || Args[i].isInAlloca) {
7351 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7352 Type *ElementTy = Ty->getElementType();
7353 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
7354 // For ByVal, alignment should come from FE. BE will guess if this
7355 // info is not there but there are cases it cannot get right.
7356 unsigned FrameAlign;
7357 if (Args[i].Alignment)
7358 FrameAlign = Args[i].Alignment;
7360 FrameAlign = getByValTypeAlignment(ElementTy);
7361 Flags.setByValAlign(FrameAlign);
7365 if (NeedsRegBlock) {
7366 Flags.setInConsecutiveRegs();
7367 if (Value == NumValues - 1)
7368 Flags.setInConsecutiveRegsLast();
7370 Flags.setOrigAlign(OriginalAlignment);
7372 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7373 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7374 SmallVector<SDValue, 4> Parts(NumParts);
7375 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7378 ExtendKind = ISD::SIGN_EXTEND;
7379 else if (Args[i].isZExt)
7380 ExtendKind = ISD::ZERO_EXTEND;
7382 // Conservatively only handle 'returned' on non-vectors for now
7383 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7384 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7385 "unexpected use of 'returned'");
7386 // Before passing 'returned' to the target lowering code, ensure that
7387 // either the register MVT and the actual EVT are the same size or that
7388 // the return value and argument are extended in the same way; in these
7389 // cases it's safe to pass the argument register value unchanged as the
7390 // return register value (although it's at the target's option whether
7392 // TODO: allow code generation to take advantage of partially preserved
7393 // registers rather than clobbering the entire register when the
7394 // parameter extension method is not compatible with the return
7396 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7397 (ExtendKind != ISD::ANY_EXTEND &&
7398 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7399 Flags.setReturned();
7402 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7403 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
7405 for (unsigned j = 0; j != NumParts; ++j) {
7406 // if it isn't first piece, alignment must be 1
7407 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7408 i < CLI.NumFixedArgs,
7409 i, j*Parts[j].getValueType().getStoreSize());
7410 if (NumParts > 1 && j == 0)
7411 MyFlags.Flags.setSplit();
7413 MyFlags.Flags.setOrigAlign(1);
7415 CLI.Outs.push_back(MyFlags);
7416 CLI.OutVals.push_back(Parts[j]);
7421 SmallVector<SDValue, 4> InVals;
7422 CLI.Chain = LowerCall(CLI, InVals);
7424 // Verify that the target's LowerCall behaved as expected.
7425 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7426 "LowerCall didn't return a valid chain!");
7427 assert((!CLI.IsTailCall || InVals.empty()) &&
7428 "LowerCall emitted a return value for a tail call!");
7429 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7430 "LowerCall didn't emit the correct number of values!");
7432 // For a tail call, the return value is merely live-out and there aren't
7433 // any nodes in the DAG representing it. Return a special value to
7434 // indicate that a tail call has been emitted and no more Instructions
7435 // should be processed in the current block.
7436 if (CLI.IsTailCall) {
7437 CLI.DAG.setRoot(CLI.Chain);
7438 return std::make_pair(SDValue(), SDValue());
7441 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7442 assert(InVals[i].getNode() &&
7443 "LowerCall emitted a null value!");
7444 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7445 "LowerCall emitted a value with the wrong type!");
7448 SmallVector<SDValue, 4> ReturnValues;
7449 if (!CanLowerReturn) {
7450 // The instruction result is the result of loading from the
7451 // hidden sret parameter.
7452 SmallVector<EVT, 1> PVTs;
7453 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
7455 ComputeValueVTs(*this, PtrRetTy, PVTs);
7456 assert(PVTs.size() == 1 && "Pointers should fit in one register");
7457 EVT PtrVT = PVTs[0];
7459 unsigned NumValues = RetTys.size();
7460 ReturnValues.resize(NumValues);
7461 SmallVector<SDValue, 4> Chains(NumValues);
7463 for (unsigned i = 0; i < NumValues; ++i) {
7464 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7465 CLI.DAG.getConstant(Offsets[i], PtrVT));
7466 SDValue L = CLI.DAG.getLoad(
7467 RetTys[i], CLI.DL, CLI.Chain, Add,
7468 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
7470 ReturnValues[i] = L;
7471 Chains[i] = L.getValue(1);
7474 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7476 // Collect the legal value parts into potentially illegal values
7477 // that correspond to the original function's return values.
7478 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7480 AssertOp = ISD::AssertSext;
7481 else if (CLI.RetZExt)
7482 AssertOp = ISD::AssertZext;
7483 unsigned CurReg = 0;
7484 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7486 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7487 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7489 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7490 NumRegs, RegisterVT, VT, nullptr,
7495 // For a function returning void, there is no return value. We can't create
7496 // such a node, so we just return a null return value in that case. In
7497 // that case, nothing will actually look at the value.
7498 if (ReturnValues.empty())
7499 return std::make_pair(SDValue(), CLI.Chain);
7502 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7503 CLI.DAG.getVTList(RetTys), ReturnValues);
7504 return std::make_pair(Res, CLI.Chain);
7507 void TargetLowering::LowerOperationWrapper(SDNode *N,
7508 SmallVectorImpl<SDValue> &Results,
7509 SelectionDAG &DAG) const {
7510 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
7512 Results.push_back(Res);
7515 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7516 llvm_unreachable("LowerOperation not implemented for this target!");
7520 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7521 SDValue Op = getNonRegisterValue(V);
7522 assert((Op.getOpcode() != ISD::CopyFromReg ||
7523 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7524 "Copy from a reg to the same reg!");
7525 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7527 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7528 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
7529 SDValue Chain = DAG.getEntryNode();
7531 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7532 FuncInfo.PreferredExtendType.end())
7534 : FuncInfo.PreferredExtendType[V];
7535 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
7536 PendingExports.push_back(Chain);
7539 #include "llvm/CodeGen/SelectionDAGISel.h"
7541 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7542 /// entry block, return true. This includes arguments used by switches, since
7543 /// the switch may expand into multiple basic blocks.
7544 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7545 // With FastISel active, we may be splitting blocks, so force creation
7546 // of virtual registers for all non-dead arguments.
7548 return A->use_empty();
7550 const BasicBlock *Entry = A->getParent()->begin();
7551 for (const User *U : A->users())
7552 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7553 return false; // Use not in entry block.
7558 void SelectionDAGISel::LowerArguments(const Function &F) {
7559 SelectionDAG &DAG = SDB->DAG;
7560 SDLoc dl = SDB->getCurSDLoc();
7561 const DataLayout *DL = TLI->getDataLayout();
7562 SmallVector<ISD::InputArg, 16> Ins;
7564 if (!FuncInfo->CanLowerReturn) {
7565 // Put in an sret pointer parameter before all the other parameters.
7566 SmallVector<EVT, 1> ValueVTs;
7567 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7569 // NOTE: Assuming that a pointer will never break down to more than one VT
7571 ISD::ArgFlagsTy Flags;
7573 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7574 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
7575 Ins.push_back(RetArg);
7578 // Set up the incoming argument description vector.
7580 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7581 I != E; ++I, ++Idx) {
7582 SmallVector<EVT, 4> ValueVTs;
7583 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7584 bool isArgValueUsed = !I->use_empty();
7585 unsigned PartBase = 0;
7586 Type *FinalType = I->getType();
7587 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7588 FinalType = cast<PointerType>(FinalType)->getElementType();
7589 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7590 FinalType, F.getCallingConv(), F.isVarArg());
7591 for (unsigned Value = 0, NumValues = ValueVTs.size();
7592 Value != NumValues; ++Value) {
7593 EVT VT = ValueVTs[Value];
7594 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7595 ISD::ArgFlagsTy Flags;
7596 unsigned OriginalAlignment = DL->getABITypeAlignment(ArgTy);
7598 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7600 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7602 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7604 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7606 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7608 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7609 Flags.setInAlloca();
7610 // Set the byval flag for CCAssignFn callbacks that don't know about
7611 // inalloca. This way we can know how many bytes we should've allocated
7612 // and how many bytes a callee cleanup function will pop. If we port
7613 // inalloca to more targets, we'll have to add custom inalloca handling
7614 // in the various CC lowering callbacks.
7617 if (Flags.isByVal() || Flags.isInAlloca()) {
7618 PointerType *Ty = cast<PointerType>(I->getType());
7619 Type *ElementTy = Ty->getElementType();
7620 Flags.setByValSize(DL->getTypeAllocSize(ElementTy));
7621 // For ByVal, alignment should be passed from FE. BE will guess if
7622 // this info is not there but there are cases it cannot get right.
7623 unsigned FrameAlign;
7624 if (F.getParamAlignment(Idx))
7625 FrameAlign = F.getParamAlignment(Idx);
7627 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
7628 Flags.setByValAlign(FrameAlign);
7630 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7632 if (NeedsRegBlock) {
7633 Flags.setInConsecutiveRegs();
7634 if (Value == NumValues - 1)
7635 Flags.setInConsecutiveRegsLast();
7637 Flags.setOrigAlign(OriginalAlignment);
7639 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7640 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7641 for (unsigned i = 0; i != NumRegs; ++i) {
7642 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7643 Idx-1, PartBase+i*RegisterVT.getStoreSize());
7644 if (NumRegs > 1 && i == 0)
7645 MyFlags.Flags.setSplit();
7646 // if it isn't first piece, alignment must be 1
7648 MyFlags.Flags.setOrigAlign(1);
7649 Ins.push_back(MyFlags);
7651 PartBase += VT.getStoreSize();
7655 // Call the target to set up the argument values.
7656 SmallVector<SDValue, 8> InVals;
7657 SDValue NewRoot = TLI->LowerFormalArguments(
7658 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
7660 // Verify that the target's LowerFormalArguments behaved as expected.
7661 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7662 "LowerFormalArguments didn't return a valid chain!");
7663 assert(InVals.size() == Ins.size() &&
7664 "LowerFormalArguments didn't emit the correct number of values!");
7666 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7667 assert(InVals[i].getNode() &&
7668 "LowerFormalArguments emitted a null value!");
7669 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7670 "LowerFormalArguments emitted a value with the wrong type!");
7674 // Update the DAG with the new chain value resulting from argument lowering.
7675 DAG.setRoot(NewRoot);
7677 // Set up the argument values.
7680 if (!FuncInfo->CanLowerReturn) {
7681 // Create a virtual register for the sret pointer, and put in a copy
7682 // from the sret argument into it.
7683 SmallVector<EVT, 1> ValueVTs;
7684 ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
7685 MVT VT = ValueVTs[0].getSimpleVT();
7686 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7687 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7688 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7689 RegVT, VT, nullptr, AssertOp);
7691 MachineFunction& MF = SDB->DAG.getMachineFunction();
7692 MachineRegisterInfo& RegInfo = MF.getRegInfo();
7693 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7694 FuncInfo->DemoteRegister = SRetReg;
7696 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
7697 DAG.setRoot(NewRoot);
7699 // i indexes lowered arguments. Bump it past the hidden sret argument.
7700 // Idx indexes LLVM arguments. Don't touch it.
7704 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7706 SmallVector<SDValue, 4> ArgValues;
7707 SmallVector<EVT, 4> ValueVTs;
7708 ComputeValueVTs(*TLI, I->getType(), ValueVTs);
7709 unsigned NumValues = ValueVTs.size();
7711 // If this argument is unused then remember its value. It is used to generate
7712 // debugging information.
7713 if (I->use_empty() && NumValues) {
7714 SDB->setUnusedArgValue(I, InVals[i]);
7716 // Also remember any frame index for use in FastISel.
7717 if (FrameIndexSDNode *FI =
7718 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7719 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7722 for (unsigned Val = 0; Val != NumValues; ++Val) {
7723 EVT VT = ValueVTs[Val];
7724 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7725 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7727 if (!I->use_empty()) {
7728 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7729 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7730 AssertOp = ISD::AssertSext;
7731 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7732 AssertOp = ISD::AssertZext;
7734 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7735 NumParts, PartVT, VT,
7736 nullptr, AssertOp));
7742 // We don't need to do anything else for unused arguments.
7743 if (ArgValues.empty())
7746 // Note down frame index.
7747 if (FrameIndexSDNode *FI =
7748 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7749 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7751 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
7752 SDB->getCurSDLoc());
7754 SDB->setValue(I, Res);
7755 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7756 if (LoadSDNode *LNode =
7757 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7758 if (FrameIndexSDNode *FI =
7759 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7760 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7763 // If this argument is live outside of the entry block, insert a copy from
7764 // wherever we got it to the vreg that other BB's will reference it as.
7765 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7766 // If we can, though, try to skip creating an unnecessary vreg.
7767 // FIXME: This isn't very clean... it would be nice to make this more
7768 // general. It's also subtly incompatible with the hacks FastISel
7770 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7771 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7772 FuncInfo->ValueMap[I] = Reg;
7776 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
7777 FuncInfo->InitializeRegForValue(I);
7778 SDB->CopyToExportRegsIfNeeded(I);
7782 assert(i == InVals.size() && "Argument register count mismatch!");
7784 // Finally, if the target has anything special to do, allow it to do so.
7785 // FIXME: this should insert code into the DAG!
7786 EmitFunctionEntryCode();
7789 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7790 /// ensure constants are generated when needed. Remember the virtual registers
7791 /// that need to be added to the Machine PHI nodes as input. We cannot just
7792 /// directly add them, because expansion might result in multiple MBB's for one
7793 /// BB. As such, the start of the BB might correspond to a different MBB than
7797 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7798 const TerminatorInst *TI = LLVMBB->getTerminator();
7800 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7802 // Check successor nodes' PHI nodes that expect a constant to be available
7804 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7805 const BasicBlock *SuccBB = TI->getSuccessor(succ);
7806 if (!isa<PHINode>(SuccBB->begin())) continue;
7807 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7809 // If this terminator has multiple identical successors (common for
7810 // switches), only handle each succ once.
7811 if (!SuccsHandled.insert(SuccMBB).second)
7814 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7816 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7817 // nodes and Machine PHI nodes, but the incoming operands have not been
7819 for (BasicBlock::const_iterator I = SuccBB->begin();
7820 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7821 // Ignore dead phi's.
7822 if (PN->use_empty()) continue;
7825 if (PN->getType()->isEmptyTy())
7829 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7831 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7832 unsigned &RegOut = ConstantsOut[C];
7834 RegOut = FuncInfo.CreateRegs(C->getType());
7835 CopyValueToVirtualRegister(C, RegOut);
7839 DenseMap<const Value *, unsigned>::iterator I =
7840 FuncInfo.ValueMap.find(PHIOp);
7841 if (I != FuncInfo.ValueMap.end())
7844 assert(isa<AllocaInst>(PHIOp) &&
7845 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7846 "Didn't codegen value into a register!??");
7847 Reg = FuncInfo.CreateRegs(PHIOp->getType());
7848 CopyValueToVirtualRegister(PHIOp, Reg);
7852 // Remember that this register needs to added to the machine PHI node as
7853 // the input for this MBB.
7854 SmallVector<EVT, 4> ValueVTs;
7855 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7856 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
7857 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7858 EVT VT = ValueVTs[vti];
7859 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
7860 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7861 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7862 Reg += NumRegisters;
7867 ConstantsOut.clear();
7870 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7873 SelectionDAGBuilder::StackProtectorDescriptor::
7874 AddSuccessorMBB(const BasicBlock *BB,
7875 MachineBasicBlock *ParentMBB,
7877 MachineBasicBlock *SuccMBB) {
7878 // If SuccBB has not been created yet, create it.
7880 MachineFunction *MF = ParentMBB->getParent();
7881 MachineFunction::iterator BBI = ParentMBB;
7882 SuccMBB = MF->CreateMachineBasicBlock(BB);
7883 MF->insert(++BBI, SuccMBB);
7885 // Add it as a successor of ParentMBB.
7886 ParentMBB->addSuccessor(
7887 SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely));