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/TargetLibraryInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/Analysis/VectorUtils.h"
26 #include "llvm/CodeGen/FastISel.h"
27 #include "llvm/CodeGen/FunctionLoweringInfo.h"
28 #include "llvm/CodeGen/GCMetadata.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/CodeGen/StackMaps.h"
38 #include "llvm/CodeGen/WinEHFuncInfo.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DebugInfo.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/IR/Statepoint.h"
53 #include "llvm/MC/MCSymbol.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Target/TargetFrameLowering.h"
60 #include "llvm/Target/TargetInstrInfo.h"
61 #include "llvm/Target/TargetIntrinsicInfo.h"
62 #include "llvm/Target/TargetLowering.h"
63 #include "llvm/Target/TargetOptions.h"
64 #include "llvm/Target/TargetSelectionDAGInfo.h"
65 #include "llvm/Target/TargetSubtargetInfo.h"
69 #define DEBUG_TYPE "isel"
71 /// LimitFloatPrecision - Generate low-precision inline sequences for
72 /// some float libcalls (6, 8 or 12 bits).
73 static unsigned LimitFloatPrecision;
75 static cl::opt<unsigned, true>
76 LimitFPPrecision("limit-float-precision",
77 cl::desc("Generate low-precision inline sequences "
78 "for some float libcalls"),
79 cl::location(LimitFloatPrecision),
83 EnableFMFInDAG("enable-fmf-dag", cl::init(true), cl::Hidden,
84 cl::desc("Enable fast-math-flags for DAG nodes"));
86 // Limit the width of DAG chains. This is important in general to prevent
87 // DAG-based analysis from blowing up. For example, alias analysis and
88 // load clustering may not complete in reasonable time. It is difficult to
89 // recognize and avoid this situation within each individual analysis, and
90 // future analyses are likely to have the same behavior. Limiting DAG width is
91 // the safe approach and will be especially important with global DAGs.
93 // MaxParallelChains default is arbitrarily high to avoid affecting
94 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
95 // sequence over this should have been converted to llvm.memcpy by the
96 // frontend. It easy to induce this behavior with .ll code such as:
97 // %buffer = alloca [4096 x i8]
98 // %data = load [4096 x i8]* %argPtr
99 // store [4096 x i8] %data, [4096 x i8]* %buffer
100 static const unsigned MaxParallelChains = 64;
102 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
103 const SDValue *Parts, unsigned NumParts,
104 MVT PartVT, EVT ValueVT, const Value *V);
106 /// getCopyFromParts - Create a value that contains the specified legal parts
107 /// combined into the value they represent. If the parts combine to a type
108 /// larger then ValueVT then AssertOp can be used to specify whether the extra
109 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
110 /// (ISD::AssertSext).
111 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
112 const SDValue *Parts,
113 unsigned NumParts, MVT PartVT, EVT ValueVT,
115 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
116 if (ValueVT.isVector())
117 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
120 assert(NumParts > 0 && "No parts to assemble!");
121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
122 SDValue Val = Parts[0];
125 // Assemble the value from multiple parts.
126 if (ValueVT.isInteger()) {
127 unsigned PartBits = PartVT.getSizeInBits();
128 unsigned ValueBits = ValueVT.getSizeInBits();
130 // Assemble the power of 2 part.
131 unsigned RoundParts = NumParts & (NumParts - 1) ?
132 1 << Log2_32(NumParts) : NumParts;
133 unsigned RoundBits = PartBits * RoundParts;
134 EVT RoundVT = RoundBits == ValueBits ?
135 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
138 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
140 if (RoundParts > 2) {
141 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
143 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
144 RoundParts / 2, PartVT, HalfVT, V);
146 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
147 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
150 if (DAG.getDataLayout().isBigEndian())
153 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
155 if (RoundParts < NumParts) {
156 // Assemble the trailing non-power-of-2 part.
157 unsigned OddParts = NumParts - RoundParts;
158 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
159 Hi = getCopyFromParts(DAG, DL,
160 Parts + RoundParts, OddParts, PartVT, OddVT, V);
162 // Combine the round and odd parts.
164 if (DAG.getDataLayout().isBigEndian())
166 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
167 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
169 DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
170 DAG.getConstant(Lo.getValueType().getSizeInBits(), DL,
171 TLI.getPointerTy(DAG.getDataLayout())));
172 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
173 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
175 } else if (PartVT.isFloatingPoint()) {
176 // FP split into multiple FP parts (for ppcf128)
177 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
180 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
181 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
182 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
184 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
186 // FP split into integer parts (soft fp)
187 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
188 !PartVT.isVector() && "Unexpected split");
189 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
190 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
194 // There is now one part, held in Val. Correct it to match ValueVT.
195 EVT PartEVT = Val.getValueType();
197 if (PartEVT == ValueVT)
200 if (PartEVT.isInteger() && ValueVT.isInteger()) {
201 if (ValueVT.bitsLT(PartEVT)) {
202 // For a truncate, see if we have any information to
203 // indicate whether the truncated bits will always be
204 // zero or sign-extension.
205 if (AssertOp != ISD::DELETED_NODE)
206 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
207 DAG.getValueType(ValueVT));
208 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
210 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
213 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
214 // FP_ROUND's are always exact here.
215 if (ValueVT.bitsLT(Val.getValueType()))
217 ISD::FP_ROUND, DL, ValueVT, Val,
218 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
220 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
223 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
224 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
226 llvm_unreachable("Unknown mismatch!");
229 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
230 const Twine &ErrMsg) {
231 const Instruction *I = dyn_cast_or_null<Instruction>(V);
233 return Ctx.emitError(ErrMsg);
235 const char *AsmError = ", possible invalid constraint for vector type";
236 if (const CallInst *CI = dyn_cast<CallInst>(I))
237 if (isa<InlineAsm>(CI->getCalledValue()))
238 return Ctx.emitError(I, ErrMsg + AsmError);
240 return Ctx.emitError(I, ErrMsg);
243 /// getCopyFromPartsVector - Create a value that contains the specified legal
244 /// parts combined into the value they represent. If the parts combine to a
245 /// type larger then ValueVT then AssertOp can be used to specify whether the
246 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
247 /// ValueVT (ISD::AssertSext).
248 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
249 const SDValue *Parts, unsigned NumParts,
250 MVT PartVT, EVT ValueVT, const Value *V) {
251 assert(ValueVT.isVector() && "Not a vector value");
252 assert(NumParts > 0 && "No parts to assemble!");
253 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
254 SDValue Val = Parts[0];
256 // Handle a multi-element vector.
260 unsigned NumIntermediates;
262 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
263 NumIntermediates, RegisterVT);
264 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
265 NumParts = NumRegs; // Silence a compiler warning.
266 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
267 assert(RegisterVT.getSizeInBits() ==
268 Parts[0].getSimpleValueType().getSizeInBits() &&
269 "Part type sizes don't match!");
271 // Assemble the parts into intermediate operands.
272 SmallVector<SDValue, 8> Ops(NumIntermediates);
273 if (NumIntermediates == NumParts) {
274 // If the register was not expanded, truncate or copy the value,
276 for (unsigned i = 0; i != NumParts; ++i)
277 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
278 PartVT, IntermediateVT, V);
279 } else if (NumParts > 0) {
280 // If the intermediate type was expanded, build the intermediate
281 // operands from the parts.
282 assert(NumParts % NumIntermediates == 0 &&
283 "Must expand into a divisible number of parts!");
284 unsigned Factor = NumParts / NumIntermediates;
285 for (unsigned i = 0; i != NumIntermediates; ++i)
286 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
287 PartVT, IntermediateVT, V);
290 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
291 // intermediate operands.
292 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
297 // There is now one part, held in Val. Correct it to match ValueVT.
298 EVT PartEVT = Val.getValueType();
300 if (PartEVT == ValueVT)
303 if (PartEVT.isVector()) {
304 // If the element type of the source/dest vectors are the same, but the
305 // parts vector has more elements than the value vector, then we have a
306 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
308 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
309 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
310 "Cannot narrow, it would be a lossy transformation");
312 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
313 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
316 // Vector/Vector bitcast.
317 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
318 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
320 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
321 "Cannot handle this kind of promotion");
322 // Promoted vector extract
323 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
327 // Trivial bitcast if the types are the same size and the destination
328 // vector type is legal.
329 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
330 TLI.isTypeLegal(ValueVT))
331 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
333 // Handle cases such as i8 -> <1 x i1>
334 if (ValueVT.getVectorNumElements() != 1) {
335 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
336 "non-trivial scalar-to-vector conversion");
337 return DAG.getUNDEF(ValueVT);
340 if (ValueVT.getVectorNumElements() == 1 &&
341 ValueVT.getVectorElementType() != PartEVT)
342 Val = DAG.getAnyExtOrTrunc(Val, DL, ValueVT.getScalarType());
344 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
347 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
348 SDValue Val, SDValue *Parts, unsigned NumParts,
349 MVT PartVT, const Value *V);
351 /// getCopyToParts - Create a series of nodes that contain the specified value
352 /// split into legal parts. If the parts contain more bits than Val, then, for
353 /// integers, ExtendKind can be used to specify how to generate the extra bits.
354 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
355 SDValue Val, SDValue *Parts, unsigned NumParts,
356 MVT PartVT, const Value *V,
357 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
358 EVT ValueVT = Val.getValueType();
360 // Handle the vector case separately.
361 if (ValueVT.isVector())
362 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
364 unsigned PartBits = PartVT.getSizeInBits();
365 unsigned OrigNumParts = NumParts;
366 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
367 "Copying to an illegal type!");
372 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
373 EVT PartEVT = PartVT;
374 if (PartEVT == ValueVT) {
375 assert(NumParts == 1 && "No-op copy with multiple parts!");
380 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
381 // If the parts cover more bits than the value has, promote the value.
382 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
383 assert(NumParts == 1 && "Do not know what to promote to!");
384 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
386 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
387 ValueVT.isInteger() &&
388 "Unknown mismatch!");
389 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
390 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
391 if (PartVT == MVT::x86mmx)
392 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
394 } else if (PartBits == ValueVT.getSizeInBits()) {
395 // Different types of the same size.
396 assert(NumParts == 1 && PartEVT != ValueVT);
397 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
398 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
399 // If the parts cover less bits than value has, truncate the value.
400 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
401 ValueVT.isInteger() &&
402 "Unknown mismatch!");
403 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
404 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
405 if (PartVT == MVT::x86mmx)
406 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
409 // The value may have changed - recompute ValueVT.
410 ValueVT = Val.getValueType();
411 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
412 "Failed to tile the value with PartVT!");
415 if (PartEVT != ValueVT)
416 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
417 "scalar-to-vector conversion failed");
423 // Expand the value into multiple parts.
424 if (NumParts & (NumParts - 1)) {
425 // The number of parts is not a power of 2. Split off and copy the tail.
426 assert(PartVT.isInteger() && ValueVT.isInteger() &&
427 "Do not know what to expand to!");
428 unsigned RoundParts = 1 << Log2_32(NumParts);
429 unsigned RoundBits = RoundParts * PartBits;
430 unsigned OddParts = NumParts - RoundParts;
431 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
432 DAG.getIntPtrConstant(RoundBits, DL));
433 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
435 if (DAG.getDataLayout().isBigEndian())
436 // The odd parts were reversed by getCopyToParts - unreverse them.
437 std::reverse(Parts + RoundParts, Parts + NumParts);
439 NumParts = RoundParts;
440 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
441 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
444 // The number of parts is a power of 2. Repeatedly bisect the value using
446 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
447 EVT::getIntegerVT(*DAG.getContext(),
448 ValueVT.getSizeInBits()),
451 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
452 for (unsigned i = 0; i < NumParts; i += StepSize) {
453 unsigned ThisBits = StepSize * PartBits / 2;
454 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
455 SDValue &Part0 = Parts[i];
456 SDValue &Part1 = Parts[i+StepSize/2];
458 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
459 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
460 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
461 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
463 if (ThisBits == PartBits && ThisVT != PartVT) {
464 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
465 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
470 if (DAG.getDataLayout().isBigEndian())
471 std::reverse(Parts, Parts + OrigNumParts);
475 /// getCopyToPartsVector - Create a series of nodes that contain the specified
476 /// value split into legal parts.
477 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
478 SDValue Val, SDValue *Parts, unsigned NumParts,
479 MVT PartVT, const Value *V) {
480 EVT ValueVT = Val.getValueType();
481 assert(ValueVT.isVector() && "Not a vector");
482 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
485 EVT PartEVT = PartVT;
486 if (PartEVT == ValueVT) {
488 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
489 // Bitconvert vector->vector case.
490 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
491 } else if (PartVT.isVector() &&
492 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
493 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
494 EVT ElementVT = PartVT.getVectorElementType();
495 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
497 SmallVector<SDValue, 16> Ops;
498 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
499 Ops.push_back(DAG.getNode(
500 ISD::EXTRACT_VECTOR_ELT, DL, ElementVT, Val,
501 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
503 for (unsigned i = ValueVT.getVectorNumElements(),
504 e = PartVT.getVectorNumElements(); i != e; ++i)
505 Ops.push_back(DAG.getUNDEF(ElementVT));
507 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
509 // FIXME: Use CONCAT for 2x -> 4x.
511 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
512 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
513 } else if (PartVT.isVector() &&
514 PartEVT.getVectorElementType().bitsGE(
515 ValueVT.getVectorElementType()) &&
516 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
518 // Promoted vector extract
519 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
521 // Vector -> scalar conversion.
522 assert(ValueVT.getVectorNumElements() == 1 &&
523 "Only trivial vector-to-scalar conversions should get here!");
525 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
526 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
528 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
535 // Handle a multi-element vector.
538 unsigned NumIntermediates;
539 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
541 NumIntermediates, RegisterVT);
542 unsigned NumElements = ValueVT.getVectorNumElements();
544 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
545 NumParts = NumRegs; // Silence a compiler warning.
546 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
548 // Split the vector into intermediate operands.
549 SmallVector<SDValue, 8> Ops(NumIntermediates);
550 for (unsigned i = 0; i != NumIntermediates; ++i) {
551 if (IntermediateVT.isVector())
553 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
554 DAG.getConstant(i * (NumElements / NumIntermediates), DL,
555 TLI.getVectorIdxTy(DAG.getDataLayout())));
557 Ops[i] = DAG.getNode(
558 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
559 DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
562 // Split the intermediate operands into legal parts.
563 if (NumParts == NumIntermediates) {
564 // If the register was not expanded, promote or copy the value,
566 for (unsigned i = 0; i != NumParts; ++i)
567 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
568 } else if (NumParts > 0) {
569 // If the intermediate type was expanded, split each the value into
571 assert(NumIntermediates != 0 && "division by zero");
572 assert(NumParts % NumIntermediates == 0 &&
573 "Must expand into a divisible number of parts!");
574 unsigned Factor = NumParts / NumIntermediates;
575 for (unsigned i = 0; i != NumIntermediates; ++i)
576 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
580 RegsForValue::RegsForValue() {}
582 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt,
584 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
586 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
587 const DataLayout &DL, unsigned Reg, Type *Ty) {
588 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
590 for (EVT ValueVT : ValueVTs) {
591 unsigned NumRegs = TLI.getNumRegisters(Context, ValueVT);
592 MVT RegisterVT = TLI.getRegisterType(Context, ValueVT);
593 for (unsigned i = 0; i != NumRegs; ++i)
594 Regs.push_back(Reg + i);
595 RegVTs.push_back(RegisterVT);
600 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
601 /// this value and returns the result as a ValueVT value. This uses
602 /// Chain/Flag as the input and updates them for the output Chain/Flag.
603 /// If the Flag pointer is NULL, no flag is used.
604 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
605 FunctionLoweringInfo &FuncInfo,
607 SDValue &Chain, SDValue *Flag,
608 const Value *V) const {
609 // A Value with type {} or [0 x %t] needs no registers.
610 if (ValueVTs.empty())
613 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
615 // Assemble the legal parts into the final values.
616 SmallVector<SDValue, 4> Values(ValueVTs.size());
617 SmallVector<SDValue, 8> Parts;
618 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
619 // Copy the legal parts from the registers.
620 EVT ValueVT = ValueVTs[Value];
621 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
622 MVT RegisterVT = RegVTs[Value];
624 Parts.resize(NumRegs);
625 for (unsigned i = 0; i != NumRegs; ++i) {
628 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
630 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
631 *Flag = P.getValue(2);
634 Chain = P.getValue(1);
637 // If the source register was virtual and if we know something about it,
638 // add an assert node.
639 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
640 !RegisterVT.isInteger() || RegisterVT.isVector())
643 const FunctionLoweringInfo::LiveOutInfo *LOI =
644 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
648 unsigned RegSize = RegisterVT.getSizeInBits();
649 unsigned NumSignBits = LOI->NumSignBits;
650 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
652 if (NumZeroBits == RegSize) {
653 // The current value is a zero.
654 // Explicitly express that as it would be easier for
655 // optimizations to kick in.
656 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
660 // FIXME: We capture more information than the dag can represent. For
661 // now, just use the tightest assertzext/assertsext possible.
663 EVT FromVT(MVT::Other);
664 if (NumSignBits == RegSize)
665 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
666 else if (NumZeroBits >= RegSize-1)
667 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
668 else if (NumSignBits > RegSize-8)
669 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
670 else if (NumZeroBits >= RegSize-8)
671 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
672 else if (NumSignBits > RegSize-16)
673 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
674 else if (NumZeroBits >= RegSize-16)
675 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
676 else if (NumSignBits > RegSize-32)
677 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
678 else if (NumZeroBits >= RegSize-32)
679 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
683 // Add an assertion node.
684 assert(FromVT != MVT::Other);
685 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
686 RegisterVT, P, DAG.getValueType(FromVT));
689 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
690 NumRegs, RegisterVT, ValueVT, V);
695 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
698 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
699 /// specified value into the registers specified by this object. This uses
700 /// Chain/Flag as the input and updates them for the output Chain/Flag.
701 /// If the Flag pointer is NULL, no flag is used.
702 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
703 SDValue &Chain, SDValue *Flag, const Value *V,
704 ISD::NodeType PreferredExtendType) const {
705 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
706 ISD::NodeType ExtendKind = PreferredExtendType;
708 // Get the list of the values's legal parts.
709 unsigned NumRegs = Regs.size();
710 SmallVector<SDValue, 8> Parts(NumRegs);
711 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
712 EVT ValueVT = ValueVTs[Value];
713 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
714 MVT RegisterVT = RegVTs[Value];
716 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
717 ExtendKind = ISD::ZERO_EXTEND;
719 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
720 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
724 // Copy the parts into the registers.
725 SmallVector<SDValue, 8> Chains(NumRegs);
726 for (unsigned i = 0; i != NumRegs; ++i) {
729 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
731 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
732 *Flag = Part.getValue(1);
735 Chains[i] = Part.getValue(0);
738 if (NumRegs == 1 || Flag)
739 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
740 // flagged to it. That is the CopyToReg nodes and the user are considered
741 // a single scheduling unit. If we create a TokenFactor and return it as
742 // chain, then the TokenFactor is both a predecessor (operand) of the
743 // user as well as a successor (the TF operands are flagged to the user).
744 // c1, f1 = CopyToReg
745 // c2, f2 = CopyToReg
746 // c3 = TokenFactor c1, c2
749 Chain = Chains[NumRegs-1];
751 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
754 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
755 /// operand list. This adds the code marker and includes the number of
756 /// values added into it.
757 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
758 unsigned MatchingIdx, SDLoc dl,
760 std::vector<SDValue> &Ops) const {
761 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
763 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
765 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
766 else if (!Regs.empty() &&
767 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
768 // Put the register class of the virtual registers in the flag word. That
769 // way, later passes can recompute register class constraints for inline
770 // assembly as well as normal instructions.
771 // Don't do this for tied operands that can use the regclass information
773 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
774 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
775 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
778 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
781 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
782 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
783 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
784 MVT RegisterVT = RegVTs[Value];
785 for (unsigned i = 0; i != NumRegs; ++i) {
786 assert(Reg < Regs.size() && "Mismatch in # registers expected");
787 unsigned TheReg = Regs[Reg++];
788 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
790 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
791 // If we clobbered the stack pointer, MFI should know about it.
792 assert(DAG.getMachineFunction().getFrameInfo()->
793 hasOpaqueSPAdjustment());
799 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
800 const TargetLibraryInfo *li) {
804 DL = &DAG.getDataLayout();
805 Context = DAG.getContext();
806 LPadToCallSiteMap.clear();
809 /// clear - Clear out the current SelectionDAG and the associated
810 /// state and prepare this SelectionDAGBuilder object to be used
811 /// for a new block. This doesn't clear out information about
812 /// additional blocks that are needed to complete switch lowering
813 /// or PHI node updating; that information is cleared out as it is
815 void SelectionDAGBuilder::clear() {
817 UnusedArgNodeMap.clear();
818 PendingLoads.clear();
819 PendingExports.clear();
822 SDNodeOrder = LowestSDNodeOrder;
823 StatepointLowering.clear();
826 /// clearDanglingDebugInfo - Clear the dangling debug information
827 /// map. This function is separated from the clear so that debug
828 /// information that is dangling in a basic block can be properly
829 /// resolved in a different basic block. This allows the
830 /// SelectionDAG to resolve dangling debug information attached
832 void SelectionDAGBuilder::clearDanglingDebugInfo() {
833 DanglingDebugInfoMap.clear();
836 /// getRoot - Return the current virtual root of the Selection DAG,
837 /// flushing any PendingLoad items. This must be done before emitting
838 /// a store or any other node that may need to be ordered after any
839 /// prior load instructions.
841 SDValue SelectionDAGBuilder::getRoot() {
842 if (PendingLoads.empty())
843 return DAG.getRoot();
845 if (PendingLoads.size() == 1) {
846 SDValue Root = PendingLoads[0];
848 PendingLoads.clear();
852 // Otherwise, we have to make a token factor node.
853 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
855 PendingLoads.clear();
860 /// getControlRoot - Similar to getRoot, but instead of flushing all the
861 /// PendingLoad items, flush all the PendingExports items. It is necessary
862 /// to do this before emitting a terminator instruction.
864 SDValue SelectionDAGBuilder::getControlRoot() {
865 SDValue Root = DAG.getRoot();
867 if (PendingExports.empty())
870 // Turn all of the CopyToReg chains into one factored node.
871 if (Root.getOpcode() != ISD::EntryToken) {
872 unsigned i = 0, e = PendingExports.size();
873 for (; i != e; ++i) {
874 assert(PendingExports[i].getNode()->getNumOperands() > 1);
875 if (PendingExports[i].getNode()->getOperand(0) == Root)
876 break; // Don't add the root if we already indirectly depend on it.
880 PendingExports.push_back(Root);
883 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
885 PendingExports.clear();
890 void SelectionDAGBuilder::visit(const Instruction &I) {
891 // Set up outgoing PHI node register values before emitting the terminator.
892 if (isa<TerminatorInst>(&I))
893 HandlePHINodesInSuccessorBlocks(I.getParent());
899 visit(I.getOpcode(), I);
901 if (!isa<TerminatorInst>(&I) && !HasTailCall)
902 CopyToExportRegsIfNeeded(&I);
907 void SelectionDAGBuilder::visitPHI(const PHINode &) {
908 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
911 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
912 // Note: this doesn't use InstVisitor, because it has to work with
913 // ConstantExpr's in addition to instructions.
915 default: llvm_unreachable("Unknown instruction type encountered!");
916 // Build the switch statement using the Instruction.def file.
917 #define HANDLE_INST(NUM, OPCODE, CLASS) \
918 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
919 #include "llvm/IR/Instruction.def"
923 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
924 // generate the debug data structures now that we've seen its definition.
925 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
927 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
929 const DbgValueInst *DI = DDI.getDI();
930 DebugLoc dl = DDI.getdl();
931 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
932 DILocalVariable *Variable = DI->getVariable();
933 DIExpression *Expr = DI->getExpression();
934 assert(Variable->isValidLocationForIntrinsic(dl) &&
935 "Expected inlined-at fields to agree");
936 uint64_t Offset = DI->getOffset();
937 // A dbg.value for an alloca is always indirect.
938 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
941 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, IsIndirect,
943 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
944 IsIndirect, Offset, dl, DbgSDNodeOrder);
945 DAG.AddDbgValue(SDV, Val.getNode(), false);
948 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
949 DanglingDebugInfoMap[V] = DanglingDebugInfo();
953 /// getCopyFromRegs - If there was virtual register allocated for the value V
954 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
955 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
956 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
959 if (It != FuncInfo.ValueMap.end()) {
960 unsigned InReg = It->second;
961 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
962 DAG.getDataLayout(), InReg, Ty);
963 SDValue Chain = DAG.getEntryNode();
964 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
965 resolveDanglingDebugInfo(V, Result);
971 /// getValue - Return an SDValue for the given Value.
972 SDValue SelectionDAGBuilder::getValue(const Value *V) {
973 // If we already have an SDValue for this value, use it. It's important
974 // to do this first, so that we don't create a CopyFromReg if we already
975 // have a regular SDValue.
976 SDValue &N = NodeMap[V];
977 if (N.getNode()) return N;
979 // If there's a virtual register allocated and initialized for this
981 SDValue copyFromReg = getCopyFromRegs(V, V->getType());
982 if (copyFromReg.getNode()) {
986 // Otherwise create a new SDValue and remember it.
987 SDValue Val = getValueImpl(V);
989 resolveDanglingDebugInfo(V, Val);
993 // Return true if SDValue exists for the given Value
994 bool SelectionDAGBuilder::findValue(const Value *V) const {
995 return (NodeMap.find(V) != NodeMap.end()) ||
996 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
999 /// getNonRegisterValue - Return an SDValue for the given Value, but
1000 /// don't look in FuncInfo.ValueMap for a virtual register.
1001 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1002 // If we already have an SDValue for this value, use it.
1003 SDValue &N = NodeMap[V];
1005 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1006 // Remove the debug location from the node as the node is about to be used
1007 // in a location which may differ from the original debug location. This
1008 // is relevant to Constant and ConstantFP nodes because they can appear
1009 // as constant expressions inside PHI nodes.
1010 N->setDebugLoc(DebugLoc());
1015 // Otherwise create a new SDValue and remember it.
1016 SDValue Val = getValueImpl(V);
1018 resolveDanglingDebugInfo(V, Val);
1022 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1023 /// Create an SDValue for the given value.
1024 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1025 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1027 if (const Constant *C = dyn_cast<Constant>(V)) {
1028 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1030 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1031 return DAG.getConstant(*CI, getCurSDLoc(), VT);
1033 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1034 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1036 if (isa<ConstantPointerNull>(C)) {
1037 unsigned AS = V->getType()->getPointerAddressSpace();
1038 return DAG.getConstant(0, getCurSDLoc(),
1039 TLI.getPointerTy(DAG.getDataLayout(), AS));
1042 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1043 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1045 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1046 return DAG.getUNDEF(VT);
1048 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1049 visit(CE->getOpcode(), *CE);
1050 SDValue N1 = NodeMap[V];
1051 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1055 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1056 SmallVector<SDValue, 4> Constants;
1057 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1059 SDNode *Val = getValue(*OI).getNode();
1060 // If the operand is an empty aggregate, there are no values.
1062 // Add each leaf value from the operand to the Constants list
1063 // to form a flattened list of all the values.
1064 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1065 Constants.push_back(SDValue(Val, i));
1068 return DAG.getMergeValues(Constants, getCurSDLoc());
1071 if (const ConstantDataSequential *CDS =
1072 dyn_cast<ConstantDataSequential>(C)) {
1073 SmallVector<SDValue, 4> Ops;
1074 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1075 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1076 // Add each leaf value from the operand to the Constants list
1077 // to form a flattened list of all the values.
1078 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1079 Ops.push_back(SDValue(Val, i));
1082 if (isa<ArrayType>(CDS->getType()))
1083 return DAG.getMergeValues(Ops, getCurSDLoc());
1084 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1088 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1089 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1090 "Unknown struct or array constant!");
1092 SmallVector<EVT, 4> ValueVTs;
1093 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1094 unsigned NumElts = ValueVTs.size();
1096 return SDValue(); // empty struct
1097 SmallVector<SDValue, 4> Constants(NumElts);
1098 for (unsigned i = 0; i != NumElts; ++i) {
1099 EVT EltVT = ValueVTs[i];
1100 if (isa<UndefValue>(C))
1101 Constants[i] = DAG.getUNDEF(EltVT);
1102 else if (EltVT.isFloatingPoint())
1103 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1105 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1108 return DAG.getMergeValues(Constants, getCurSDLoc());
1111 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1112 return DAG.getBlockAddress(BA, VT);
1114 VectorType *VecTy = cast<VectorType>(V->getType());
1115 unsigned NumElements = VecTy->getNumElements();
1117 // Now that we know the number and type of the elements, get that number of
1118 // elements into the Ops array based on what kind of constant it is.
1119 SmallVector<SDValue, 16> Ops;
1120 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1121 for (unsigned i = 0; i != NumElements; ++i)
1122 Ops.push_back(getValue(CV->getOperand(i)));
1124 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1126 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1129 if (EltVT.isFloatingPoint())
1130 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1132 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1133 Ops.assign(NumElements, Op);
1136 // Create a BUILD_VECTOR node.
1137 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1140 // If this is a static alloca, generate it as the frameindex instead of
1142 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1143 DenseMap<const AllocaInst*, int>::iterator SI =
1144 FuncInfo.StaticAllocaMap.find(AI);
1145 if (SI != FuncInfo.StaticAllocaMap.end())
1146 return DAG.getFrameIndex(SI->second,
1147 TLI.getPointerTy(DAG.getDataLayout()));
1150 // If this is an instruction which fast-isel has deferred, select it now.
1151 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1152 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1153 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1155 SDValue Chain = DAG.getEntryNode();
1156 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1159 llvm_unreachable("Can't get register for value!");
1162 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1163 llvm_unreachable("should never codegen catchpads");
1166 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1167 // Update machine-CFG edge.
1168 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1169 FuncInfo.MBB->addSuccessor(TargetMBB);
1171 // Figure out the funclet membership for the catchret's successor.
1172 // This will be used by the FuncletLayout pass to determine how to order the
1174 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
1175 WinEHFuncInfo &EHInfo =
1176 MMI.getWinEHFuncInfo(DAG.getMachineFunction().getFunction());
1177 const BasicBlock *SuccessorColor = EHInfo.CatchRetSuccessorColorMap[&I];
1178 assert(SuccessorColor && "No parent funclet for catchret!");
1179 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1180 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1182 // Create the terminator node.
1183 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1184 getControlRoot(), DAG.getBasicBlock(TargetMBB),
1185 DAG.getBasicBlock(SuccessorColorMBB));
1189 void SelectionDAGBuilder::visitCatchEndPad(const CatchEndPadInst &I) {
1190 llvm_unreachable("should never codegen catchendpads");
1193 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1194 // Don't emit any special code for the cleanuppad instruction. It just marks
1195 // the start of a funclet.
1196 FuncInfo.MBB->setIsEHFuncletEntry();
1197 FuncInfo.MBB->setIsCleanupFuncletEntry();
1200 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1201 /// many places it could ultimately go. In the IR, we have a single unwind
1202 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1203 /// This function skips over imaginary basic blocks that hold catchpad,
1204 /// terminatepad, or catchendpad instructions, and finds all the "real" machine
1205 /// basic block destinations.
1207 findUnwindDestinations(FunctionLoweringInfo &FuncInfo,
1208 const BasicBlock *EHPadBB,
1209 SmallVectorImpl<MachineBasicBlock *> &UnwindDests) {
1210 bool IsMSVCCXX = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn()) ==
1211 EHPersonality::MSVC_CXX;
1213 const Instruction *Pad = EHPadBB->getFirstNonPHI();
1214 if (isa<LandingPadInst>(Pad)) {
1215 // Stop on landingpads. They are not funclets.
1216 UnwindDests.push_back(FuncInfo.MBBMap[EHPadBB]);
1218 } else if (isa<CleanupPadInst>(Pad) || isa<LandingPadInst>(Pad)) {
1219 // Stop on cleanup pads. Cleanups are always funclet entries for all known
1221 UnwindDests.push_back(FuncInfo.MBBMap[EHPadBB]);
1222 UnwindDests.back()->setIsEHFuncletEntry();
1224 } else if (const auto *CPI = dyn_cast<CatchPadInst>(Pad)) {
1225 // Add the catchpad handler to the possible destinations.
1226 UnwindDests.push_back(FuncInfo.MBBMap[CPI->getNormalDest()]);
1227 // In MSVC C++, catchblocks are funclets and need prologues.
1229 UnwindDests.back()->setIsEHFuncletEntry();
1230 EHPadBB = CPI->getUnwindDest();
1231 } else if (const auto *CEPI = dyn_cast<CatchEndPadInst>(Pad)) {
1232 EHPadBB = CEPI->getUnwindDest();
1233 } else if (const auto *CEPI = dyn_cast<CleanupEndPadInst>(Pad)) {
1234 EHPadBB = CEPI->getUnwindDest();
1239 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1240 // Update successor info.
1241 // FIXME: The weights for catchpads will be wrong.
1242 SmallVector<MachineBasicBlock *, 1> UnwindDests;
1243 findUnwindDestinations(FuncInfo, I.getUnwindDest(), UnwindDests);
1244 for (MachineBasicBlock *UnwindDest : UnwindDests) {
1245 UnwindDest->setIsEHPad();
1246 addSuccessorWithWeight(FuncInfo.MBB, UnwindDest);
1249 // Create the terminator node.
1251 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1255 void SelectionDAGBuilder::visitCleanupEndPad(const CleanupEndPadInst &I) {
1256 report_fatal_error("visitCleanupEndPad not yet implemented!");
1259 void SelectionDAGBuilder::visitTerminatePad(const TerminatePadInst &TPI) {
1260 report_fatal_error("visitTerminatePad not yet implemented!");
1263 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1264 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1265 auto &DL = DAG.getDataLayout();
1266 SDValue Chain = getControlRoot();
1267 SmallVector<ISD::OutputArg, 8> Outs;
1268 SmallVector<SDValue, 8> OutVals;
1270 if (!FuncInfo.CanLowerReturn) {
1271 unsigned DemoteReg = FuncInfo.DemoteRegister;
1272 const Function *F = I.getParent()->getParent();
1274 // Emit a store of the return value through the virtual register.
1275 // Leave Outs empty so that LowerReturn won't try to load return
1276 // registers the usual way.
1277 SmallVector<EVT, 1> PtrValueVTs;
1278 ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()),
1281 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1282 SDValue RetOp = getValue(I.getOperand(0));
1284 SmallVector<EVT, 4> ValueVTs;
1285 SmallVector<uint64_t, 4> Offsets;
1286 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1287 unsigned NumValues = ValueVTs.size();
1289 SmallVector<SDValue, 4> Chains(NumValues);
1290 for (unsigned i = 0; i != NumValues; ++i) {
1291 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1292 RetPtr.getValueType(), RetPtr,
1293 DAG.getIntPtrConstant(Offsets[i],
1296 DAG.getStore(Chain, getCurSDLoc(),
1297 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1298 // FIXME: better loc info would be nice.
1299 Add, MachinePointerInfo(), false, false, 0);
1302 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1303 MVT::Other, Chains);
1304 } else if (I.getNumOperands() != 0) {
1305 SmallVector<EVT, 4> ValueVTs;
1306 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1307 unsigned NumValues = ValueVTs.size();
1309 SDValue RetOp = getValue(I.getOperand(0));
1311 const Function *F = I.getParent()->getParent();
1313 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1314 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1316 ExtendKind = ISD::SIGN_EXTEND;
1317 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1319 ExtendKind = ISD::ZERO_EXTEND;
1321 LLVMContext &Context = F->getContext();
1322 bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1325 for (unsigned j = 0; j != NumValues; ++j) {
1326 EVT VT = ValueVTs[j];
1328 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1329 VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind);
1331 unsigned NumParts = TLI.getNumRegisters(Context, VT);
1332 MVT PartVT = TLI.getRegisterType(Context, VT);
1333 SmallVector<SDValue, 4> Parts(NumParts);
1334 getCopyToParts(DAG, getCurSDLoc(),
1335 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1336 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1338 // 'inreg' on function refers to return value
1339 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1343 // Propagate extension type if any
1344 if (ExtendKind == ISD::SIGN_EXTEND)
1346 else if (ExtendKind == ISD::ZERO_EXTEND)
1349 for (unsigned i = 0; i < NumParts; ++i) {
1350 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1351 VT, /*isfixed=*/true, 0, 0));
1352 OutVals.push_back(Parts[i]);
1358 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1359 CallingConv::ID CallConv =
1360 DAG.getMachineFunction().getFunction()->getCallingConv();
1361 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1362 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1364 // Verify that the target's LowerReturn behaved as expected.
1365 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1366 "LowerReturn didn't return a valid chain!");
1368 // Update the DAG with the new chain value resulting from return lowering.
1372 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1373 /// created for it, emit nodes to copy the value into the virtual
1375 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1377 if (V->getType()->isEmptyTy())
1380 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1381 if (VMI != FuncInfo.ValueMap.end()) {
1382 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1383 CopyValueToVirtualRegister(V, VMI->second);
1387 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1388 /// the current basic block, add it to ValueMap now so that we'll get a
1390 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1391 // No need to export constants.
1392 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1394 // Already exported?
1395 if (FuncInfo.isExportedInst(V)) return;
1397 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1398 CopyValueToVirtualRegister(V, Reg);
1401 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1402 const BasicBlock *FromBB) {
1403 // The operands of the setcc have to be in this block. We don't know
1404 // how to export them from some other block.
1405 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1406 // Can export from current BB.
1407 if (VI->getParent() == FromBB)
1410 // Is already exported, noop.
1411 return FuncInfo.isExportedInst(V);
1414 // If this is an argument, we can export it if the BB is the entry block or
1415 // if it is already exported.
1416 if (isa<Argument>(V)) {
1417 if (FromBB == &FromBB->getParent()->getEntryBlock())
1420 // Otherwise, can only export this if it is already exported.
1421 return FuncInfo.isExportedInst(V);
1424 // Otherwise, constants can always be exported.
1428 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1429 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1430 const MachineBasicBlock *Dst) const {
1431 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1434 const BasicBlock *SrcBB = Src->getBasicBlock();
1435 const BasicBlock *DstBB = Dst->getBasicBlock();
1436 return BPI->getEdgeWeight(SrcBB, DstBB);
1439 void SelectionDAGBuilder::
1440 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1441 uint32_t Weight /* = 0 */) {
1443 Weight = getEdgeWeight(Src, Dst);
1444 Src->addSuccessor(Dst, Weight);
1448 static bool InBlock(const Value *V, const BasicBlock *BB) {
1449 if (const Instruction *I = dyn_cast<Instruction>(V))
1450 return I->getParent() == BB;
1454 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1455 /// This function emits a branch and is used at the leaves of an OR or an
1456 /// AND operator tree.
1459 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1460 MachineBasicBlock *TBB,
1461 MachineBasicBlock *FBB,
1462 MachineBasicBlock *CurBB,
1463 MachineBasicBlock *SwitchBB,
1466 const BasicBlock *BB = CurBB->getBasicBlock();
1468 // If the leaf of the tree is a comparison, merge the condition into
1470 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1471 // The operands of the cmp have to be in this block. We don't know
1472 // how to export them from some other block. If this is the first block
1473 // of the sequence, no exporting is needed.
1474 if (CurBB == SwitchBB ||
1475 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1476 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1477 ISD::CondCode Condition;
1478 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1479 Condition = getICmpCondCode(IC->getPredicate());
1481 const FCmpInst *FC = cast<FCmpInst>(Cond);
1482 Condition = getFCmpCondCode(FC->getPredicate());
1483 if (TM.Options.NoNaNsFPMath)
1484 Condition = getFCmpCodeWithoutNaN(Condition);
1487 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1488 TBB, FBB, CurBB, TWeight, FWeight);
1489 SwitchCases.push_back(CB);
1494 // Create a CaseBlock record representing this branch.
1495 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1496 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
1497 SwitchCases.push_back(CB);
1500 /// Scale down both weights to fit into uint32_t.
1501 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1502 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1503 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1504 NewTrue = NewTrue / Scale;
1505 NewFalse = NewFalse / Scale;
1508 /// FindMergedConditions - If Cond is an expression like
1509 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1510 MachineBasicBlock *TBB,
1511 MachineBasicBlock *FBB,
1512 MachineBasicBlock *CurBB,
1513 MachineBasicBlock *SwitchBB,
1514 Instruction::BinaryOps Opc,
1517 // If this node is not part of the or/and tree, emit it as a branch.
1518 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1519 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1520 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1521 BOp->getParent() != CurBB->getBasicBlock() ||
1522 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1523 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1524 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1529 // Create TmpBB after CurBB.
1530 MachineFunction::iterator BBI = CurBB;
1531 MachineFunction &MF = DAG.getMachineFunction();
1532 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1533 CurBB->getParent()->insert(++BBI, TmpBB);
1535 if (Opc == Instruction::Or) {
1536 // Codegen X | Y as:
1545 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1546 // The requirement is that
1547 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1548 // = TrueProb for original BB.
1549 // Assuming the original weights are A and B, one choice is to set BB1's
1550 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1552 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1553 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1554 // TmpBB, but the math is more complicated.
1556 uint64_t NewTrueWeight = TWeight;
1557 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1558 ScaleWeights(NewTrueWeight, NewFalseWeight);
1559 // Emit the LHS condition.
1560 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1561 NewTrueWeight, NewFalseWeight);
1563 NewTrueWeight = TWeight;
1564 NewFalseWeight = 2 * (uint64_t)FWeight;
1565 ScaleWeights(NewTrueWeight, NewFalseWeight);
1566 // Emit the RHS condition into TmpBB.
1567 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1568 NewTrueWeight, NewFalseWeight);
1570 assert(Opc == Instruction::And && "Unknown merge op!");
1571 // Codegen X & Y as:
1579 // This requires creation of TmpBB after CurBB.
1581 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1582 // The requirement is that
1583 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1584 // = FalseProb for original BB.
1585 // Assuming the original weights are A and B, one choice is to set BB1's
1586 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1588 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1590 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1591 uint64_t NewFalseWeight = FWeight;
1592 ScaleWeights(NewTrueWeight, NewFalseWeight);
1593 // Emit the LHS condition.
1594 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1595 NewTrueWeight, NewFalseWeight);
1597 NewTrueWeight = 2 * (uint64_t)TWeight;
1598 NewFalseWeight = FWeight;
1599 ScaleWeights(NewTrueWeight, NewFalseWeight);
1600 // Emit the RHS condition into TmpBB.
1601 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1602 NewTrueWeight, NewFalseWeight);
1606 /// If the set of cases should be emitted as a series of branches, return true.
1607 /// If we should emit this as a bunch of and/or'd together conditions, return
1610 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1611 if (Cases.size() != 2) return true;
1613 // If this is two comparisons of the same values or'd or and'd together, they
1614 // will get folded into a single comparison, so don't emit two blocks.
1615 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1616 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1617 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1618 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1622 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1623 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1624 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1625 Cases[0].CC == Cases[1].CC &&
1626 isa<Constant>(Cases[0].CmpRHS) &&
1627 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1628 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1630 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1637 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1638 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1640 // Update machine-CFG edges.
1641 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1643 if (I.isUnconditional()) {
1644 // Update machine-CFG edges.
1645 BrMBB->addSuccessor(Succ0MBB);
1647 // If this is not a fall-through branch or optimizations are switched off,
1649 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1650 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1651 MVT::Other, getControlRoot(),
1652 DAG.getBasicBlock(Succ0MBB)));
1657 // If this condition is one of the special cases we handle, do special stuff
1659 const Value *CondVal = I.getCondition();
1660 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1662 // If this is a series of conditions that are or'd or and'd together, emit
1663 // this as a sequence of branches instead of setcc's with and/or operations.
1664 // As long as jumps are not expensive, this should improve performance.
1665 // For example, instead of something like:
1678 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1679 Instruction::BinaryOps Opcode = BOp->getOpcode();
1680 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
1681 !I.getMetadata(LLVMContext::MD_unpredictable) &&
1682 (Opcode == Instruction::And || Opcode == Instruction::Or)) {
1683 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1684 Opcode, getEdgeWeight(BrMBB, Succ0MBB),
1685 getEdgeWeight(BrMBB, Succ1MBB));
1686 // If the compares in later blocks need to use values not currently
1687 // exported from this block, export them now. This block should always
1688 // be the first entry.
1689 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1691 // Allow some cases to be rejected.
1692 if (ShouldEmitAsBranches(SwitchCases)) {
1693 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1694 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1695 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1698 // Emit the branch for this block.
1699 visitSwitchCase(SwitchCases[0], BrMBB);
1700 SwitchCases.erase(SwitchCases.begin());
1704 // Okay, we decided not to do this, remove any inserted MBB's and clear
1706 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1707 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1709 SwitchCases.clear();
1713 // Create a CaseBlock record representing this branch.
1714 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1715 nullptr, Succ0MBB, Succ1MBB, BrMBB);
1717 // Use visitSwitchCase to actually insert the fast branch sequence for this
1719 visitSwitchCase(CB, BrMBB);
1722 /// visitSwitchCase - Emits the necessary code to represent a single node in
1723 /// the binary search tree resulting from lowering a switch instruction.
1724 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1725 MachineBasicBlock *SwitchBB) {
1727 SDValue CondLHS = getValue(CB.CmpLHS);
1728 SDLoc dl = getCurSDLoc();
1730 // Build the setcc now.
1732 // Fold "(X == true)" to X and "(X == false)" to !X to
1733 // handle common cases produced by branch lowering.
1734 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1735 CB.CC == ISD::SETEQ)
1737 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1738 CB.CC == ISD::SETEQ) {
1739 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
1740 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1742 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1744 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1746 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1747 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1749 SDValue CmpOp = getValue(CB.CmpMHS);
1750 EVT VT = CmpOp.getValueType();
1752 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1753 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
1756 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1757 VT, CmpOp, DAG.getConstant(Low, dl, VT));
1758 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1759 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
1763 // Update successor info
1764 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1765 // TrueBB and FalseBB are always different unless the incoming IR is
1766 // degenerate. This only happens when running llc on weird IR.
1767 if (CB.TrueBB != CB.FalseBB)
1768 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1770 // If the lhs block is the next block, invert the condition so that we can
1771 // fall through to the lhs instead of the rhs block.
1772 if (CB.TrueBB == NextBlock(SwitchBB)) {
1773 std::swap(CB.TrueBB, CB.FalseBB);
1774 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
1775 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1778 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1779 MVT::Other, getControlRoot(), Cond,
1780 DAG.getBasicBlock(CB.TrueBB));
1782 // Insert the false branch. Do this even if it's a fall through branch,
1783 // this makes it easier to do DAG optimizations which require inverting
1784 // the branch condition.
1785 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1786 DAG.getBasicBlock(CB.FalseBB));
1788 DAG.setRoot(BrCond);
1791 /// visitJumpTable - Emit JumpTable node in the current MBB
1792 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1793 // Emit the code for the jump table
1794 assert(JT.Reg != -1U && "Should lower JT Header first!");
1795 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1796 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1798 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1799 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1800 MVT::Other, Index.getValue(1),
1802 DAG.setRoot(BrJumpTable);
1805 /// visitJumpTableHeader - This function emits necessary code to produce index
1806 /// in the JumpTable from switch case.
1807 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1808 JumpTableHeader &JTH,
1809 MachineBasicBlock *SwitchBB) {
1810 SDLoc dl = getCurSDLoc();
1812 // Subtract the lowest switch case value from the value being switched on and
1813 // conditional branch to default mbb if the result is greater than the
1814 // difference between smallest and largest cases.
1815 SDValue SwitchOp = getValue(JTH.SValue);
1816 EVT VT = SwitchOp.getValueType();
1817 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
1818 DAG.getConstant(JTH.First, dl, VT));
1820 // The SDNode we just created, which holds the value being switched on minus
1821 // the smallest case value, needs to be copied to a virtual register so it
1822 // can be used as an index into the jump table in a subsequent basic block.
1823 // This value may be smaller or larger than the target's pointer type, and
1824 // therefore require extension or truncating.
1825 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1826 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
1828 unsigned JumpTableReg =
1829 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
1830 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
1831 JumpTableReg, SwitchOp);
1832 JT.Reg = JumpTableReg;
1834 // Emit the range check for the jump table, and branch to the default block
1835 // for the switch statement if the value being switched on exceeds the largest
1836 // case in the switch.
1837 SDValue CMP = DAG.getSetCC(
1838 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
1839 Sub.getValueType()),
1840 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
1842 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1843 MVT::Other, CopyTo, CMP,
1844 DAG.getBasicBlock(JT.Default));
1846 // Avoid emitting unnecessary branches to the next block.
1847 if (JT.MBB != NextBlock(SwitchBB))
1848 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1849 DAG.getBasicBlock(JT.MBB));
1851 DAG.setRoot(BrCond);
1854 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1855 /// tail spliced into a stack protector check success bb.
1857 /// For a high level explanation of how this fits into the stack protector
1858 /// generation see the comment on the declaration of class
1859 /// StackProtectorDescriptor.
1860 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1861 MachineBasicBlock *ParentBB) {
1863 // First create the loads to the guard/stack slot for the comparison.
1864 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1865 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
1867 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1868 int FI = MFI->getStackProtectorIndex();
1870 const Value *IRGuard = SPD.getGuard();
1871 SDValue GuardPtr = getValue(IRGuard);
1872 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1874 unsigned Align = DL->getPrefTypeAlignment(IRGuard->getType());
1877 SDLoc dl = getCurSDLoc();
1879 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1880 // guard value from the virtual register holding the value. Otherwise, emit a
1881 // volatile load to retrieve the stack guard value.
1882 unsigned GuardReg = SPD.getGuardReg();
1884 if (GuardReg && TLI.useLoadStackGuardNode())
1885 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), dl, GuardReg,
1888 Guard = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
1889 GuardPtr, MachinePointerInfo(IRGuard, 0),
1890 true, false, false, Align);
1892 SDValue StackSlot = DAG.getLoad(
1893 PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
1894 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), true,
1895 false, false, Align);
1897 // Perform the comparison via a subtract/getsetcc.
1898 EVT VT = Guard.getValueType();
1899 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
1901 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
1903 Sub.getValueType()),
1904 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
1906 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1907 // branch to failure MBB.
1908 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1909 MVT::Other, StackSlot.getOperand(0),
1910 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1911 // Otherwise branch to success MBB.
1912 SDValue Br = DAG.getNode(ISD::BR, dl,
1914 DAG.getBasicBlock(SPD.getSuccessMBB()));
1919 /// Codegen the failure basic block for a stack protector check.
1921 /// A failure stack protector machine basic block consists simply of a call to
1922 /// __stack_chk_fail().
1924 /// For a high level explanation of how this fits into the stack protector
1925 /// generation see the comment on the declaration of class
1926 /// StackProtectorDescriptor.
1928 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1929 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1931 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1932 nullptr, 0, false, getCurSDLoc(), false, false).second;
1936 /// visitBitTestHeader - This function emits necessary code to produce value
1937 /// suitable for "bit tests"
1938 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1939 MachineBasicBlock *SwitchBB) {
1940 SDLoc dl = getCurSDLoc();
1942 // Subtract the minimum value
1943 SDValue SwitchOp = getValue(B.SValue);
1944 EVT VT = SwitchOp.getValueType();
1945 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
1946 DAG.getConstant(B.First, dl, VT));
1949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1950 SDValue RangeCmp = DAG.getSetCC(
1951 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
1952 Sub.getValueType()),
1953 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
1955 // Determine the type of the test operands.
1956 bool UsePtrType = false;
1957 if (!TLI.isTypeLegal(VT))
1960 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1961 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1962 // Switch table case range are encoded into series of masks.
1963 // Just use pointer type, it's guaranteed to fit.
1969 VT = TLI.getPointerTy(DAG.getDataLayout());
1970 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
1973 B.RegVT = VT.getSimpleVT();
1974 B.Reg = FuncInfo.CreateReg(B.RegVT);
1975 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
1977 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1979 addSuccessorWithWeight(SwitchBB, B.Default, B.DefaultWeight);
1980 addSuccessorWithWeight(SwitchBB, MBB, B.Weight);
1982 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
1983 MVT::Other, CopyTo, RangeCmp,
1984 DAG.getBasicBlock(B.Default));
1986 // Avoid emitting unnecessary branches to the next block.
1987 if (MBB != NextBlock(SwitchBB))
1988 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
1989 DAG.getBasicBlock(MBB));
1991 DAG.setRoot(BrRange);
1994 /// visitBitTestCase - this function produces one "bit test"
1995 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1996 MachineBasicBlock* NextMBB,
1997 uint32_t BranchWeightToNext,
2000 MachineBasicBlock *SwitchBB) {
2001 SDLoc dl = getCurSDLoc();
2003 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2005 unsigned PopCount = countPopulation(B.Mask);
2006 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2007 if (PopCount == 1) {
2008 // Testing for a single bit; just compare the shift count with what it
2009 // would need to be to shift a 1 bit in that position.
2011 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2012 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2014 } else if (PopCount == BB.Range) {
2015 // There is only one zero bit in the range, test for it directly.
2017 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2018 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2021 // Make desired shift
2022 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2023 DAG.getConstant(1, dl, VT), ShiftOp);
2025 // Emit bit tests and jumps
2026 SDValue AndOp = DAG.getNode(ISD::AND, dl,
2027 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2029 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2030 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2033 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
2034 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
2035 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
2036 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
2038 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2039 MVT::Other, getControlRoot(),
2040 Cmp, DAG.getBasicBlock(B.TargetBB));
2042 // Avoid emitting unnecessary branches to the next block.
2043 if (NextMBB != NextBlock(SwitchBB))
2044 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2045 DAG.getBasicBlock(NextMBB));
2050 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2051 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2053 // Retrieve successors. Look through artificial IR level blocks like catchpads
2054 // and catchendpads for successors.
2055 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2056 const BasicBlock *EHPadBB = I.getSuccessor(1);
2058 const Value *Callee(I.getCalledValue());
2059 const Function *Fn = dyn_cast<Function>(Callee);
2060 if (isa<InlineAsm>(Callee))
2062 else if (Fn && Fn->isIntrinsic()) {
2063 switch (Fn->getIntrinsicID()) {
2065 llvm_unreachable("Cannot invoke this intrinsic");
2066 case Intrinsic::donothing:
2067 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2069 case Intrinsic::experimental_patchpoint_void:
2070 case Intrinsic::experimental_patchpoint_i64:
2071 visitPatchpoint(&I, EHPadBB);
2073 case Intrinsic::experimental_gc_statepoint:
2074 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2078 LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2080 // If the value of the invoke is used outside of its defining block, make it
2081 // available as a virtual register.
2082 // We already took care of the exported value for the statepoint instruction
2083 // during call to the LowerStatepoint.
2084 if (!isStatepoint(I)) {
2085 CopyToExportRegsIfNeeded(&I);
2088 SmallVector<MachineBasicBlock *, 1> UnwindDests;
2089 findUnwindDestinations(FuncInfo, EHPadBB, UnwindDests);
2091 // Update successor info.
2092 // FIXME: The weights for catchpads will be wrong.
2093 addSuccessorWithWeight(InvokeMBB, Return);
2094 for (MachineBasicBlock *UnwindDest : UnwindDests) {
2095 UnwindDest->setIsEHPad();
2096 addSuccessorWithWeight(InvokeMBB, UnwindDest);
2099 // Drop into normal successor.
2100 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2101 MVT::Other, getControlRoot(),
2102 DAG.getBasicBlock(Return)));
2105 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2106 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2109 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2110 assert(FuncInfo.MBB->isEHPad() &&
2111 "Call to landingpad not in landing pad!");
2113 MachineBasicBlock *MBB = FuncInfo.MBB;
2114 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2115 AddLandingPadInfo(LP, MMI, MBB);
2117 // If there aren't registers to copy the values into (e.g., during SjLj
2118 // exceptions), then don't bother to create these DAG nodes.
2119 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2120 if (TLI.getExceptionPointerRegister() == 0 &&
2121 TLI.getExceptionSelectorRegister() == 0)
2124 SmallVector<EVT, 2> ValueVTs;
2125 SDLoc dl = getCurSDLoc();
2126 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2127 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2129 // Get the two live-in registers as SDValues. The physregs have already been
2130 // copied into virtual registers.
2132 if (FuncInfo.ExceptionPointerVirtReg) {
2133 Ops[0] = DAG.getZExtOrTrunc(
2134 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2135 FuncInfo.ExceptionPointerVirtReg,
2136 TLI.getPointerTy(DAG.getDataLayout())),
2139 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2141 Ops[1] = DAG.getZExtOrTrunc(
2142 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2143 FuncInfo.ExceptionSelectorVirtReg,
2144 TLI.getPointerTy(DAG.getDataLayout())),
2148 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2149 DAG.getVTList(ValueVTs), Ops);
2153 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2155 for (const CaseCluster &CC : Clusters)
2156 assert(CC.Low == CC.High && "Input clusters must be single-case");
2159 std::sort(Clusters.begin(), Clusters.end(),
2160 [](const CaseCluster &a, const CaseCluster &b) {
2161 return a.Low->getValue().slt(b.Low->getValue());
2164 // Merge adjacent clusters with the same destination.
2165 const unsigned N = Clusters.size();
2166 unsigned DstIndex = 0;
2167 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2168 CaseCluster &CC = Clusters[SrcIndex];
2169 const ConstantInt *CaseVal = CC.Low;
2170 MachineBasicBlock *Succ = CC.MBB;
2172 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2173 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2174 // If this case has the same successor and is a neighbour, merge it into
2175 // the previous cluster.
2176 Clusters[DstIndex - 1].High = CaseVal;
2177 Clusters[DstIndex - 1].Weight += CC.Weight;
2178 assert(Clusters[DstIndex - 1].Weight >= CC.Weight && "Weight overflow!");
2180 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2181 sizeof(Clusters[SrcIndex]));
2184 Clusters.resize(DstIndex);
2187 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2188 MachineBasicBlock *Last) {
2190 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2191 if (JTCases[i].first.HeaderBB == First)
2192 JTCases[i].first.HeaderBB = Last;
2194 // Update BitTestCases.
2195 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2196 if (BitTestCases[i].Parent == First)
2197 BitTestCases[i].Parent = Last;
2200 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2201 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2203 // Update machine-CFG edges with unique successors.
2204 SmallSet<BasicBlock*, 32> Done;
2205 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2206 BasicBlock *BB = I.getSuccessor(i);
2207 bool Inserted = Done.insert(BB).second;
2211 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2212 addSuccessorWithWeight(IndirectBrMBB, Succ);
2215 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2216 MVT::Other, getControlRoot(),
2217 getValue(I.getAddress())));
2220 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2221 if (DAG.getTarget().Options.TrapUnreachable)
2223 DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2226 void SelectionDAGBuilder::visitFSub(const User &I) {
2227 // -0.0 - X --> fneg
2228 Type *Ty = I.getType();
2229 if (isa<Constant>(I.getOperand(0)) &&
2230 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2231 SDValue Op2 = getValue(I.getOperand(1));
2232 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2233 Op2.getValueType(), Op2));
2237 visitBinary(I, ISD::FSUB);
2240 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2241 SDValue Op1 = getValue(I.getOperand(0));
2242 SDValue Op2 = getValue(I.getOperand(1));
2249 if (const OverflowingBinaryOperator *OFBinOp =
2250 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2251 nuw = OFBinOp->hasNoUnsignedWrap();
2252 nsw = OFBinOp->hasNoSignedWrap();
2254 if (const PossiblyExactOperator *ExactOp =
2255 dyn_cast<const PossiblyExactOperator>(&I))
2256 exact = ExactOp->isExact();
2257 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
2258 FMF = FPOp->getFastMathFlags();
2261 Flags.setExact(exact);
2262 Flags.setNoSignedWrap(nsw);
2263 Flags.setNoUnsignedWrap(nuw);
2264 if (EnableFMFInDAG) {
2265 Flags.setAllowReciprocal(FMF.allowReciprocal());
2266 Flags.setNoInfs(FMF.noInfs());
2267 Flags.setNoNaNs(FMF.noNaNs());
2268 Flags.setNoSignedZeros(FMF.noSignedZeros());
2269 Flags.setUnsafeAlgebra(FMF.unsafeAlgebra());
2271 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2273 setValue(&I, BinNodeValue);
2276 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2277 SDValue Op1 = getValue(I.getOperand(0));
2278 SDValue Op2 = getValue(I.getOperand(1));
2280 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2281 Op2.getValueType(), DAG.getDataLayout());
2283 // Coerce the shift amount to the right type if we can.
2284 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2285 unsigned ShiftSize = ShiftTy.getSizeInBits();
2286 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2287 SDLoc DL = getCurSDLoc();
2289 // If the operand is smaller than the shift count type, promote it.
2290 if (ShiftSize > Op2Size)
2291 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2293 // If the operand is larger than the shift count type but the shift
2294 // count type has enough bits to represent any shift value, truncate
2295 // it now. This is a common case and it exposes the truncate to
2296 // optimization early.
2297 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2298 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2299 // Otherwise we'll need to temporarily settle for some other convenient
2300 // type. Type legalization will make adjustments once the shiftee is split.
2302 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2309 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2311 if (const OverflowingBinaryOperator *OFBinOp =
2312 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2313 nuw = OFBinOp->hasNoUnsignedWrap();
2314 nsw = OFBinOp->hasNoSignedWrap();
2316 if (const PossiblyExactOperator *ExactOp =
2317 dyn_cast<const PossiblyExactOperator>(&I))
2318 exact = ExactOp->isExact();
2321 Flags.setExact(exact);
2322 Flags.setNoSignedWrap(nsw);
2323 Flags.setNoUnsignedWrap(nuw);
2324 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2329 void SelectionDAGBuilder::visitSDiv(const User &I) {
2330 SDValue Op1 = getValue(I.getOperand(0));
2331 SDValue Op2 = getValue(I.getOperand(1));
2334 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2335 cast<PossiblyExactOperator>(&I)->isExact());
2336 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2340 void SelectionDAGBuilder::visitICmp(const User &I) {
2341 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2342 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2343 predicate = IC->getPredicate();
2344 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2345 predicate = ICmpInst::Predicate(IC->getPredicate());
2346 SDValue Op1 = getValue(I.getOperand(0));
2347 SDValue Op2 = getValue(I.getOperand(1));
2348 ISD::CondCode Opcode = getICmpCondCode(predicate);
2350 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2352 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2355 void SelectionDAGBuilder::visitFCmp(const User &I) {
2356 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2357 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2358 predicate = FC->getPredicate();
2359 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2360 predicate = FCmpInst::Predicate(FC->getPredicate());
2361 SDValue Op1 = getValue(I.getOperand(0));
2362 SDValue Op2 = getValue(I.getOperand(1));
2363 ISD::CondCode Condition = getFCmpCondCode(predicate);
2365 // FIXME: Fcmp instructions have fast-math-flags in IR, so we should use them.
2366 // FIXME: We should propagate the fast-math-flags to the DAG node itself for
2367 // further optimization, but currently FMF is only applicable to binary nodes.
2368 if (TM.Options.NoNaNsFPMath)
2369 Condition = getFCmpCodeWithoutNaN(Condition);
2370 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2372 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2375 void SelectionDAGBuilder::visitSelect(const User &I) {
2376 SmallVector<EVT, 4> ValueVTs;
2377 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2379 unsigned NumValues = ValueVTs.size();
2380 if (NumValues == 0) return;
2382 SmallVector<SDValue, 4> Values(NumValues);
2383 SDValue Cond = getValue(I.getOperand(0));
2384 SDValue LHSVal = getValue(I.getOperand(1));
2385 SDValue RHSVal = getValue(I.getOperand(2));
2386 auto BaseOps = {Cond};
2387 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2388 ISD::VSELECT : ISD::SELECT;
2390 // Min/max matching is only viable if all output VTs are the same.
2391 if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2392 EVT VT = ValueVTs[0];
2393 LLVMContext &Ctx = *DAG.getContext();
2394 auto &TLI = DAG.getTargetLoweringInfo();
2395 while (TLI.getTypeAction(Ctx, VT) == TargetLoweringBase::TypeSplitVector)
2396 VT = TLI.getTypeToTransformTo(Ctx, VT);
2399 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2400 ISD::NodeType Opc = ISD::DELETED_NODE;
2401 switch (SPR.Flavor) {
2402 case SPF_UMAX: Opc = ISD::UMAX; break;
2403 case SPF_UMIN: Opc = ISD::UMIN; break;
2404 case SPF_SMAX: Opc = ISD::SMAX; break;
2405 case SPF_SMIN: Opc = ISD::SMIN; break;
2407 switch (SPR.NaNBehavior) {
2408 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2409 case SPNB_RETURNS_NAN: Opc = ISD::FMINNAN; break;
2410 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2411 case SPNB_RETURNS_ANY:
2412 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ? ISD::FMINNUM
2418 switch (SPR.NaNBehavior) {
2419 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2420 case SPNB_RETURNS_NAN: Opc = ISD::FMAXNAN; break;
2421 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
2422 case SPNB_RETURNS_ANY:
2423 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ? ISD::FMAXNUM
2431 if (Opc != ISD::DELETED_NODE && TLI.isOperationLegalOrCustom(Opc, VT) &&
2432 // If the underlying comparison instruction is used by any other instruction,
2433 // the consumed instructions won't be destroyed, so it is not profitable
2434 // to convert to a min/max.
2435 cast<SelectInst>(&I)->getCondition()->hasOneUse()) {
2437 LHSVal = getValue(LHS);
2438 RHSVal = getValue(RHS);
2443 for (unsigned i = 0; i != NumValues; ++i) {
2444 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2445 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2446 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2447 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2448 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2452 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2453 DAG.getVTList(ValueVTs), Values));
2456 void SelectionDAGBuilder::visitTrunc(const User &I) {
2457 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2458 SDValue N = getValue(I.getOperand(0));
2459 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2461 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2464 void SelectionDAGBuilder::visitZExt(const User &I) {
2465 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2466 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2467 SDValue N = getValue(I.getOperand(0));
2468 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2470 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2473 void SelectionDAGBuilder::visitSExt(const User &I) {
2474 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2475 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2476 SDValue N = getValue(I.getOperand(0));
2477 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2479 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2482 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2483 // FPTrunc is never a no-op cast, no need to check
2484 SDValue N = getValue(I.getOperand(0));
2485 SDLoc dl = getCurSDLoc();
2486 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2487 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2488 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
2489 DAG.getTargetConstant(
2490 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
2493 void SelectionDAGBuilder::visitFPExt(const User &I) {
2494 // FPExt is never a no-op cast, no need to check
2495 SDValue N = getValue(I.getOperand(0));
2496 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2498 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2501 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2502 // FPToUI is never a no-op cast, no need to check
2503 SDValue N = getValue(I.getOperand(0));
2504 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2506 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2509 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2510 // FPToSI is never a no-op cast, no need to check
2511 SDValue N = getValue(I.getOperand(0));
2512 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2514 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2517 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2518 // UIToFP is never a no-op cast, no need to check
2519 SDValue N = getValue(I.getOperand(0));
2520 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2522 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2525 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2526 // SIToFP is never a no-op cast, no need to check
2527 SDValue N = getValue(I.getOperand(0));
2528 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2530 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2533 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2534 // What to do depends on the size of the integer and the size of the pointer.
2535 // We can either truncate, zero extend, or no-op, accordingly.
2536 SDValue N = getValue(I.getOperand(0));
2537 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2539 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2542 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2543 // What to do depends on the size of the integer and the size of the pointer.
2544 // We can either truncate, zero extend, or no-op, accordingly.
2545 SDValue N = getValue(I.getOperand(0));
2546 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2548 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2551 void SelectionDAGBuilder::visitBitCast(const User &I) {
2552 SDValue N = getValue(I.getOperand(0));
2553 SDLoc dl = getCurSDLoc();
2554 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2557 // BitCast assures us that source and destination are the same size so this is
2558 // either a BITCAST or a no-op.
2559 if (DestVT != N.getValueType())
2560 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
2561 DestVT, N)); // convert types.
2562 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
2563 // might fold any kind of constant expression to an integer constant and that
2564 // is not what we are looking for. Only regcognize a bitcast of a genuine
2565 // constant integer as an opaque constant.
2566 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
2567 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
2570 setValue(&I, N); // noop cast.
2573 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2574 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2575 const Value *SV = I.getOperand(0);
2576 SDValue N = getValue(SV);
2577 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2579 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
2580 unsigned DestAS = I.getType()->getPointerAddressSpace();
2582 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2583 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
2588 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2589 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2590 SDValue InVec = getValue(I.getOperand(0));
2591 SDValue InVal = getValue(I.getOperand(1));
2592 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
2593 TLI.getVectorIdxTy(DAG.getDataLayout()));
2594 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
2595 TLI.getValueType(DAG.getDataLayout(), I.getType()),
2596 InVec, InVal, InIdx));
2599 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2600 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2601 SDValue InVec = getValue(I.getOperand(0));
2602 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
2603 TLI.getVectorIdxTy(DAG.getDataLayout()));
2604 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
2605 TLI.getValueType(DAG.getDataLayout(), I.getType()),
2609 // Utility for visitShuffleVector - Return true if every element in Mask,
2610 // beginning from position Pos and ending in Pos+Size, falls within the
2611 // specified sequential range [L, L+Pos). or is undef.
2612 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
2613 unsigned Pos, unsigned Size, int Low) {
2614 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
2615 if (Mask[i] >= 0 && Mask[i] != Low)
2620 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2621 SDValue Src1 = getValue(I.getOperand(0));
2622 SDValue Src2 = getValue(I.getOperand(1));
2624 SmallVector<int, 8> Mask;
2625 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2626 unsigned MaskNumElts = Mask.size();
2628 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2629 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
2630 EVT SrcVT = Src1.getValueType();
2631 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2633 if (SrcNumElts == MaskNumElts) {
2634 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2639 // Normalize the shuffle vector since mask and vector length don't match.
2640 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2641 // Mask is longer than the source vectors and is a multiple of the source
2642 // vectors. We can use concatenate vector to make the mask and vectors
2644 if (SrcNumElts*2 == MaskNumElts) {
2645 // First check for Src1 in low and Src2 in high
2646 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
2647 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
2648 // The shuffle is concatenating two vectors together.
2649 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
2653 // Then check for Src2 in low and Src1 in high
2654 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
2655 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
2656 // The shuffle is concatenating two vectors together.
2657 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
2663 // Pad both vectors with undefs to make them the same length as the mask.
2664 unsigned NumConcat = MaskNumElts / SrcNumElts;
2665 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2666 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2667 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2669 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2670 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2674 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2675 getCurSDLoc(), VT, MOps1);
2676 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2677 getCurSDLoc(), VT, MOps2);
2679 // Readjust mask for new input vector length.
2680 SmallVector<int, 8> MappedOps;
2681 for (unsigned i = 0; i != MaskNumElts; ++i) {
2683 if (Idx >= (int)SrcNumElts)
2684 Idx -= SrcNumElts - MaskNumElts;
2685 MappedOps.push_back(Idx);
2688 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2693 if (SrcNumElts > MaskNumElts) {
2694 // Analyze the access pattern of the vector to see if we can extract
2695 // two subvectors and do the shuffle. The analysis is done by calculating
2696 // the range of elements the mask access on both vectors.
2697 int MinRange[2] = { static_cast<int>(SrcNumElts),
2698 static_cast<int>(SrcNumElts)};
2699 int MaxRange[2] = {-1, -1};
2701 for (unsigned i = 0; i != MaskNumElts; ++i) {
2707 if (Idx >= (int)SrcNumElts) {
2711 if (Idx > MaxRange[Input])
2712 MaxRange[Input] = Idx;
2713 if (Idx < MinRange[Input])
2714 MinRange[Input] = Idx;
2717 // Check if the access is smaller than the vector size and can we find
2718 // a reasonable extract index.
2719 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
2721 int StartIdx[2]; // StartIdx to extract from
2722 for (unsigned Input = 0; Input < 2; ++Input) {
2723 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
2724 RangeUse[Input] = 0; // Unused
2725 StartIdx[Input] = 0;
2729 // Find a good start index that is a multiple of the mask length. Then
2730 // see if the rest of the elements are in range.
2731 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2732 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2733 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2734 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2737 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2738 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2741 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
2742 // Extract appropriate subvector and generate a vector shuffle
2743 for (unsigned Input = 0; Input < 2; ++Input) {
2744 SDValue &Src = Input == 0 ? Src1 : Src2;
2745 if (RangeUse[Input] == 0)
2746 Src = DAG.getUNDEF(VT);
2748 SDLoc dl = getCurSDLoc();
2750 ISD::EXTRACT_SUBVECTOR, dl, VT, Src,
2751 DAG.getConstant(StartIdx[Input], dl,
2752 TLI.getVectorIdxTy(DAG.getDataLayout())));
2756 // Calculate new mask.
2757 SmallVector<int, 8> MappedOps;
2758 for (unsigned i = 0; i != MaskNumElts; ++i) {
2761 if (Idx < (int)SrcNumElts)
2764 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
2766 MappedOps.push_back(Idx);
2769 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2775 // We can't use either concat vectors or extract subvectors so fall back to
2776 // replacing the shuffle with extract and build vector.
2777 // to insert and build vector.
2778 EVT EltVT = VT.getVectorElementType();
2779 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
2780 SDLoc dl = getCurSDLoc();
2781 SmallVector<SDValue,8> Ops;
2782 for (unsigned i = 0; i != MaskNumElts; ++i) {
2787 Res = DAG.getUNDEF(EltVT);
2789 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
2790 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
2792 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2793 EltVT, Src, DAG.getConstant(Idx, dl, IdxVT));
2799 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops));
2802 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2803 const Value *Op0 = I.getOperand(0);
2804 const Value *Op1 = I.getOperand(1);
2805 Type *AggTy = I.getType();
2806 Type *ValTy = Op1->getType();
2807 bool IntoUndef = isa<UndefValue>(Op0);
2808 bool FromUndef = isa<UndefValue>(Op1);
2810 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
2812 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2813 SmallVector<EVT, 4> AggValueVTs;
2814 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
2815 SmallVector<EVT, 4> ValValueVTs;
2816 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
2818 unsigned NumAggValues = AggValueVTs.size();
2819 unsigned NumValValues = ValValueVTs.size();
2820 SmallVector<SDValue, 4> Values(NumAggValues);
2822 // Ignore an insertvalue that produces an empty object
2823 if (!NumAggValues) {
2824 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
2828 SDValue Agg = getValue(Op0);
2830 // Copy the beginning value(s) from the original aggregate.
2831 for (; i != LinearIndex; ++i)
2832 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2833 SDValue(Agg.getNode(), Agg.getResNo() + i);
2834 // Copy values from the inserted value(s).
2836 SDValue Val = getValue(Op1);
2837 for (; i != LinearIndex + NumValValues; ++i)
2838 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2839 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2841 // Copy remaining value(s) from the original aggregate.
2842 for (; i != NumAggValues; ++i)
2843 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2844 SDValue(Agg.getNode(), Agg.getResNo() + i);
2846 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2847 DAG.getVTList(AggValueVTs), Values));
2850 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2851 const Value *Op0 = I.getOperand(0);
2852 Type *AggTy = Op0->getType();
2853 Type *ValTy = I.getType();
2854 bool OutOfUndef = isa<UndefValue>(Op0);
2856 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
2858 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2859 SmallVector<EVT, 4> ValValueVTs;
2860 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
2862 unsigned NumValValues = ValValueVTs.size();
2864 // Ignore a extractvalue that produces an empty object
2865 if (!NumValValues) {
2866 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
2870 SmallVector<SDValue, 4> Values(NumValValues);
2872 SDValue Agg = getValue(Op0);
2873 // Copy out the selected value(s).
2874 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2875 Values[i - LinearIndex] =
2877 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2878 SDValue(Agg.getNode(), Agg.getResNo() + i);
2880 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2881 DAG.getVTList(ValValueVTs), Values));
2884 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2885 Value *Op0 = I.getOperand(0);
2886 // Note that the pointer operand may be a vector of pointers. Take the scalar
2887 // element which holds a pointer.
2888 Type *Ty = Op0->getType()->getScalarType();
2889 unsigned AS = Ty->getPointerAddressSpace();
2890 SDValue N = getValue(Op0);
2891 SDLoc dl = getCurSDLoc();
2893 // Normalize Vector GEP - all scalar operands should be converted to the
2895 unsigned VectorWidth = I.getType()->isVectorTy() ?
2896 cast<VectorType>(I.getType())->getVectorNumElements() : 0;
2898 if (VectorWidth && !N.getValueType().isVector()) {
2899 MVT VT = MVT::getVectorVT(N.getValueType().getSimpleVT(), VectorWidth);
2900 SmallVector<SDValue, 16> Ops(VectorWidth, N);
2901 N = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
2903 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2905 const Value *Idx = *OI;
2906 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
2907 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
2910 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
2911 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
2912 DAG.getConstant(Offset, dl, N.getValueType()));
2915 Ty = StTy->getElementType(Field);
2917 Ty = cast<SequentialType>(Ty)->getElementType();
2919 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout(), AS);
2920 unsigned PtrSize = PtrTy.getSizeInBits();
2921 APInt ElementSize(PtrSize, DL->getTypeAllocSize(Ty));
2923 // If this is a scalar constant or a splat vector of constants,
2924 // handle it quickly.
2925 const auto *CI = dyn_cast<ConstantInt>(Idx);
2926 if (!CI && isa<ConstantDataVector>(Idx) &&
2927 cast<ConstantDataVector>(Idx)->getSplatValue())
2928 CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
2933 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
2934 SDValue OffsVal = VectorWidth ?
2935 DAG.getConstant(Offs, dl, MVT::getVectorVT(PtrTy, VectorWidth)) :
2936 DAG.getConstant(Offs, dl, PtrTy);
2937 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal);
2941 // N = N + Idx * ElementSize;
2942 SDValue IdxN = getValue(Idx);
2944 if (!IdxN.getValueType().isVector() && VectorWidth) {
2945 MVT VT = MVT::getVectorVT(IdxN.getValueType().getSimpleVT(), VectorWidth);
2946 SmallVector<SDValue, 16> Ops(VectorWidth, IdxN);
2947 IdxN = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
2949 // If the index is smaller or larger than intptr_t, truncate or extend
2951 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
2953 // If this is a multiply by a power of two, turn it into a shl
2954 // immediately. This is a very common case.
2955 if (ElementSize != 1) {
2956 if (ElementSize.isPowerOf2()) {
2957 unsigned Amt = ElementSize.logBase2();
2958 IdxN = DAG.getNode(ISD::SHL, dl,
2959 N.getValueType(), IdxN,
2960 DAG.getConstant(Amt, dl, IdxN.getValueType()));
2962 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
2963 IdxN = DAG.getNode(ISD::MUL, dl,
2964 N.getValueType(), IdxN, Scale);
2968 N = DAG.getNode(ISD::ADD, dl,
2969 N.getValueType(), N, IdxN);
2976 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
2977 // If this is a fixed sized alloca in the entry block of the function,
2978 // allocate it statically on the stack.
2979 if (FuncInfo.StaticAllocaMap.count(&I))
2980 return; // getValue will auto-populate this.
2982 SDLoc dl = getCurSDLoc();
2983 Type *Ty = I.getAllocatedType();
2984 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2985 auto &DL = DAG.getDataLayout();
2986 uint64_t TySize = DL.getTypeAllocSize(Ty);
2988 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
2990 SDValue AllocSize = getValue(I.getArraySize());
2992 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout());
2993 if (AllocSize.getValueType() != IntPtr)
2994 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
2996 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
2998 DAG.getConstant(TySize, dl, IntPtr));
3000 // Handle alignment. If the requested alignment is less than or equal to
3001 // the stack alignment, ignore it. If the size is greater than or equal to
3002 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3003 unsigned StackAlign =
3004 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3005 if (Align <= StackAlign)
3008 // Round the size of the allocation up to the stack alignment size
3009 // by add SA-1 to the size.
3010 AllocSize = DAG.getNode(ISD::ADD, dl,
3011 AllocSize.getValueType(), AllocSize,
3012 DAG.getIntPtrConstant(StackAlign - 1, dl));
3014 // Mask out the low bits for alignment purposes.
3015 AllocSize = DAG.getNode(ISD::AND, dl,
3016 AllocSize.getValueType(), AllocSize,
3017 DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
3020 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
3021 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3022 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3024 DAG.setRoot(DSA.getValue(1));
3026 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
3029 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3031 return visitAtomicLoad(I);
3033 const Value *SV = I.getOperand(0);
3034 SDValue Ptr = getValue(SV);
3036 Type *Ty = I.getType();
3038 bool isVolatile = I.isVolatile();
3039 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3041 // The IR notion of invariant_load only guarantees that all *non-faulting*
3042 // invariant loads result in the same value. The MI notion of invariant load
3043 // guarantees that the load can be legally moved to any location within its
3044 // containing function. The MI notion of invariant_load is stronger than the
3045 // IR notion of invariant_load -- an MI invariant_load is an IR invariant_load
3046 // with a guarantee that the location being loaded from is dereferenceable
3047 // throughout the function's lifetime.
3049 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr &&
3050 isDereferenceablePointer(SV, DAG.getDataLayout());
3051 unsigned Alignment = I.getAlignment();
3054 I.getAAMetadata(AAInfo);
3055 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3057 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3058 SmallVector<EVT, 4> ValueVTs;
3059 SmallVector<uint64_t, 4> Offsets;
3060 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3061 unsigned NumValues = ValueVTs.size();
3066 bool ConstantMemory = false;
3067 if (isVolatile || NumValues > MaxParallelChains)
3068 // Serialize volatile loads with other side effects.
3070 else if (AA->pointsToConstantMemory(MemoryLocation(
3071 SV, DAG.getDataLayout().getTypeStoreSize(Ty), AAInfo))) {
3072 // Do not serialize (non-volatile) loads of constant memory with anything.
3073 Root = DAG.getEntryNode();
3074 ConstantMemory = true;
3076 // Do not serialize non-volatile loads against each other.
3077 Root = DAG.getRoot();
3080 SDLoc dl = getCurSDLoc();
3083 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3085 SmallVector<SDValue, 4> Values(NumValues);
3086 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3087 EVT PtrVT = Ptr.getValueType();
3088 unsigned ChainI = 0;
3089 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3090 // Serializing loads here may result in excessive register pressure, and
3091 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3092 // could recover a bit by hoisting nodes upward in the chain by recognizing
3093 // they are side-effect free or do not alias. The optimizer should really
3094 // avoid this case by converting large object/array copies to llvm.memcpy
3095 // (MaxParallelChains should always remain as failsafe).
3096 if (ChainI == MaxParallelChains) {
3097 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3098 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3099 makeArrayRef(Chains.data(), ChainI));
3103 SDValue A = DAG.getNode(ISD::ADD, dl,
3105 DAG.getConstant(Offsets[i], dl, PtrVT));
3106 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root,
3107 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3108 isNonTemporal, isInvariant, Alignment, AAInfo,
3112 Chains[ChainI] = L.getValue(1);
3115 if (!ConstantMemory) {
3116 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3117 makeArrayRef(Chains.data(), ChainI));
3121 PendingLoads.push_back(Chain);
3124 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3125 DAG.getVTList(ValueVTs), Values));
3128 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3130 return visitAtomicStore(I);
3132 const Value *SrcV = I.getOperand(0);
3133 const Value *PtrV = I.getOperand(1);
3135 SmallVector<EVT, 4> ValueVTs;
3136 SmallVector<uint64_t, 4> Offsets;
3137 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3138 SrcV->getType(), ValueVTs, &Offsets);
3139 unsigned NumValues = ValueVTs.size();
3143 // Get the lowered operands. Note that we do this after
3144 // checking if NumResults is zero, because with zero results
3145 // the operands won't have values in the map.
3146 SDValue Src = getValue(SrcV);
3147 SDValue Ptr = getValue(PtrV);
3149 SDValue Root = getRoot();
3150 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3151 EVT PtrVT = Ptr.getValueType();
3152 bool isVolatile = I.isVolatile();
3153 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3154 unsigned Alignment = I.getAlignment();
3155 SDLoc dl = getCurSDLoc();
3158 I.getAAMetadata(AAInfo);
3160 unsigned ChainI = 0;
3161 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3162 // See visitLoad comments.
3163 if (ChainI == MaxParallelChains) {
3164 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3165 makeArrayRef(Chains.data(), ChainI));
3169 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3170 DAG.getConstant(Offsets[i], dl, PtrVT));
3171 SDValue St = DAG.getStore(Root, dl,
3172 SDValue(Src.getNode(), Src.getResNo() + i),
3173 Add, MachinePointerInfo(PtrV, Offsets[i]),
3174 isVolatile, isNonTemporal, Alignment, AAInfo);
3175 Chains[ChainI] = St;
3178 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3179 makeArrayRef(Chains.data(), ChainI));
3180 DAG.setRoot(StoreNode);
3183 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
3184 SDLoc sdl = getCurSDLoc();
3186 // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3187 Value *PtrOperand = I.getArgOperand(1);
3188 SDValue Ptr = getValue(PtrOperand);
3189 SDValue Src0 = getValue(I.getArgOperand(0));
3190 SDValue Mask = getValue(I.getArgOperand(3));
3191 EVT VT = Src0.getValueType();
3192 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3194 Alignment = DAG.getEVTAlignment(VT);
3197 I.getAAMetadata(AAInfo);
3199 MachineMemOperand *MMO =
3200 DAG.getMachineFunction().
3201 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3202 MachineMemOperand::MOStore, VT.getStoreSize(),
3204 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3206 DAG.setRoot(StoreNode);
3207 setValue(&I, StoreNode);
3210 // Get a uniform base for the Gather/Scatter intrinsic.
3211 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3212 // We try to represent it as a base pointer + vector of indices.
3213 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3214 // The first operand of the GEP may be a single pointer or a vector of pointers
3216 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3218 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
3219 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3221 // When the first GEP operand is a single pointer - it is the uniform base we
3222 // are looking for. If first operand of the GEP is a splat vector - we
3223 // extract the spalt value and use it as a uniform base.
3224 // In all other cases the function returns 'false'.
3226 static bool getUniformBase(Value *& Ptr, SDValue& Base, SDValue& Index,
3227 SelectionDAGBuilder* SDB) {
3229 SelectionDAG& DAG = SDB->DAG;
3230 LLVMContext &Context = *DAG.getContext();
3232 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3233 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3234 if (!GEP || GEP->getNumOperands() > 2)
3237 Value *GEPPtr = GEP->getPointerOperand();
3238 if (!GEPPtr->getType()->isVectorTy())
3240 else if (!(Ptr = getSplatValue(GEPPtr)))
3243 Value *IndexVal = GEP->getOperand(1);
3245 // The operands of the GEP may be defined in another basic block.
3246 // In this case we'll not find nodes for the operands.
3247 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3250 Base = SDB->getValue(Ptr);
3251 Index = SDB->getValue(IndexVal);
3253 // Suppress sign extension.
3254 if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) {
3255 if (SDB->findValue(Sext->getOperand(0))) {
3256 IndexVal = Sext->getOperand(0);
3257 Index = SDB->getValue(IndexVal);
3260 if (!Index.getValueType().isVector()) {
3261 unsigned GEPWidth = GEP->getType()->getVectorNumElements();
3262 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
3263 SmallVector<SDValue, 16> Ops(GEPWidth, Index);
3264 Index = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(Index), VT, Ops);
3269 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3270 SDLoc sdl = getCurSDLoc();
3272 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3273 Value *Ptr = I.getArgOperand(1);
3274 SDValue Src0 = getValue(I.getArgOperand(0));
3275 SDValue Mask = getValue(I.getArgOperand(3));
3276 EVT VT = Src0.getValueType();
3277 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3279 Alignment = DAG.getEVTAlignment(VT);
3280 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3283 I.getAAMetadata(AAInfo);
3287 Value *BasePtr = Ptr;
3288 bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3290 Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3291 MachineMemOperand *MMO = DAG.getMachineFunction().
3292 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3293 MachineMemOperand::MOStore, VT.getStoreSize(),
3296 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3297 Index = getValue(Ptr);
3299 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
3300 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3302 DAG.setRoot(Scatter);
3303 setValue(&I, Scatter);
3306 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
3307 SDLoc sdl = getCurSDLoc();
3309 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
3310 Value *PtrOperand = I.getArgOperand(0);
3311 SDValue Ptr = getValue(PtrOperand);
3312 SDValue Src0 = getValue(I.getArgOperand(3));
3313 SDValue Mask = getValue(I.getArgOperand(2));
3315 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3316 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3317 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3319 Alignment = DAG.getEVTAlignment(VT);
3322 I.getAAMetadata(AAInfo);
3323 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3325 SDValue InChain = DAG.getRoot();
3326 if (AA->pointsToConstantMemory(MemoryLocation(
3327 PtrOperand, DAG.getDataLayout().getTypeStoreSize(I.getType()),
3329 // Do not serialize (non-volatile) loads of constant memory with anything.
3330 InChain = DAG.getEntryNode();
3333 MachineMemOperand *MMO =
3334 DAG.getMachineFunction().
3335 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3336 MachineMemOperand::MOLoad, VT.getStoreSize(),
3337 Alignment, AAInfo, Ranges);
3339 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
3341 SDValue OutChain = Load.getValue(1);
3342 DAG.setRoot(OutChain);
3346 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
3347 SDLoc sdl = getCurSDLoc();
3349 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
3350 Value *Ptr = I.getArgOperand(0);
3351 SDValue Src0 = getValue(I.getArgOperand(3));
3352 SDValue Mask = getValue(I.getArgOperand(2));
3354 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3355 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3356 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3358 Alignment = DAG.getEVTAlignment(VT);
3361 I.getAAMetadata(AAInfo);
3362 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3364 SDValue Root = DAG.getRoot();
3367 Value *BasePtr = Ptr;
3368 bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3369 bool ConstantMemory = false;
3371 AA->pointsToConstantMemory(MemoryLocation(
3372 BasePtr, DAG.getDataLayout().getTypeStoreSize(I.getType()),
3374 // Do not serialize (non-volatile) loads of constant memory with anything.
3375 Root = DAG.getEntryNode();
3376 ConstantMemory = true;
3379 MachineMemOperand *MMO =
3380 DAG.getMachineFunction().
3381 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
3382 MachineMemOperand::MOLoad, VT.getStoreSize(),
3383 Alignment, AAInfo, Ranges);
3386 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
3387 Index = getValue(Ptr);
3389 SDValue Ops[] = { Root, Src0, Mask, Base, Index };
3390 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
3393 SDValue OutChain = Gather.getValue(1);
3394 if (!ConstantMemory)
3395 PendingLoads.push_back(OutChain);
3396 setValue(&I, Gather);
3399 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3400 SDLoc dl = getCurSDLoc();
3401 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3402 AtomicOrdering FailureOrder = I.getFailureOrdering();
3403 SynchronizationScope Scope = I.getSynchScope();
3405 SDValue InChain = getRoot();
3407 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3408 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3409 SDValue L = DAG.getAtomicCmpSwap(
3410 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3411 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3412 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3413 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3415 SDValue OutChain = L.getValue(2);
3418 DAG.setRoot(OutChain);
3421 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3422 SDLoc dl = getCurSDLoc();
3424 switch (I.getOperation()) {
3425 default: llvm_unreachable("Unknown atomicrmw operation");
3426 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3427 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3428 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3429 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3430 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3431 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3432 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3433 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3434 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3435 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3436 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3438 AtomicOrdering Order = I.getOrdering();
3439 SynchronizationScope Scope = I.getSynchScope();
3441 SDValue InChain = getRoot();
3444 DAG.getAtomic(NT, dl,
3445 getValue(I.getValOperand()).getSimpleValueType(),
3447 getValue(I.getPointerOperand()),
3448 getValue(I.getValOperand()),
3449 I.getPointerOperand(),
3450 /* Alignment=*/ 0, Order, Scope);
3452 SDValue OutChain = L.getValue(1);
3455 DAG.setRoot(OutChain);
3458 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3459 SDLoc dl = getCurSDLoc();
3460 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3463 Ops[1] = DAG.getConstant(I.getOrdering(), dl,
3464 TLI.getPointerTy(DAG.getDataLayout()));
3465 Ops[2] = DAG.getConstant(I.getSynchScope(), dl,
3466 TLI.getPointerTy(DAG.getDataLayout()));
3467 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3470 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3471 SDLoc dl = getCurSDLoc();
3472 AtomicOrdering Order = I.getOrdering();
3473 SynchronizationScope Scope = I.getSynchScope();
3475 SDValue InChain = getRoot();
3477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3478 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3480 if (I.getAlignment() < VT.getSizeInBits() / 8)
3481 report_fatal_error("Cannot generate unaligned atomic load");
3483 MachineMemOperand *MMO =
3484 DAG.getMachineFunction().
3485 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3486 MachineMemOperand::MOVolatile |
3487 MachineMemOperand::MOLoad,
3489 I.getAlignment() ? I.getAlignment() :
3490 DAG.getEVTAlignment(VT));
3492 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3494 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3495 getValue(I.getPointerOperand()), MMO,
3498 SDValue OutChain = L.getValue(1);
3501 DAG.setRoot(OutChain);
3504 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3505 SDLoc dl = getCurSDLoc();
3507 AtomicOrdering Order = I.getOrdering();
3508 SynchronizationScope Scope = I.getSynchScope();
3510 SDValue InChain = getRoot();
3512 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3514 TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
3516 if (I.getAlignment() < VT.getSizeInBits() / 8)
3517 report_fatal_error("Cannot generate unaligned atomic store");
3520 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3522 getValue(I.getPointerOperand()),
3523 getValue(I.getValueOperand()),
3524 I.getPointerOperand(), I.getAlignment(),
3527 DAG.setRoot(OutChain);
3530 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3532 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3533 unsigned Intrinsic) {
3534 bool HasChain = !I.doesNotAccessMemory();
3535 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3537 // Build the operand list.
3538 SmallVector<SDValue, 8> Ops;
3539 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3541 // We don't need to serialize loads against other loads.
3542 Ops.push_back(DAG.getRoot());
3544 Ops.push_back(getRoot());
3548 // Info is set by getTgtMemInstrinsic
3549 TargetLowering::IntrinsicInfo Info;
3550 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3551 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3553 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3554 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3555 Info.opc == ISD::INTRINSIC_W_CHAIN)
3556 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
3557 TLI.getPointerTy(DAG.getDataLayout())));
3559 // Add all operands of the call to the operand list.
3560 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3561 SDValue Op = getValue(I.getArgOperand(i));
3565 SmallVector<EVT, 4> ValueVTs;
3566 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
3569 ValueVTs.push_back(MVT::Other);
3571 SDVTList VTs = DAG.getVTList(ValueVTs);
3575 if (IsTgtIntrinsic) {
3576 // This is target intrinsic that touches memory
3577 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3578 VTs, Ops, Info.memVT,
3579 MachinePointerInfo(Info.ptrVal, Info.offset),
3580 Info.align, Info.vol,
3581 Info.readMem, Info.writeMem, Info.size);
3582 } else if (!HasChain) {
3583 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
3584 } else if (!I.getType()->isVoidTy()) {
3585 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
3587 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
3591 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3593 PendingLoads.push_back(Chain);
3598 if (!I.getType()->isVoidTy()) {
3599 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3600 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
3601 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3604 setValue(&I, Result);
3608 /// GetSignificand - Get the significand and build it into a floating-point
3609 /// number with exponent of 1:
3611 /// Op = (Op & 0x007fffff) | 0x3f800000;
3613 /// where Op is the hexadecimal representation of floating point value.
3615 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3616 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3617 DAG.getConstant(0x007fffff, dl, MVT::i32));
3618 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3619 DAG.getConstant(0x3f800000, dl, MVT::i32));
3620 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3623 /// GetExponent - Get the exponent:
3625 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3627 /// where Op is the hexadecimal representation of floating point value.
3629 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3631 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3632 DAG.getConstant(0x7f800000, dl, MVT::i32));
3633 SDValue t1 = DAG.getNode(
3634 ISD::SRL, dl, MVT::i32, t0,
3635 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
3636 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3637 DAG.getConstant(127, dl, MVT::i32));
3638 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3641 /// getF32Constant - Get 32-bit floating point constant.
3643 getF32Constant(SelectionDAG &DAG, unsigned Flt, SDLoc dl) {
3644 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl,
3648 static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl,
3649 SelectionDAG &DAG) {
3650 // TODO: What fast-math-flags should be set on the floating-point nodes?
3652 // IntegerPartOfX = ((int32_t)(t0);
3653 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3655 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
3656 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3657 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3659 // IntegerPartOfX <<= 23;
3660 IntegerPartOfX = DAG.getNode(
3661 ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3662 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
3663 DAG.getDataLayout())));
3665 SDValue TwoToFractionalPartOfX;
3666 if (LimitFloatPrecision <= 6) {
3667 // For floating-point precision of 6:
3669 // TwoToFractionalPartOfX =
3671 // (0.735607626f + 0.252464424f * x) * x;
3673 // error 0.0144103317, which is 6 bits
3674 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3675 getF32Constant(DAG, 0x3e814304, dl));
3676 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3677 getF32Constant(DAG, 0x3f3c50c8, dl));
3678 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3679 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3680 getF32Constant(DAG, 0x3f7f5e7e, dl));
3681 } else if (LimitFloatPrecision <= 12) {
3682 // For floating-point precision of 12:
3684 // TwoToFractionalPartOfX =
3687 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3689 // error 0.000107046256, which is 13 to 14 bits
3690 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3691 getF32Constant(DAG, 0x3da235e3, dl));
3692 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3693 getF32Constant(DAG, 0x3e65b8f3, dl));
3694 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3695 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3696 getF32Constant(DAG, 0x3f324b07, dl));
3697 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3698 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3699 getF32Constant(DAG, 0x3f7ff8fd, dl));
3700 } else { // LimitFloatPrecision <= 18
3701 // For floating-point precision of 18:
3703 // TwoToFractionalPartOfX =
3707 // (0.554906021e-1f +
3708 // (0.961591928e-2f +
3709 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3710 // error 2.47208000*10^(-7), which is better than 18 bits
3711 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3712 getF32Constant(DAG, 0x3924b03e, dl));
3713 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3714 getF32Constant(DAG, 0x3ab24b87, dl));
3715 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3716 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3717 getF32Constant(DAG, 0x3c1d8c17, dl));
3718 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3719 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3720 getF32Constant(DAG, 0x3d634a1d, dl));
3721 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3722 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3723 getF32Constant(DAG, 0x3e75fe14, dl));
3724 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3725 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3726 getF32Constant(DAG, 0x3f317234, dl));
3727 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3728 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3729 getF32Constant(DAG, 0x3f800000, dl));
3732 // Add the exponent into the result in integer domain.
3733 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
3734 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3735 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
3738 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
3739 /// limited-precision mode.
3740 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3741 const TargetLowering &TLI) {
3742 if (Op.getValueType() == MVT::f32 &&
3743 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3745 // Put the exponent in the right bit position for later addition to the
3748 // #define LOG2OFe 1.4426950f
3749 // t0 = Op * LOG2OFe
3751 // TODO: What fast-math-flags should be set here?
3752 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3753 getF32Constant(DAG, 0x3fb8aa3b, dl));
3754 return getLimitedPrecisionExp2(t0, dl, DAG);
3757 // No special expansion.
3758 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
3761 /// expandLog - Lower a log intrinsic. Handles the special sequences for
3762 /// limited-precision mode.
3763 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3764 const TargetLowering &TLI) {
3766 // TODO: What fast-math-flags should be set on the floating-point nodes?
3768 if (Op.getValueType() == MVT::f32 &&
3769 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3770 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3772 // Scale the exponent by log(2) [0.69314718f].
3773 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3774 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3775 getF32Constant(DAG, 0x3f317218, dl));
3777 // Get the significand and build it into a floating-point number with
3779 SDValue X = GetSignificand(DAG, Op1, dl);
3781 SDValue LogOfMantissa;
3782 if (LimitFloatPrecision <= 6) {
3783 // For floating-point precision of 6:
3787 // (1.4034025f - 0.23903021f * x) * x;
3789 // error 0.0034276066, which is better than 8 bits
3790 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3791 getF32Constant(DAG, 0xbe74c456, dl));
3792 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3793 getF32Constant(DAG, 0x3fb3a2b1, dl));
3794 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3795 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3796 getF32Constant(DAG, 0x3f949a29, dl));
3797 } else if (LimitFloatPrecision <= 12) {
3798 // For floating-point precision of 12:
3804 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3806 // error 0.000061011436, which is 14 bits
3807 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3808 getF32Constant(DAG, 0xbd67b6d6, dl));
3809 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3810 getF32Constant(DAG, 0x3ee4f4b8, dl));
3811 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3812 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3813 getF32Constant(DAG, 0x3fbc278b, dl));
3814 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3815 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3816 getF32Constant(DAG, 0x40348e95, dl));
3817 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3818 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3819 getF32Constant(DAG, 0x3fdef31a, dl));
3820 } else { // LimitFloatPrecision <= 18
3821 // For floating-point precision of 18:
3829 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3831 // error 0.0000023660568, which is better than 18 bits
3832 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3833 getF32Constant(DAG, 0xbc91e5ac, dl));
3834 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3835 getF32Constant(DAG, 0x3e4350aa, dl));
3836 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3837 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3838 getF32Constant(DAG, 0x3f60d3e3, dl));
3839 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3840 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3841 getF32Constant(DAG, 0x4011cdf0, dl));
3842 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3843 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3844 getF32Constant(DAG, 0x406cfd1c, dl));
3845 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3846 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3847 getF32Constant(DAG, 0x408797cb, dl));
3848 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3849 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3850 getF32Constant(DAG, 0x4006dcab, dl));
3853 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
3856 // No special expansion.
3857 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
3860 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
3861 /// limited-precision mode.
3862 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3863 const TargetLowering &TLI) {
3865 // TODO: What fast-math-flags should be set on the floating-point nodes?
3867 if (Op.getValueType() == MVT::f32 &&
3868 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3869 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3871 // Get the exponent.
3872 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3874 // Get the significand and build it into a floating-point number with
3876 SDValue X = GetSignificand(DAG, Op1, dl);
3878 // Different possible minimax approximations of significand in
3879 // floating-point for various degrees of accuracy over [1,2].
3880 SDValue Log2ofMantissa;
3881 if (LimitFloatPrecision <= 6) {
3882 // For floating-point precision of 6:
3884 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3886 // error 0.0049451742, which is more than 7 bits
3887 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3888 getF32Constant(DAG, 0xbeb08fe0, dl));
3889 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3890 getF32Constant(DAG, 0x40019463, dl));
3891 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3892 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3893 getF32Constant(DAG, 0x3fd6633d, dl));
3894 } else if (LimitFloatPrecision <= 12) {
3895 // For floating-point precision of 12:
3901 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3903 // error 0.0000876136000, which is better than 13 bits
3904 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3905 getF32Constant(DAG, 0xbda7262e, dl));
3906 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3907 getF32Constant(DAG, 0x3f25280b, dl));
3908 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3909 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3910 getF32Constant(DAG, 0x4007b923, dl));
3911 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3912 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3913 getF32Constant(DAG, 0x40823e2f, dl));
3914 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3915 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3916 getF32Constant(DAG, 0x4020d29c, dl));
3917 } else { // LimitFloatPrecision <= 18
3918 // For floating-point precision of 18:
3927 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3929 // error 0.0000018516, which is better than 18 bits
3930 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3931 getF32Constant(DAG, 0xbcd2769e, dl));
3932 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3933 getF32Constant(DAG, 0x3e8ce0b9, dl));
3934 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3935 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3936 getF32Constant(DAG, 0x3fa22ae7, dl));
3937 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3938 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3939 getF32Constant(DAG, 0x40525723, dl));
3940 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3941 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3942 getF32Constant(DAG, 0x40aaf200, dl));
3943 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3944 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3945 getF32Constant(DAG, 0x40c39dad, dl));
3946 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3947 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3948 getF32Constant(DAG, 0x4042902c, dl));
3951 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
3954 // No special expansion.
3955 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
3958 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
3959 /// limited-precision mode.
3960 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3961 const TargetLowering &TLI) {
3963 // TODO: What fast-math-flags should be set on the floating-point nodes?
3965 if (Op.getValueType() == MVT::f32 &&
3966 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3967 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3969 // Scale the exponent by log10(2) [0.30102999f].
3970 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3971 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3972 getF32Constant(DAG, 0x3e9a209a, dl));
3974 // Get the significand and build it into a floating-point number with
3976 SDValue X = GetSignificand(DAG, Op1, dl);
3978 SDValue Log10ofMantissa;
3979 if (LimitFloatPrecision <= 6) {
3980 // For floating-point precision of 6:
3982 // Log10ofMantissa =
3984 // (0.60948995f - 0.10380950f * x) * x;
3986 // error 0.0014886165, which is 6 bits
3987 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3988 getF32Constant(DAG, 0xbdd49a13, dl));
3989 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3990 getF32Constant(DAG, 0x3f1c0789, dl));
3991 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3992 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3993 getF32Constant(DAG, 0x3f011300, dl));
3994 } else if (LimitFloatPrecision <= 12) {
3995 // For floating-point precision of 12:
3997 // Log10ofMantissa =
4000 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4002 // error 0.00019228036, which is better than 12 bits
4003 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4004 getF32Constant(DAG, 0x3d431f31, dl));
4005 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4006 getF32Constant(DAG, 0x3ea21fb2, dl));
4007 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4008 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4009 getF32Constant(DAG, 0x3f6ae232, dl));
4010 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4011 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4012 getF32Constant(DAG, 0x3f25f7c3, dl));
4013 } else { // LimitFloatPrecision <= 18
4014 // For floating-point precision of 18:
4016 // Log10ofMantissa =
4021 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4023 // error 0.0000037995730, which is better than 18 bits
4024 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4025 getF32Constant(DAG, 0x3c5d51ce, dl));
4026 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4027 getF32Constant(DAG, 0x3e00685a, dl));
4028 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4029 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4030 getF32Constant(DAG, 0x3efb6798, dl));
4031 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4032 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4033 getF32Constant(DAG, 0x3f88d192, dl));
4034 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4035 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4036 getF32Constant(DAG, 0x3fc4316c, dl));
4037 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4038 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4039 getF32Constant(DAG, 0x3f57ce70, dl));
4042 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4045 // No special expansion.
4046 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4049 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4050 /// limited-precision mode.
4051 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
4052 const TargetLowering &TLI) {
4053 if (Op.getValueType() == MVT::f32 &&
4054 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4055 return getLimitedPrecisionExp2(Op, dl, DAG);
4057 // No special expansion.
4058 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4061 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4062 /// limited-precision mode with x == 10.0f.
4063 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
4064 SelectionDAG &DAG, const TargetLowering &TLI) {
4065 bool IsExp10 = false;
4066 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4067 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4068 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4070 IsExp10 = LHSC->isExactlyValue(Ten);
4074 // TODO: What fast-math-flags should be set on the FMUL node?
4076 // Put the exponent in the right bit position for later addition to the
4079 // #define LOG2OF10 3.3219281f
4080 // t0 = Op * LOG2OF10;
4081 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4082 getF32Constant(DAG, 0x40549a78, dl));
4083 return getLimitedPrecisionExp2(t0, dl, DAG);
4086 // No special expansion.
4087 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4091 /// ExpandPowI - Expand a llvm.powi intrinsic.
4092 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
4093 SelectionDAG &DAG) {
4094 // If RHS is a constant, we can expand this out to a multiplication tree,
4095 // otherwise we end up lowering to a call to __powidf2 (for example). When
4096 // optimizing for size, we only want to do this if the expansion would produce
4097 // a small number of multiplies, otherwise we do the full expansion.
4098 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4099 // Get the exponent as a positive value.
4100 unsigned Val = RHSC->getSExtValue();
4101 if ((int)Val < 0) Val = -Val;
4103 // powi(x, 0) -> 1.0
4105 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4107 const Function *F = DAG.getMachineFunction().getFunction();
4108 if (!F->optForSize() ||
4109 // If optimizing for size, don't insert too many multiplies.
4110 // This inserts up to 5 multiplies.
4111 countPopulation(Val) + Log2_32(Val) < 7) {
4112 // We use the simple binary decomposition method to generate the multiply
4113 // sequence. There are more optimal ways to do this (for example,
4114 // powi(x,15) generates one more multiply than it should), but this has
4115 // the benefit of being both really simple and much better than a libcall.
4116 SDValue Res; // Logically starts equal to 1.0
4117 SDValue CurSquare = LHS;
4118 // TODO: Intrinsics should have fast-math-flags that propagate to these
4123 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4125 Res = CurSquare; // 1.0*CurSquare.
4128 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4129 CurSquare, CurSquare);
4133 // If the original was negative, invert the result, producing 1/(x*x*x).
4134 if (RHSC->getSExtValue() < 0)
4135 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4136 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4141 // Otherwise, expand to a libcall.
4142 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4145 // getTruncatedArgReg - Find underlying register used for an truncated
4147 static unsigned getTruncatedArgReg(const SDValue &N) {
4148 if (N.getOpcode() != ISD::TRUNCATE)
4151 const SDValue &Ext = N.getOperand(0);
4152 if (Ext.getOpcode() == ISD::AssertZext ||
4153 Ext.getOpcode() == ISD::AssertSext) {
4154 const SDValue &CFR = Ext.getOperand(0);
4155 if (CFR.getOpcode() == ISD::CopyFromReg)
4156 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4157 if (CFR.getOpcode() == ISD::TRUNCATE)
4158 return getTruncatedArgReg(CFR);
4163 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4164 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4165 /// At the end of instruction selection, they will be inserted to the entry BB.
4166 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4167 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4168 DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
4169 const Argument *Arg = dyn_cast<Argument>(V);
4173 MachineFunction &MF = DAG.getMachineFunction();
4174 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4176 // Ignore inlined function arguments here.
4178 // FIXME: Should we be checking DL->inlinedAt() to determine this?
4179 if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
4182 Optional<MachineOperand> Op;
4183 // Some arguments' frame index is recorded during argument lowering.
4184 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
4185 Op = MachineOperand::CreateFI(FI);
4187 if (!Op && N.getNode()) {
4189 if (N.getOpcode() == ISD::CopyFromReg)
4190 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4192 Reg = getTruncatedArgReg(N);
4193 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4194 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4195 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4200 Op = MachineOperand::CreateReg(Reg, false);
4204 // Check if ValueMap has reg number.
4205 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4206 if (VMI != FuncInfo.ValueMap.end())
4207 Op = MachineOperand::CreateReg(VMI->second, false);
4210 if (!Op && N.getNode())
4211 // Check if frame index is available.
4212 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4213 if (FrameIndexSDNode *FINode =
4214 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4215 Op = MachineOperand::CreateFI(FINode->getIndex());
4220 assert(Variable->isValidLocationForIntrinsic(DL) &&
4221 "Expected inlined-at fields to agree");
4223 FuncInfo.ArgDbgValues.push_back(
4224 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4225 Op->getReg(), Offset, Variable, Expr));
4227 FuncInfo.ArgDbgValues.push_back(
4228 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4231 .addMetadata(Variable)
4232 .addMetadata(Expr));
4237 // VisualStudio defines setjmp as _setjmp
4238 #if defined(_MSC_VER) && defined(setjmp) && \
4239 !defined(setjmp_undefined_for_msvc)
4240 # pragma push_macro("setjmp")
4242 # define setjmp_undefined_for_msvc
4245 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4246 /// we want to emit this as a call to a named external function, return the name
4247 /// otherwise lower it and return null.
4249 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4250 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4251 SDLoc sdl = getCurSDLoc();
4252 DebugLoc dl = getCurDebugLoc();
4255 switch (Intrinsic) {
4257 // By default, turn this into a target intrinsic node.
4258 visitTargetIntrinsic(I, Intrinsic);
4260 case Intrinsic::vastart: visitVAStart(I); return nullptr;
4261 case Intrinsic::vaend: visitVAEnd(I); return nullptr;
4262 case Intrinsic::vacopy: visitVACopy(I); return nullptr;
4263 case Intrinsic::returnaddress:
4264 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
4265 TLI.getPointerTy(DAG.getDataLayout()),
4266 getValue(I.getArgOperand(0))));
4268 case Intrinsic::frameaddress:
4269 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
4270 TLI.getPointerTy(DAG.getDataLayout()),
4271 getValue(I.getArgOperand(0))));
4273 case Intrinsic::read_register: {
4274 Value *Reg = I.getArgOperand(0);
4275 SDValue Chain = getRoot();
4277 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4278 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4279 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
4280 DAG.getVTList(VT, MVT::Other), Chain, RegName);
4282 DAG.setRoot(Res.getValue(1));
4285 case Intrinsic::write_register: {
4286 Value *Reg = I.getArgOperand(0);
4287 Value *RegValue = I.getArgOperand(1);
4288 SDValue Chain = getRoot();
4290 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4291 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4292 RegName, getValue(RegValue)));
4295 case Intrinsic::setjmp:
4296 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
4297 case Intrinsic::longjmp:
4298 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
4299 case Intrinsic::memcpy: {
4300 // FIXME: this definition of "user defined address space" is x86-specific
4301 // Assert for address < 256 since we support only user defined address
4303 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4305 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4307 "Unknown address space");
4308 SDValue Op1 = getValue(I.getArgOperand(0));
4309 SDValue Op2 = getValue(I.getArgOperand(1));
4310 SDValue Op3 = getValue(I.getArgOperand(2));
4311 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4313 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4314 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4315 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4316 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4318 MachinePointerInfo(I.getArgOperand(0)),
4319 MachinePointerInfo(I.getArgOperand(1)));
4320 updateDAGForMaybeTailCall(MC);
4323 case Intrinsic::memset: {
4324 // FIXME: this definition of "user defined address space" is x86-specific
4325 // Assert for address < 256 since we support only user defined address
4327 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4329 "Unknown address space");
4330 SDValue Op1 = getValue(I.getArgOperand(0));
4331 SDValue Op2 = getValue(I.getArgOperand(1));
4332 SDValue Op3 = getValue(I.getArgOperand(2));
4333 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4335 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4336 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4337 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4338 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4339 isTC, MachinePointerInfo(I.getArgOperand(0)));
4340 updateDAGForMaybeTailCall(MS);
4343 case Intrinsic::memmove: {
4344 // FIXME: this definition of "user defined address space" is x86-specific
4345 // Assert for address < 256 since we support only user defined address
4347 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4349 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4351 "Unknown address space");
4352 SDValue Op1 = getValue(I.getArgOperand(0));
4353 SDValue Op2 = getValue(I.getArgOperand(1));
4354 SDValue Op3 = getValue(I.getArgOperand(2));
4355 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4357 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4358 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4359 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4360 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4361 isTC, MachinePointerInfo(I.getArgOperand(0)),
4362 MachinePointerInfo(I.getArgOperand(1)));
4363 updateDAGForMaybeTailCall(MM);
4366 case Intrinsic::dbg_declare: {
4367 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4368 DILocalVariable *Variable = DI.getVariable();
4369 DIExpression *Expression = DI.getExpression();
4370 const Value *Address = DI.getAddress();
4371 assert(Variable && "Missing variable");
4373 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4377 // Check if address has undef value.
4378 if (isa<UndefValue>(Address) ||
4379 (Address->use_empty() && !isa<Argument>(Address))) {
4380 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4384 SDValue &N = NodeMap[Address];
4385 if (!N.getNode() && isa<Argument>(Address))
4386 // Check unused arguments map.
4387 N = UnusedArgNodeMap[Address];
4390 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4391 Address = BCI->getOperand(0);
4392 // Parameters are handled specially.
4393 bool isParameter = Variable->isParameter() || isa<Argument>(Address);
4395 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4397 if (isParameter && !AI) {
4398 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4400 // Byval parameter. We have a frame index at this point.
4401 SDV = DAG.getFrameIndexDbgValue(
4402 Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
4404 // Address is an argument, so try to emit its dbg value using
4405 // virtual register info from the FuncInfo.ValueMap.
4406 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4411 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4412 true, 0, dl, SDNodeOrder);
4414 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4416 // If Address is an argument then try to emit its dbg value using
4417 // virtual register info from the FuncInfo.ValueMap.
4418 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4420 // If variable is pinned by a alloca in dominating bb then
4421 // use StaticAllocaMap.
4422 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4423 if (AI->getParent() != DI.getParent()) {
4424 DenseMap<const AllocaInst*, int>::iterator SI =
4425 FuncInfo.StaticAllocaMap.find(AI);
4426 if (SI != FuncInfo.StaticAllocaMap.end()) {
4427 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
4428 0, dl, SDNodeOrder);
4429 DAG.AddDbgValue(SDV, nullptr, false);
4434 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4439 case Intrinsic::dbg_value: {
4440 const DbgValueInst &DI = cast<DbgValueInst>(I);
4441 assert(DI.getVariable() && "Missing variable");
4443 DILocalVariable *Variable = DI.getVariable();
4444 DIExpression *Expression = DI.getExpression();
4445 uint64_t Offset = DI.getOffset();
4446 const Value *V = DI.getValue();
4451 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4452 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4454 DAG.AddDbgValue(SDV, nullptr, false);
4456 // Do not use getValue() in here; we don't want to generate code at
4457 // this point if it hasn't been done yet.
4458 SDValue N = NodeMap[V];
4459 if (!N.getNode() && isa<Argument>(V))
4460 // Check unused arguments map.
4461 N = UnusedArgNodeMap[V];
4463 // A dbg.value for an alloca is always indirect.
4464 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
4465 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
4467 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4468 IsIndirect, Offset, dl, SDNodeOrder);
4469 DAG.AddDbgValue(SDV, N.getNode(), false);
4471 } else if (!V->use_empty() ) {
4472 // Do not call getValue(V) yet, as we don't want to generate code.
4473 // Remember it for later.
4474 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4475 DanglingDebugInfoMap[V] = DDI;
4477 // We may expand this to cover more cases. One case where we have no
4478 // data available is an unreferenced parameter.
4479 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4483 // Build a debug info table entry.
4484 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4485 V = BCI->getOperand(0);
4486 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4487 // Don't handle byval struct arguments or VLAs, for example.
4489 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4490 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
4493 DenseMap<const AllocaInst*, int>::iterator SI =
4494 FuncInfo.StaticAllocaMap.find(AI);
4495 if (SI == FuncInfo.StaticAllocaMap.end())
4496 return nullptr; // VLAs.
4500 case Intrinsic::eh_typeid_for: {
4501 // Find the type id for the given typeinfo.
4502 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
4503 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4504 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
4509 case Intrinsic::eh_return_i32:
4510 case Intrinsic::eh_return_i64:
4511 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4512 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4515 getValue(I.getArgOperand(0)),
4516 getValue(I.getArgOperand(1))));
4518 case Intrinsic::eh_unwind_init:
4519 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4521 case Intrinsic::eh_dwarf_cfa: {
4522 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4523 TLI.getPointerTy(DAG.getDataLayout()));
4524 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4525 CfaArg.getValueType(),
4526 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4527 CfaArg.getValueType()),
4529 SDValue FA = DAG.getNode(
4530 ISD::FRAMEADDR, sdl, TLI.getPointerTy(DAG.getDataLayout()),
4531 DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
4532 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4536 case Intrinsic::eh_sjlj_callsite: {
4537 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4538 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4539 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4540 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4542 MMI.setCurrentCallSite(CI->getZExtValue());
4545 case Intrinsic::eh_sjlj_functioncontext: {
4546 // Get and store the index of the function context.
4547 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4549 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4550 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4551 MFI->setFunctionContextIndex(FI);
4554 case Intrinsic::eh_sjlj_setjmp: {
4557 Ops[1] = getValue(I.getArgOperand(0));
4558 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4559 DAG.getVTList(MVT::i32, MVT::Other), Ops);
4560 setValue(&I, Op.getValue(0));
4561 DAG.setRoot(Op.getValue(1));
4564 case Intrinsic::eh_sjlj_longjmp: {
4565 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4566 getRoot(), getValue(I.getArgOperand(0))));
4569 case Intrinsic::eh_sjlj_setup_dispatch: {
4570 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
4575 case Intrinsic::masked_gather:
4576 visitMaskedGather(I);
4578 case Intrinsic::masked_load:
4581 case Intrinsic::masked_scatter:
4582 visitMaskedScatter(I);
4584 case Intrinsic::masked_store:
4585 visitMaskedStore(I);
4587 case Intrinsic::x86_mmx_pslli_w:
4588 case Intrinsic::x86_mmx_pslli_d:
4589 case Intrinsic::x86_mmx_pslli_q:
4590 case Intrinsic::x86_mmx_psrli_w:
4591 case Intrinsic::x86_mmx_psrli_d:
4592 case Intrinsic::x86_mmx_psrli_q:
4593 case Intrinsic::x86_mmx_psrai_w:
4594 case Intrinsic::x86_mmx_psrai_d: {
4595 SDValue ShAmt = getValue(I.getArgOperand(1));
4596 if (isa<ConstantSDNode>(ShAmt)) {
4597 visitTargetIntrinsic(I, Intrinsic);
4600 unsigned NewIntrinsic = 0;
4601 EVT ShAmtVT = MVT::v2i32;
4602 switch (Intrinsic) {
4603 case Intrinsic::x86_mmx_pslli_w:
4604 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4606 case Intrinsic::x86_mmx_pslli_d:
4607 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4609 case Intrinsic::x86_mmx_pslli_q:
4610 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4612 case Intrinsic::x86_mmx_psrli_w:
4613 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4615 case Intrinsic::x86_mmx_psrli_d:
4616 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4618 case Intrinsic::x86_mmx_psrli_q:
4619 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4621 case Intrinsic::x86_mmx_psrai_w:
4622 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4624 case Intrinsic::x86_mmx_psrai_d:
4625 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4627 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4630 // The vector shift intrinsics with scalars uses 32b shift amounts but
4631 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4633 // We must do this early because v2i32 is not a legal type.
4636 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
4637 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
4638 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4639 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4640 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4641 DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
4642 getValue(I.getArgOperand(0)), ShAmt);
4646 case Intrinsic::convertff:
4647 case Intrinsic::convertfsi:
4648 case Intrinsic::convertfui:
4649 case Intrinsic::convertsif:
4650 case Intrinsic::convertuif:
4651 case Intrinsic::convertss:
4652 case Intrinsic::convertsu:
4653 case Intrinsic::convertus:
4654 case Intrinsic::convertuu: {
4655 ISD::CvtCode Code = ISD::CVT_INVALID;
4656 switch (Intrinsic) {
4657 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4658 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4659 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4660 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4661 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4662 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4663 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4664 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4665 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4666 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4668 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4669 const Value *Op1 = I.getArgOperand(0);
4670 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
4671 DAG.getValueType(DestVT),
4672 DAG.getValueType(getValue(Op1).getValueType()),
4673 getValue(I.getArgOperand(1)),
4674 getValue(I.getArgOperand(2)),
4679 case Intrinsic::powi:
4680 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
4681 getValue(I.getArgOperand(1)), DAG));
4683 case Intrinsic::log:
4684 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4686 case Intrinsic::log2:
4687 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4689 case Intrinsic::log10:
4690 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4692 case Intrinsic::exp:
4693 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4695 case Intrinsic::exp2:
4696 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4698 case Intrinsic::pow:
4699 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
4700 getValue(I.getArgOperand(1)), DAG, TLI));
4702 case Intrinsic::sqrt:
4703 case Intrinsic::fabs:
4704 case Intrinsic::sin:
4705 case Intrinsic::cos:
4706 case Intrinsic::floor:
4707 case Intrinsic::ceil:
4708 case Intrinsic::trunc:
4709 case Intrinsic::rint:
4710 case Intrinsic::nearbyint:
4711 case Intrinsic::round: {
4713 switch (Intrinsic) {
4714 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4715 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
4716 case Intrinsic::fabs: Opcode = ISD::FABS; break;
4717 case Intrinsic::sin: Opcode = ISD::FSIN; break;
4718 case Intrinsic::cos: Opcode = ISD::FCOS; break;
4719 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
4720 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
4721 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
4722 case Intrinsic::rint: Opcode = ISD::FRINT; break;
4723 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
4724 case Intrinsic::round: Opcode = ISD::FROUND; break;
4727 setValue(&I, DAG.getNode(Opcode, sdl,
4728 getValue(I.getArgOperand(0)).getValueType(),
4729 getValue(I.getArgOperand(0))));
4732 case Intrinsic::minnum:
4733 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
4734 getValue(I.getArgOperand(0)).getValueType(),
4735 getValue(I.getArgOperand(0)),
4736 getValue(I.getArgOperand(1))));
4738 case Intrinsic::maxnum:
4739 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
4740 getValue(I.getArgOperand(0)).getValueType(),
4741 getValue(I.getArgOperand(0)),
4742 getValue(I.getArgOperand(1))));
4744 case Intrinsic::copysign:
4745 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
4746 getValue(I.getArgOperand(0)).getValueType(),
4747 getValue(I.getArgOperand(0)),
4748 getValue(I.getArgOperand(1))));
4750 case Intrinsic::fma:
4751 setValue(&I, DAG.getNode(ISD::FMA, sdl,
4752 getValue(I.getArgOperand(0)).getValueType(),
4753 getValue(I.getArgOperand(0)),
4754 getValue(I.getArgOperand(1)),
4755 getValue(I.getArgOperand(2))));
4757 case Intrinsic::fmuladd: {
4758 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4759 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
4760 TLI.isFMAFasterThanFMulAndFAdd(VT)) {
4761 setValue(&I, DAG.getNode(ISD::FMA, sdl,
4762 getValue(I.getArgOperand(0)).getValueType(),
4763 getValue(I.getArgOperand(0)),
4764 getValue(I.getArgOperand(1)),
4765 getValue(I.getArgOperand(2))));
4767 // TODO: Intrinsic calls should have fast-math-flags.
4768 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
4769 getValue(I.getArgOperand(0)).getValueType(),
4770 getValue(I.getArgOperand(0)),
4771 getValue(I.getArgOperand(1)));
4772 SDValue Add = DAG.getNode(ISD::FADD, sdl,
4773 getValue(I.getArgOperand(0)).getValueType(),
4775 getValue(I.getArgOperand(2)));
4780 case Intrinsic::convert_to_fp16:
4781 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
4782 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
4783 getValue(I.getArgOperand(0)),
4784 DAG.getTargetConstant(0, sdl,
4787 case Intrinsic::convert_from_fp16:
4788 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
4789 TLI.getValueType(DAG.getDataLayout(), I.getType()),
4790 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
4791 getValue(I.getArgOperand(0)))));
4793 case Intrinsic::pcmarker: {
4794 SDValue Tmp = getValue(I.getArgOperand(0));
4795 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
4798 case Intrinsic::readcyclecounter: {
4799 SDValue Op = getRoot();
4800 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
4801 DAG.getVTList(MVT::i64, MVT::Other), Op);
4803 DAG.setRoot(Res.getValue(1));
4806 case Intrinsic::bswap:
4807 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
4808 getValue(I.getArgOperand(0)).getValueType(),
4809 getValue(I.getArgOperand(0))));
4811 case Intrinsic::uabsdiff:
4812 setValue(&I, DAG.getNode(ISD::UABSDIFF, sdl,
4813 getValue(I.getArgOperand(0)).getValueType(),
4814 getValue(I.getArgOperand(0)),
4815 getValue(I.getArgOperand(1))));
4817 case Intrinsic::sabsdiff:
4818 setValue(&I, DAG.getNode(ISD::SABSDIFF, sdl,
4819 getValue(I.getArgOperand(0)).getValueType(),
4820 getValue(I.getArgOperand(0)),
4821 getValue(I.getArgOperand(1))));
4823 case Intrinsic::cttz: {
4824 SDValue Arg = getValue(I.getArgOperand(0));
4825 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
4826 EVT Ty = Arg.getValueType();
4827 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
4831 case Intrinsic::ctlz: {
4832 SDValue Arg = getValue(I.getArgOperand(0));
4833 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
4834 EVT Ty = Arg.getValueType();
4835 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
4839 case Intrinsic::ctpop: {
4840 SDValue Arg = getValue(I.getArgOperand(0));
4841 EVT Ty = Arg.getValueType();
4842 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
4845 case Intrinsic::stacksave: {
4846 SDValue Op = getRoot();
4848 ISD::STACKSAVE, sdl,
4849 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
4851 DAG.setRoot(Res.getValue(1));
4854 case Intrinsic::stackrestore: {
4855 Res = getValue(I.getArgOperand(0));
4856 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
4859 case Intrinsic::stackprotector: {
4860 // Emit code into the DAG to store the stack guard onto the stack.
4861 MachineFunction &MF = DAG.getMachineFunction();
4862 MachineFrameInfo *MFI = MF.getFrameInfo();
4863 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
4864 SDValue Src, Chain = getRoot();
4865 const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
4866 const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
4868 // See if Ptr is a bitcast. If it is, look through it and see if we can get
4869 // global variable __stack_chk_guard.
4871 if (const Operator *BC = dyn_cast<Operator>(Ptr))
4872 if (BC->getOpcode() == Instruction::BitCast)
4873 GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
4875 if (GV && TLI.useLoadStackGuardNode()) {
4876 // Emit a LOAD_STACK_GUARD node.
4877 MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
4879 MachinePointerInfo MPInfo(GV);
4880 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
4881 unsigned Flags = MachineMemOperand::MOLoad |
4882 MachineMemOperand::MOInvariant;
4883 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
4884 PtrTy.getSizeInBits() / 8,
4885 DAG.getEVTAlignment(PtrTy));
4886 Node->setMemRefs(MemRefs, MemRefs + 1);
4888 // Copy the guard value to a virtual register so that it can be
4889 // retrieved in the epilogue.
4890 Src = SDValue(Node, 0);
4891 const TargetRegisterClass *RC =
4892 TLI.getRegClassFor(Src.getSimpleValueType());
4893 unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
4895 SPDescriptor.setGuardReg(Reg);
4896 Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
4898 Src = getValue(I.getArgOperand(0)); // The guard's value.
4901 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4903 int FI = FuncInfo.StaticAllocaMap[Slot];
4904 MFI->setStackProtectorIndex(FI);
4906 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4908 // Store the stack protector onto the stack.
4909 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
4910 DAG.getMachineFunction(), FI),
4916 case Intrinsic::objectsize: {
4917 // If we don't know by now, we're never going to know.
4918 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
4920 assert(CI && "Non-constant type in __builtin_object_size?");
4922 SDValue Arg = getValue(I.getCalledValue());
4923 EVT Ty = Arg.getValueType();
4926 Res = DAG.getConstant(-1ULL, sdl, Ty);
4928 Res = DAG.getConstant(0, sdl, Ty);
4933 case Intrinsic::annotation:
4934 case Intrinsic::ptr_annotation:
4935 // Drop the intrinsic, but forward the value
4936 setValue(&I, getValue(I.getOperand(0)));
4938 case Intrinsic::assume:
4939 case Intrinsic::var_annotation:
4940 // Discard annotate attributes and assumptions
4943 case Intrinsic::init_trampoline: {
4944 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
4948 Ops[1] = getValue(I.getArgOperand(0));
4949 Ops[2] = getValue(I.getArgOperand(1));
4950 Ops[3] = getValue(I.getArgOperand(2));
4951 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
4952 Ops[5] = DAG.getSrcValue(F);
4954 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
4959 case Intrinsic::adjust_trampoline: {
4960 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
4961 TLI.getPointerTy(DAG.getDataLayout()),
4962 getValue(I.getArgOperand(0))));
4965 case Intrinsic::gcroot:
4967 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
4968 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
4970 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4971 GFI->addStackRoot(FI->getIndex(), TypeMap);
4974 case Intrinsic::gcread:
4975 case Intrinsic::gcwrite:
4976 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4977 case Intrinsic::flt_rounds:
4978 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
4981 case Intrinsic::expect: {
4982 // Just replace __builtin_expect(exp, c) with EXP.
4983 setValue(&I, getValue(I.getArgOperand(0)));
4987 case Intrinsic::debugtrap:
4988 case Intrinsic::trap: {
4989 StringRef TrapFuncName =
4991 .getAttribute(AttributeSet::FunctionIndex, "trap-func-name")
4992 .getValueAsString();
4993 if (TrapFuncName.empty()) {
4994 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
4995 ISD::TRAP : ISD::DEBUGTRAP;
4996 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
4999 TargetLowering::ArgListTy Args;
5001 TargetLowering::CallLoweringInfo CLI(DAG);
5002 CLI.setDebugLoc(sdl).setChain(getRoot()).setCallee(
5003 CallingConv::C, I.getType(),
5004 DAG.getExternalSymbol(TrapFuncName.data(),
5005 TLI.getPointerTy(DAG.getDataLayout())),
5006 std::move(Args), 0);
5008 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5009 DAG.setRoot(Result.second);
5013 case Intrinsic::uadd_with_overflow:
5014 case Intrinsic::sadd_with_overflow:
5015 case Intrinsic::usub_with_overflow:
5016 case Intrinsic::ssub_with_overflow:
5017 case Intrinsic::umul_with_overflow:
5018 case Intrinsic::smul_with_overflow: {
5020 switch (Intrinsic) {
5021 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5022 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5023 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5024 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5025 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5026 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5027 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5029 SDValue Op1 = getValue(I.getArgOperand(0));
5030 SDValue Op2 = getValue(I.getArgOperand(1));
5032 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5033 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
5036 case Intrinsic::prefetch: {
5038 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
5040 Ops[1] = getValue(I.getArgOperand(0));
5041 Ops[2] = getValue(I.getArgOperand(1));
5042 Ops[3] = getValue(I.getArgOperand(2));
5043 Ops[4] = getValue(I.getArgOperand(3));
5044 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
5045 DAG.getVTList(MVT::Other), Ops,
5046 EVT::getIntegerVT(*Context, 8),
5047 MachinePointerInfo(I.getArgOperand(0)),
5049 false, /* volatile */
5051 rw==1)); /* write */
5054 case Intrinsic::lifetime_start:
5055 case Intrinsic::lifetime_end: {
5056 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
5057 // Stack coloring is not enabled in O0, discard region information.
5058 if (TM.getOptLevel() == CodeGenOpt::None)
5061 SmallVector<Value *, 4> Allocas;
5062 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
5064 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
5065 E = Allocas.end(); Object != E; ++Object) {
5066 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5068 // Could not find an Alloca.
5069 if (!LifetimeObject)
5072 // First check that the Alloca is static, otherwise it won't have a
5073 // valid frame index.
5074 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
5075 if (SI == FuncInfo.StaticAllocaMap.end())
5078 int FI = SI->second;
5083 DAG.getFrameIndex(FI, TLI.getPointerTy(DAG.getDataLayout()), true);
5084 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5086 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
5091 case Intrinsic::invariant_start:
5092 // Discard region information.
5093 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5095 case Intrinsic::invariant_end:
5096 // Discard region information.
5098 case Intrinsic::stackprotectorcheck: {
5099 // Do not actually emit anything for this basic block. Instead we initialize
5100 // the stack protector descriptor and export the guard variable so we can
5101 // access it in FinishBasicBlock.
5102 const BasicBlock *BB = I.getParent();
5103 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
5104 ExportFromCurrentBlock(SPDescriptor.getGuard());
5106 // Flush our exports since we are going to process a terminator.
5107 (void)getControlRoot();
5110 case Intrinsic::clear_cache:
5111 return TLI.getClearCacheBuiltinName();
5112 case Intrinsic::eh_actions:
5113 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
5115 case Intrinsic::donothing:
5118 case Intrinsic::experimental_stackmap: {
5122 case Intrinsic::experimental_patchpoint_void:
5123 case Intrinsic::experimental_patchpoint_i64: {
5124 visitPatchpoint(&I);
5127 case Intrinsic::experimental_gc_statepoint: {
5131 case Intrinsic::experimental_gc_result_int:
5132 case Intrinsic::experimental_gc_result_float:
5133 case Intrinsic::experimental_gc_result_ptr:
5134 case Intrinsic::experimental_gc_result: {
5138 case Intrinsic::experimental_gc_relocate: {
5142 case Intrinsic::instrprof_increment:
5143 llvm_unreachable("instrprof failed to lower an increment");
5145 case Intrinsic::localescape: {
5146 MachineFunction &MF = DAG.getMachineFunction();
5147 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5149 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
5150 // is the same on all targets.
5151 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
5152 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
5153 if (isa<ConstantPointerNull>(Arg))
5154 continue; // Skip null pointers. They represent a hole in index space.
5155 AllocaInst *Slot = cast<AllocaInst>(Arg);
5156 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
5157 "can only escape static allocas");
5158 int FI = FuncInfo.StaticAllocaMap[Slot];
5159 MCSymbol *FrameAllocSym =
5160 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5161 GlobalValue::getRealLinkageName(MF.getName()), Idx);
5162 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
5163 TII->get(TargetOpcode::LOCAL_ESCAPE))
5164 .addSym(FrameAllocSym)
5171 case Intrinsic::localrecover: {
5172 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
5173 MachineFunction &MF = DAG.getMachineFunction();
5174 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
5176 // Get the symbol that defines the frame offset.
5177 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
5178 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
5179 unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
5180 MCSymbol *FrameAllocSym =
5181 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
5182 GlobalValue::getRealLinkageName(Fn->getName()), IdxVal);
5184 // Create a MCSymbol for the label to avoid any target lowering
5185 // that would make this PC relative.
5186 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
5188 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
5190 // Add the offset to the FP.
5191 Value *FP = I.getArgOperand(1);
5192 SDValue FPVal = getValue(FP);
5193 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
5198 case Intrinsic::eh_begincatch:
5199 case Intrinsic::eh_endcatch:
5200 llvm_unreachable("begin/end catch intrinsics not lowered in codegen");
5201 case Intrinsic::eh_exceptioncode: {
5202 unsigned Reg = TLI.getExceptionPointerRegister();
5203 assert(Reg && "cannot get exception code on this platform");
5204 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
5205 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
5206 assert(FuncInfo.MBB->isEHPad() && "eh.exceptioncode in non-lpad");
5207 unsigned VReg = FuncInfo.MBB->addLiveIn(Reg, PtrRC);
5209 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
5210 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
5217 std::pair<SDValue, SDValue>
5218 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5219 const BasicBlock *EHPadBB) {
5220 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5221 MCSymbol *BeginLabel = nullptr;
5224 // Insert a label before the invoke call to mark the try range. This can be
5225 // used to detect deletion of the invoke via the MachineModuleInfo.
5226 BeginLabel = MMI.getContext().createTempSymbol();
5228 // For SjLj, keep track of which landing pads go with which invokes
5229 // so as to maintain the ordering of pads in the LSDA.
5230 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5231 if (CallSiteIndex) {
5232 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5233 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
5235 // Now that the call site is handled, stop tracking it.
5236 MMI.setCurrentCallSite(0);
5239 // Both PendingLoads and PendingExports must be flushed here;
5240 // this call might not return.
5242 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5244 CLI.setChain(getRoot());
5246 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5247 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5249 assert((CLI.IsTailCall || Result.second.getNode()) &&
5250 "Non-null chain expected with non-tail call!");
5251 assert((Result.second.getNode() || !Result.first.getNode()) &&
5252 "Null value expected with tail call!");
5254 if (!Result.second.getNode()) {
5255 // As a special case, a null chain means that a tail call has been emitted
5256 // and the DAG root is already updated.
5259 // Since there's no actual continuation from this block, nothing can be
5260 // relying on us setting vregs for them.
5261 PendingExports.clear();
5263 DAG.setRoot(Result.second);
5267 // Insert a label at the end of the invoke call to mark the try range. This
5268 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5269 MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
5270 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5272 // Inform MachineModuleInfo of range.
5273 if (MMI.hasEHFunclets()) {
5274 WinEHFuncInfo &EHInfo =
5275 MMI.getWinEHFuncInfo(DAG.getMachineFunction().getFunction());
5276 EHInfo.addIPToStateRange(EHPadBB, BeginLabel, EndLabel);
5278 MMI.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
5285 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5287 const BasicBlock *EHPadBB) {
5288 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5289 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5290 Type *RetTy = FTy->getReturnType();
5292 TargetLowering::ArgListTy Args;
5293 TargetLowering::ArgListEntry Entry;
5294 Args.reserve(CS.arg_size());
5296 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5298 const Value *V = *i;
5301 if (V->getType()->isEmptyTy())
5304 SDValue ArgNode = getValue(V);
5305 Entry.Node = ArgNode; Entry.Ty = V->getType();
5307 // Skip the first return-type Attribute to get to params.
5308 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5309 Args.push_back(Entry);
5311 // If we have an explicit sret argument that is an Instruction, (i.e., it
5312 // might point to function-local memory), we can't meaningfully tail-call.
5313 if (Entry.isSRet && isa<Instruction>(V))
5317 // Check if target-independent constraints permit a tail call here.
5318 // Target-dependent constraints are checked within TLI->LowerCallTo.
5319 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5322 TargetLowering::CallLoweringInfo CLI(DAG);
5323 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
5324 .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5325 .setTailCall(isTailCall);
5326 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
5328 if (Result.first.getNode())
5329 setValue(CS.getInstruction(), Result.first);
5332 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5333 /// value is equal or not-equal to zero.
5334 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5335 for (const User *U : V->users()) {
5336 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5337 if (IC->isEquality())
5338 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5339 if (C->isNullValue())
5341 // Unknown instruction.
5347 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5349 SelectionDAGBuilder &Builder) {
5351 // Check to see if this load can be trivially constant folded, e.g. if the
5352 // input is from a string literal.
5353 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5354 // Cast pointer to the type we really want to load.
5355 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5356 PointerType::getUnqual(LoadTy));
5358 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
5359 const_cast<Constant *>(LoadInput), *Builder.DL))
5360 return Builder.getValue(LoadCst);
5363 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5364 // still constant memory, the input chain can be the entry node.
5366 bool ConstantMemory = false;
5368 // Do not serialize (non-volatile) loads of constant memory with anything.
5369 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5370 Root = Builder.DAG.getEntryNode();
5371 ConstantMemory = true;
5373 // Do not serialize non-volatile loads against each other.
5374 Root = Builder.DAG.getRoot();
5377 SDValue Ptr = Builder.getValue(PtrVal);
5378 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5379 Ptr, MachinePointerInfo(PtrVal),
5381 false /*nontemporal*/,
5382 false /*isinvariant*/, 1 /* align=1 */);
5384 if (!ConstantMemory)
5385 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5389 /// processIntegerCallValue - Record the value for an instruction that
5390 /// produces an integer result, converting the type where necessary.
5391 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5394 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5397 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5399 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5400 setValue(&I, Value);
5403 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5404 /// If so, return true and lower it, otherwise return false and it will be
5405 /// lowered like a normal call.
5406 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5407 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5408 if (I.getNumArgOperands() != 3)
5411 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5412 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5413 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5414 !I.getType()->isIntegerTy())
5417 const Value *Size = I.getArgOperand(2);
5418 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5419 if (CSize && CSize->getZExtValue() == 0) {
5420 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
5422 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
5426 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5427 std::pair<SDValue, SDValue> Res =
5428 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5429 getValue(LHS), getValue(RHS), getValue(Size),
5430 MachinePointerInfo(LHS),
5431 MachinePointerInfo(RHS));
5432 if (Res.first.getNode()) {
5433 processIntegerCallValue(I, Res.first, true);
5434 PendingLoads.push_back(Res.second);
5438 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5439 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5440 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5441 bool ActuallyDoIt = true;
5444 switch (CSize->getZExtValue()) {
5446 LoadVT = MVT::Other;
5448 ActuallyDoIt = false;
5452 LoadTy = Type::getInt16Ty(CSize->getContext());
5456 LoadTy = Type::getInt32Ty(CSize->getContext());
5460 LoadTy = Type::getInt64Ty(CSize->getContext());
5464 LoadVT = MVT::v4i32;
5465 LoadTy = Type::getInt32Ty(CSize->getContext());
5466 LoadTy = VectorType::get(LoadTy, 4);
5471 // This turns into unaligned loads. We only do this if the target natively
5472 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5473 // we'll only produce a small number of byte loads.
5475 // Require that we can find a legal MVT, and only do this if the target
5476 // supports unaligned loads of that type. Expanding into byte loads would
5478 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5479 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5480 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5481 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5482 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5483 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5484 // TODO: Check alignment of src and dest ptrs.
5485 if (!TLI.isTypeLegal(LoadVT) ||
5486 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5487 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
5488 ActuallyDoIt = false;
5492 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5493 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5495 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5497 processIntegerCallValue(I, Res, false);
5506 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5507 /// form. If so, return true and lower it, otherwise return false and it
5508 /// will be lowered like a normal call.
5509 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5510 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5511 if (I.getNumArgOperands() != 3)
5514 const Value *Src = I.getArgOperand(0);
5515 const Value *Char = I.getArgOperand(1);
5516 const Value *Length = I.getArgOperand(2);
5517 if (!Src->getType()->isPointerTy() ||
5518 !Char->getType()->isIntegerTy() ||
5519 !Length->getType()->isIntegerTy() ||
5520 !I.getType()->isPointerTy())
5523 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5524 std::pair<SDValue, SDValue> Res =
5525 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5526 getValue(Src), getValue(Char), getValue(Length),
5527 MachinePointerInfo(Src));
5528 if (Res.first.getNode()) {
5529 setValue(&I, Res.first);
5530 PendingLoads.push_back(Res.second);
5537 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5538 /// optimized form. If so, return true and lower it, otherwise return false
5539 /// and it will be lowered like a normal call.
5540 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5541 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5542 if (I.getNumArgOperands() != 2)
5545 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5546 if (!Arg0->getType()->isPointerTy() ||
5547 !Arg1->getType()->isPointerTy() ||
5548 !I.getType()->isPointerTy())
5551 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5552 std::pair<SDValue, SDValue> Res =
5553 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5554 getValue(Arg0), getValue(Arg1),
5555 MachinePointerInfo(Arg0),
5556 MachinePointerInfo(Arg1), isStpcpy);
5557 if (Res.first.getNode()) {
5558 setValue(&I, Res.first);
5559 DAG.setRoot(Res.second);
5566 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5567 /// If so, return true and lower it, otherwise return false and it will be
5568 /// lowered like a normal call.
5569 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5570 // Verify that the prototype makes sense. int strcmp(void*,void*)
5571 if (I.getNumArgOperands() != 2)
5574 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5575 if (!Arg0->getType()->isPointerTy() ||
5576 !Arg1->getType()->isPointerTy() ||
5577 !I.getType()->isIntegerTy())
5580 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5581 std::pair<SDValue, SDValue> Res =
5582 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5583 getValue(Arg0), getValue(Arg1),
5584 MachinePointerInfo(Arg0),
5585 MachinePointerInfo(Arg1));
5586 if (Res.first.getNode()) {
5587 processIntegerCallValue(I, Res.first, true);
5588 PendingLoads.push_back(Res.second);
5595 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5596 /// form. If so, return true and lower it, otherwise return false and it
5597 /// will be lowered like a normal call.
5598 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5599 // Verify that the prototype makes sense. size_t strlen(char *)
5600 if (I.getNumArgOperands() != 1)
5603 const Value *Arg0 = I.getArgOperand(0);
5604 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5607 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5608 std::pair<SDValue, SDValue> Res =
5609 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5610 getValue(Arg0), MachinePointerInfo(Arg0));
5611 if (Res.first.getNode()) {
5612 processIntegerCallValue(I, Res.first, false);
5613 PendingLoads.push_back(Res.second);
5620 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5621 /// form. If so, return true and lower it, otherwise return false and it
5622 /// will be lowered like a normal call.
5623 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5624 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5625 if (I.getNumArgOperands() != 2)
5628 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5629 if (!Arg0->getType()->isPointerTy() ||
5630 !Arg1->getType()->isIntegerTy() ||
5631 !I.getType()->isIntegerTy())
5634 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5635 std::pair<SDValue, SDValue> Res =
5636 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5637 getValue(Arg0), getValue(Arg1),
5638 MachinePointerInfo(Arg0));
5639 if (Res.first.getNode()) {
5640 processIntegerCallValue(I, Res.first, false);
5641 PendingLoads.push_back(Res.second);
5648 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5649 /// operation (as expected), translate it to an SDNode with the specified opcode
5650 /// and return true.
5651 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5653 // Sanity check that it really is a unary floating-point call.
5654 if (I.getNumArgOperands() != 1 ||
5655 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5656 I.getType() != I.getArgOperand(0)->getType() ||
5657 !I.onlyReadsMemory())
5660 SDValue Tmp = getValue(I.getArgOperand(0));
5661 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5665 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
5666 /// operation (as expected), translate it to an SDNode with the specified opcode
5667 /// and return true.
5668 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
5670 // Sanity check that it really is a binary floating-point call.
5671 if (I.getNumArgOperands() != 2 ||
5672 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5673 I.getType() != I.getArgOperand(0)->getType() ||
5674 I.getType() != I.getArgOperand(1)->getType() ||
5675 !I.onlyReadsMemory())
5678 SDValue Tmp0 = getValue(I.getArgOperand(0));
5679 SDValue Tmp1 = getValue(I.getArgOperand(1));
5680 EVT VT = Tmp0.getValueType();
5681 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
5685 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5686 // Handle inline assembly differently.
5687 if (isa<InlineAsm>(I.getCalledValue())) {
5692 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5693 ComputeUsesVAFloatArgument(I, &MMI);
5695 const char *RenameFn = nullptr;
5696 if (Function *F = I.getCalledFunction()) {
5697 if (F->isDeclaration()) {
5698 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5699 if (unsigned IID = II->getIntrinsicID(F)) {
5700 RenameFn = visitIntrinsicCall(I, IID);
5705 if (Intrinsic::ID IID = F->getIntrinsicID()) {
5706 RenameFn = visitIntrinsicCall(I, IID);
5712 // Check for well-known libc/libm calls. If the function is internal, it
5713 // can't be a library call.
5715 if (!F->hasLocalLinkage() && F->hasName() &&
5716 LibInfo->getLibFunc(F->getName(), Func) &&
5717 LibInfo->hasOptimizedCodeGen(Func)) {
5720 case LibFunc::copysign:
5721 case LibFunc::copysignf:
5722 case LibFunc::copysignl:
5723 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5724 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5725 I.getType() == I.getArgOperand(0)->getType() &&
5726 I.getType() == I.getArgOperand(1)->getType() &&
5727 I.onlyReadsMemory()) {
5728 SDValue LHS = getValue(I.getArgOperand(0));
5729 SDValue RHS = getValue(I.getArgOperand(1));
5730 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5731 LHS.getValueType(), LHS, RHS));
5736 case LibFunc::fabsf:
5737 case LibFunc::fabsl:
5738 if (visitUnaryFloatCall(I, ISD::FABS))
5742 case LibFunc::fminf:
5743 case LibFunc::fminl:
5744 if (visitBinaryFloatCall(I, ISD::FMINNUM))
5748 case LibFunc::fmaxf:
5749 case LibFunc::fmaxl:
5750 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
5756 if (visitUnaryFloatCall(I, ISD::FSIN))
5762 if (visitUnaryFloatCall(I, ISD::FCOS))
5766 case LibFunc::sqrtf:
5767 case LibFunc::sqrtl:
5768 case LibFunc::sqrt_finite:
5769 case LibFunc::sqrtf_finite:
5770 case LibFunc::sqrtl_finite:
5771 if (visitUnaryFloatCall(I, ISD::FSQRT))
5774 case LibFunc::floor:
5775 case LibFunc::floorf:
5776 case LibFunc::floorl:
5777 if (visitUnaryFloatCall(I, ISD::FFLOOR))
5780 case LibFunc::nearbyint:
5781 case LibFunc::nearbyintf:
5782 case LibFunc::nearbyintl:
5783 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
5787 case LibFunc::ceilf:
5788 case LibFunc::ceill:
5789 if (visitUnaryFloatCall(I, ISD::FCEIL))
5793 case LibFunc::rintf:
5794 case LibFunc::rintl:
5795 if (visitUnaryFloatCall(I, ISD::FRINT))
5798 case LibFunc::round:
5799 case LibFunc::roundf:
5800 case LibFunc::roundl:
5801 if (visitUnaryFloatCall(I, ISD::FROUND))
5804 case LibFunc::trunc:
5805 case LibFunc::truncf:
5806 case LibFunc::truncl:
5807 if (visitUnaryFloatCall(I, ISD::FTRUNC))
5811 case LibFunc::log2f:
5812 case LibFunc::log2l:
5813 if (visitUnaryFloatCall(I, ISD::FLOG2))
5817 case LibFunc::exp2f:
5818 case LibFunc::exp2l:
5819 if (visitUnaryFloatCall(I, ISD::FEXP2))
5822 case LibFunc::memcmp:
5823 if (visitMemCmpCall(I))
5826 case LibFunc::memchr:
5827 if (visitMemChrCall(I))
5830 case LibFunc::strcpy:
5831 if (visitStrCpyCall(I, false))
5834 case LibFunc::stpcpy:
5835 if (visitStrCpyCall(I, true))
5838 case LibFunc::strcmp:
5839 if (visitStrCmpCall(I))
5842 case LibFunc::strlen:
5843 if (visitStrLenCall(I))
5846 case LibFunc::strnlen:
5847 if (visitStrNLenCall(I))
5856 Callee = getValue(I.getCalledValue());
5858 Callee = DAG.getExternalSymbol(
5860 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5862 // Check if we can potentially perform a tail call. More detailed checking is
5863 // be done within LowerCallTo, after more information about the call is known.
5864 LowerCallTo(&I, Callee, I.isTailCall());
5869 /// AsmOperandInfo - This contains information for each constraint that we are
5871 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
5873 /// CallOperand - If this is the result output operand or a clobber
5874 /// this is null, otherwise it is the incoming operand to the CallInst.
5875 /// This gets modified as the asm is processed.
5876 SDValue CallOperand;
5878 /// AssignedRegs - If this is a register or register class operand, this
5879 /// contains the set of register corresponding to the operand.
5880 RegsForValue AssignedRegs;
5882 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
5883 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
5886 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5887 /// corresponds to. If there is no Value* for this operand, it returns
5889 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
5890 const DataLayout &DL) const {
5891 if (!CallOperandVal) return MVT::Other;
5893 if (isa<BasicBlock>(CallOperandVal))
5894 return TLI.getPointerTy(DL);
5896 llvm::Type *OpTy = CallOperandVal->getType();
5898 // FIXME: code duplicated from TargetLowering::ParseConstraints().
5899 // If this is an indirect operand, the operand is a pointer to the
5902 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5904 report_fatal_error("Indirect operand for inline asm not a pointer!");
5905 OpTy = PtrTy->getElementType();
5908 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5909 if (StructType *STy = dyn_cast<StructType>(OpTy))
5910 if (STy->getNumElements() == 1)
5911 OpTy = STy->getElementType(0);
5913 // If OpTy is not a single value, it may be a struct/union that we
5914 // can tile with integers.
5915 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5916 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
5925 OpTy = IntegerType::get(Context, BitSize);
5930 return TLI.getValueType(DL, OpTy, true);
5934 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5936 } // end anonymous namespace
5938 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5939 /// specified operand. We prefer to assign virtual registers, to allow the
5940 /// register allocator to handle the assignment process. However, if the asm
5941 /// uses features that we can't model on machineinstrs, we have SDISel do the
5942 /// allocation. This produces generally horrible, but correct, code.
5944 /// OpInfo describes the operand.
5946 static void GetRegistersForValue(SelectionDAG &DAG,
5947 const TargetLowering &TLI,
5949 SDISelAsmOperandInfo &OpInfo) {
5950 LLVMContext &Context = *DAG.getContext();
5952 MachineFunction &MF = DAG.getMachineFunction();
5953 SmallVector<unsigned, 4> Regs;
5955 // If this is a constraint for a single physreg, or a constraint for a
5956 // register class, find it.
5957 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
5958 TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
5959 OpInfo.ConstraintCode,
5960 OpInfo.ConstraintVT);
5962 unsigned NumRegs = 1;
5963 if (OpInfo.ConstraintVT != MVT::Other) {
5964 // If this is a FP input in an integer register (or visa versa) insert a bit
5965 // cast of the input value. More generally, handle any case where the input
5966 // value disagrees with the register class we plan to stick this in.
5967 if (OpInfo.Type == InlineAsm::isInput &&
5968 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5969 // Try to convert to the first EVT that the reg class contains. If the
5970 // types are identical size, use a bitcast to convert (e.g. two differing
5972 MVT RegVT = *PhysReg.second->vt_begin();
5973 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
5974 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5975 RegVT, OpInfo.CallOperand);
5976 OpInfo.ConstraintVT = RegVT;
5977 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5978 // If the input is a FP value and we want it in FP registers, do a
5979 // bitcast to the corresponding integer type. This turns an f64 value
5980 // into i64, which can be passed with two i32 values on a 32-bit
5982 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
5983 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5984 RegVT, OpInfo.CallOperand);
5985 OpInfo.ConstraintVT = RegVT;
5989 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5993 EVT ValueVT = OpInfo.ConstraintVT;
5995 // If this is a constraint for a specific physical register, like {r17},
5997 if (unsigned AssignedReg = PhysReg.first) {
5998 const TargetRegisterClass *RC = PhysReg.second;
5999 if (OpInfo.ConstraintVT == MVT::Other)
6000 ValueVT = *RC->vt_begin();
6002 // Get the actual register value type. This is important, because the user
6003 // may have asked for (e.g.) the AX register in i32 type. We need to
6004 // remember that AX is actually i16 to get the right extension.
6005 RegVT = *RC->vt_begin();
6007 // This is a explicit reference to a physical register.
6008 Regs.push_back(AssignedReg);
6010 // If this is an expanded reference, add the rest of the regs to Regs.
6012 TargetRegisterClass::iterator I = RC->begin();
6013 for (; *I != AssignedReg; ++I)
6014 assert(I != RC->end() && "Didn't find reg!");
6016 // Already added the first reg.
6018 for (; NumRegs; --NumRegs, ++I) {
6019 assert(I != RC->end() && "Ran out of registers to allocate!");
6024 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6028 // Otherwise, if this was a reference to an LLVM register class, create vregs
6029 // for this reference.
6030 if (const TargetRegisterClass *RC = PhysReg.second) {
6031 RegVT = *RC->vt_begin();
6032 if (OpInfo.ConstraintVT == MVT::Other)
6035 // Create the appropriate number of virtual registers.
6036 MachineRegisterInfo &RegInfo = MF.getRegInfo();
6037 for (; NumRegs; --NumRegs)
6038 Regs.push_back(RegInfo.createVirtualRegister(RC));
6040 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
6044 // Otherwise, we couldn't allocate enough registers for this.
6047 /// visitInlineAsm - Handle a call to an InlineAsm object.
6049 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
6050 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
6052 /// ConstraintOperands - Information about all of the constraints.
6053 SDISelAsmOperandInfoVector ConstraintOperands;
6055 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6056 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
6057 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
6059 bool hasMemory = false;
6061 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
6062 unsigned ResNo = 0; // ResNo - The result number of the next output.
6063 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6064 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
6065 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
6067 MVT OpVT = MVT::Other;
6069 // Compute the value type for each operand.
6070 switch (OpInfo.Type) {
6071 case InlineAsm::isOutput:
6072 // Indirect outputs just consume an argument.
6073 if (OpInfo.isIndirect) {
6074 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6078 // The return value of the call is this value. As such, there is no
6079 // corresponding argument.
6080 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6081 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
6082 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(),
6083 STy->getElementType(ResNo));
6085 assert(ResNo == 0 && "Asm only has one result!");
6086 OpVT = TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
6090 case InlineAsm::isInput:
6091 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
6093 case InlineAsm::isClobber:
6098 // If this is an input or an indirect output, process the call argument.
6099 // BasicBlocks are labels, currently appearing only in asm's.
6100 if (OpInfo.CallOperandVal) {
6101 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
6102 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
6104 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
6107 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
6108 DAG.getDataLayout()).getSimpleVT();
6111 OpInfo.ConstraintVT = OpVT;
6113 // Indirect operand accesses access memory.
6114 if (OpInfo.isIndirect)
6117 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
6118 TargetLowering::ConstraintType
6119 CType = TLI.getConstraintType(OpInfo.Codes[j]);
6120 if (CType == TargetLowering::C_Memory) {
6128 SDValue Chain, Flag;
6130 // We won't need to flush pending loads if this asm doesn't touch
6131 // memory and is nonvolatile.
6132 if (hasMemory || IA->hasSideEffects())
6135 Chain = DAG.getRoot();
6137 // Second pass over the constraints: compute which constraint option to use
6138 // and assign registers to constraints that want a specific physreg.
6139 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6140 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6142 // If this is an output operand with a matching input operand, look up the
6143 // matching input. If their types mismatch, e.g. one is an integer, the
6144 // other is floating point, or their sizes are different, flag it as an
6146 if (OpInfo.hasMatchingInput()) {
6147 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
6149 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
6150 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
6151 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
6152 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
6153 OpInfo.ConstraintVT);
6154 std::pair<unsigned, const TargetRegisterClass *> InputRC =
6155 TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
6156 Input.ConstraintVT);
6157 if ((OpInfo.ConstraintVT.isInteger() !=
6158 Input.ConstraintVT.isInteger()) ||
6159 (MatchRC.second != InputRC.second)) {
6160 report_fatal_error("Unsupported asm: input constraint"
6161 " with a matching output constraint of"
6162 " incompatible type!");
6164 Input.ConstraintVT = OpInfo.ConstraintVT;
6168 // Compute the constraint code and ConstraintType to use.
6169 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
6171 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6172 OpInfo.Type == InlineAsm::isClobber)
6175 // If this is a memory input, and if the operand is not indirect, do what we
6176 // need to to provide an address for the memory input.
6177 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6178 !OpInfo.isIndirect) {
6179 assert((OpInfo.isMultipleAlternative ||
6180 (OpInfo.Type == InlineAsm::isInput)) &&
6181 "Can only indirectify direct input operands!");
6183 // Memory operands really want the address of the value. If we don't have
6184 // an indirect input, put it in the constpool if we can, otherwise spill
6185 // it to a stack slot.
6186 // TODO: This isn't quite right. We need to handle these according to
6187 // the addressing mode that the constraint wants. Also, this may take
6188 // an additional register for the computation and we don't want that
6191 // If the operand is a float, integer, or vector constant, spill to a
6192 // constant pool entry to get its address.
6193 const Value *OpVal = OpInfo.CallOperandVal;
6194 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
6195 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
6196 OpInfo.CallOperand = DAG.getConstantPool(
6197 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
6199 // Otherwise, create a stack slot and emit a store to it before the
6201 Type *Ty = OpVal->getType();
6202 auto &DL = DAG.getDataLayout();
6203 uint64_t TySize = DL.getTypeAllocSize(Ty);
6204 unsigned Align = DL.getPrefTypeAlignment(Ty);
6205 MachineFunction &MF = DAG.getMachineFunction();
6206 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6208 DAG.getFrameIndex(SSFI, TLI.getPointerTy(DAG.getDataLayout()));
6209 Chain = DAG.getStore(
6210 Chain, getCurSDLoc(), OpInfo.CallOperand, StackSlot,
6211 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
6213 OpInfo.CallOperand = StackSlot;
6216 // There is no longer a Value* corresponding to this operand.
6217 OpInfo.CallOperandVal = nullptr;
6219 // It is now an indirect operand.
6220 OpInfo.isIndirect = true;
6223 // If this constraint is for a specific register, allocate it before
6225 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6226 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6229 // Second pass - Loop over all of the operands, assigning virtual or physregs
6230 // to register class operands.
6231 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6232 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6234 // C_Register operands have already been allocated, Other/Memory don't need
6236 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6237 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6240 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6241 std::vector<SDValue> AsmNodeOperands;
6242 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6243 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
6244 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
6246 // If we have a !srcloc metadata node associated with it, we want to attach
6247 // this to the ultimately generated inline asm machineinstr. To do this, we
6248 // pass in the third operand as this (potentially null) inline asm MDNode.
6249 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6250 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6252 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6253 // bits as operand 3.
6254 unsigned ExtraInfo = 0;
6255 if (IA->hasSideEffects())
6256 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6257 if (IA->isAlignStack())
6258 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6259 // Set the asm dialect.
6260 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6262 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6263 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6264 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6266 // Compute the constraint code and ConstraintType to use.
6267 TLI.ComputeConstraintToUse(OpInfo, SDValue());
6269 // Ideally, we would only check against memory constraints. However, the
6270 // meaning of an other constraint can be target-specific and we can't easily
6271 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6272 // for other constriants as well.
6273 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6274 OpInfo.ConstraintType == TargetLowering::C_Other) {
6275 if (OpInfo.Type == InlineAsm::isInput)
6276 ExtraInfo |= InlineAsm::Extra_MayLoad;
6277 else if (OpInfo.Type == InlineAsm::isOutput)
6278 ExtraInfo |= InlineAsm::Extra_MayStore;
6279 else if (OpInfo.Type == InlineAsm::isClobber)
6280 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6284 AsmNodeOperands.push_back(DAG.getTargetConstant(
6285 ExtraInfo, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6287 // Loop over all of the inputs, copying the operand values into the
6288 // appropriate registers and processing the output regs.
6289 RegsForValue RetValRegs;
6291 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6292 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6294 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6295 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6297 switch (OpInfo.Type) {
6298 case InlineAsm::isOutput: {
6299 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6300 OpInfo.ConstraintType != TargetLowering::C_Register) {
6301 // Memory output, or 'other' output (e.g. 'X' constraint).
6302 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6304 unsigned ConstraintID =
6305 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6306 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6307 "Failed to convert memory constraint code to constraint id.");
6309 // Add information to the INLINEASM node to know about this output.
6310 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6311 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
6312 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
6314 AsmNodeOperands.push_back(OpInfo.CallOperand);
6318 // Otherwise, this is a register or register class output.
6320 // Copy the output from the appropriate register. Find a register that
6322 if (OpInfo.AssignedRegs.Regs.empty()) {
6323 LLVMContext &Ctx = *DAG.getContext();
6324 Ctx.emitError(CS.getInstruction(),
6325 "couldn't allocate output register for constraint '" +
6326 Twine(OpInfo.ConstraintCode) + "'");
6330 // If this is an indirect operand, store through the pointer after the
6332 if (OpInfo.isIndirect) {
6333 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6334 OpInfo.CallOperandVal));
6336 // This is the result value of the call.
6337 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6338 // Concatenate this output onto the outputs list.
6339 RetValRegs.append(OpInfo.AssignedRegs);
6342 // Add information to the INLINEASM node to know that this register is
6345 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6346 ? InlineAsm::Kind_RegDefEarlyClobber
6347 : InlineAsm::Kind_RegDef,
6348 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
6351 case InlineAsm::isInput: {
6352 SDValue InOperandVal = OpInfo.CallOperand;
6354 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6355 // If this is required to match an output register we have already set,
6356 // just use its register.
6357 unsigned OperandNo = OpInfo.getMatchedOperand();
6359 // Scan until we find the definition we already emitted of this operand.
6360 // When we find it, create a RegsForValue operand.
6361 unsigned CurOp = InlineAsm::Op_FirstOperand;
6362 for (; OperandNo; --OperandNo) {
6363 // Advance to the next operand.
6365 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6366 assert((InlineAsm::isRegDefKind(OpFlag) ||
6367 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6368 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6369 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6373 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6374 if (InlineAsm::isRegDefKind(OpFlag) ||
6375 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6376 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6377 if (OpInfo.isIndirect) {
6378 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6379 LLVMContext &Ctx = *DAG.getContext();
6380 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6381 " don't know how to handle tied "
6382 "indirect register inputs");
6386 RegsForValue MatchedRegs;
6387 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6388 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6389 MatchedRegs.RegVTs.push_back(RegVT);
6390 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6391 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6393 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6394 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6396 LLVMContext &Ctx = *DAG.getContext();
6397 Ctx.emitError(CS.getInstruction(),
6398 "inline asm error: This value"
6399 " type register class is not natively supported!");
6403 SDLoc dl = getCurSDLoc();
6404 // Use the produced MatchedRegs object to
6405 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6406 Chain, &Flag, CS.getInstruction());
6407 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6408 true, OpInfo.getMatchedOperand(), dl,
6409 DAG, AsmNodeOperands);
6413 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6414 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6415 "Unexpected number of operands");
6416 // Add information to the INLINEASM node to know about this input.
6417 // See InlineAsm.h isUseOperandTiedToDef.
6418 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
6419 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6420 OpInfo.getMatchedOperand());
6421 AsmNodeOperands.push_back(DAG.getTargetConstant(
6422 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6423 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6427 // Treat indirect 'X' constraint as memory.
6428 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6430 OpInfo.ConstraintType = TargetLowering::C_Memory;
6432 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6433 std::vector<SDValue> Ops;
6434 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6437 LLVMContext &Ctx = *DAG.getContext();
6438 Ctx.emitError(CS.getInstruction(),
6439 "invalid operand for inline asm constraint '" +
6440 Twine(OpInfo.ConstraintCode) + "'");
6444 // Add information to the INLINEASM node to know about this input.
6445 unsigned ResOpType =
6446 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6447 AsmNodeOperands.push_back(DAG.getTargetConstant(
6448 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
6449 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6453 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6454 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6455 assert(InOperandVal.getValueType() ==
6456 TLI.getPointerTy(DAG.getDataLayout()) &&
6457 "Memory operands expect pointer values");
6459 unsigned ConstraintID =
6460 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6461 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6462 "Failed to convert memory constraint code to constraint id.");
6464 // Add information to the INLINEASM node to know about this input.
6465 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6466 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
6467 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6470 AsmNodeOperands.push_back(InOperandVal);
6474 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6475 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6476 "Unknown constraint type!");
6478 // TODO: Support this.
6479 if (OpInfo.isIndirect) {
6480 LLVMContext &Ctx = *DAG.getContext();
6481 Ctx.emitError(CS.getInstruction(),
6482 "Don't know how to handle indirect register inputs yet "
6483 "for constraint '" +
6484 Twine(OpInfo.ConstraintCode) + "'");
6488 // Copy the input into the appropriate registers.
6489 if (OpInfo.AssignedRegs.Regs.empty()) {
6490 LLVMContext &Ctx = *DAG.getContext();
6491 Ctx.emitError(CS.getInstruction(),
6492 "couldn't allocate input reg for constraint '" +
6493 Twine(OpInfo.ConstraintCode) + "'");
6497 SDLoc dl = getCurSDLoc();
6499 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6500 Chain, &Flag, CS.getInstruction());
6502 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6503 dl, DAG, AsmNodeOperands);
6506 case InlineAsm::isClobber: {
6507 // Add the clobbered value to the operand list, so that the register
6508 // allocator is aware that the physreg got clobbered.
6509 if (!OpInfo.AssignedRegs.Regs.empty())
6510 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6511 false, 0, getCurSDLoc(), DAG,
6518 // Finish up input operands. Set the input chain and add the flag last.
6519 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6520 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6522 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6523 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
6524 Flag = Chain.getValue(1);
6526 // If this asm returns a register value, copy the result from that register
6527 // and set it as the value of the call.
6528 if (!RetValRegs.Regs.empty()) {
6529 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6530 Chain, &Flag, CS.getInstruction());
6532 // FIXME: Why don't we do this for inline asms with MRVs?
6533 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6534 EVT ResultType = TLI.getValueType(DAG.getDataLayout(), CS.getType());
6536 // If any of the results of the inline asm is a vector, it may have the
6537 // wrong width/num elts. This can happen for register classes that can
6538 // contain multiple different value types. The preg or vreg allocated may
6539 // not have the same VT as was expected. Convert it to the right type
6540 // with bit_convert.
6541 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6542 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6545 } else if (ResultType != Val.getValueType() &&
6546 ResultType.isInteger() && Val.getValueType().isInteger()) {
6547 // If a result value was tied to an input value, the computed result may
6548 // have a wider width than the expected result. Extract the relevant
6550 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6553 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6556 setValue(CS.getInstruction(), Val);
6557 // Don't need to use this as a chain in this case.
6558 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6562 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6564 // Process indirect outputs, first output all of the flagged copies out of
6566 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6567 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6568 const Value *Ptr = IndirectStoresToEmit[i].second;
6569 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6571 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6574 // Emit the non-flagged stores from the physregs.
6575 SmallVector<SDValue, 8> OutChains;
6576 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6577 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6578 StoresToEmit[i].first,
6579 getValue(StoresToEmit[i].second),
6580 MachinePointerInfo(StoresToEmit[i].second),
6582 OutChains.push_back(Val);
6585 if (!OutChains.empty())
6586 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
6591 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6592 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6593 MVT::Other, getRoot(),
6594 getValue(I.getArgOperand(0)),
6595 DAG.getSrcValue(I.getArgOperand(0))));
6598 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6599 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6600 const DataLayout &DL = DAG.getDataLayout();
6601 SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6602 getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
6603 DAG.getSrcValue(I.getOperand(0)),
6604 DL.getABITypeAlignment(I.getType()));
6606 DAG.setRoot(V.getValue(1));
6609 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6610 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6611 MVT::Other, getRoot(),
6612 getValue(I.getArgOperand(0)),
6613 DAG.getSrcValue(I.getArgOperand(0))));
6616 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6617 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6618 MVT::Other, getRoot(),
6619 getValue(I.getArgOperand(0)),
6620 getValue(I.getArgOperand(1)),
6621 DAG.getSrcValue(I.getArgOperand(0)),
6622 DAG.getSrcValue(I.getArgOperand(1))));
6625 /// \brief Lower an argument list according to the target calling convention.
6627 /// \return A tuple of <return-value, token-chain>
6629 /// This is a helper for lowering intrinsics that follow a target calling
6630 /// convention or require stack pointer adjustment. Only a subset of the
6631 /// intrinsic's operands need to participate in the calling convention.
6632 std::pair<SDValue, SDValue> SelectionDAGBuilder::lowerCallOperands(
6633 ImmutableCallSite CS, unsigned ArgIdx, unsigned NumArgs, SDValue Callee,
6634 Type *ReturnTy, const BasicBlock *EHPadBB, bool IsPatchPoint) {
6635 TargetLowering::ArgListTy Args;
6636 Args.reserve(NumArgs);
6638 // Populate the argument list.
6639 // Attributes for args start at offset 1, after the return attribute.
6640 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6641 ArgI != ArgE; ++ArgI) {
6642 const Value *V = CS->getOperand(ArgI);
6644 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6646 TargetLowering::ArgListEntry Entry;
6647 Entry.Node = getValue(V);
6648 Entry.Ty = V->getType();
6649 Entry.setAttributes(&CS, AttrI);
6650 Args.push_back(Entry);
6653 TargetLowering::CallLoweringInfo CLI(DAG);
6654 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
6655 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args), NumArgs)
6656 .setDiscardResult(CS->use_empty()).setIsPatchPoint(IsPatchPoint);
6658 return lowerInvokable(CLI, EHPadBB);
6661 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6662 /// or patchpoint target node's operand list.
6664 /// Constants are converted to TargetConstants purely as an optimization to
6665 /// avoid constant materialization and register allocation.
6667 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6668 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6669 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6670 /// address materialization and register allocation, but may also be required
6671 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6672 /// alloca in the entry block, then the runtime may assume that the alloca's
6673 /// StackMap location can be read immediately after compilation and that the
6674 /// location is valid at any point during execution (this is similar to the
6675 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6676 /// only available in a register, then the runtime would need to trap when
6677 /// execution reaches the StackMap in order to read the alloca's location.
6678 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
6679 SDLoc DL, SmallVectorImpl<SDValue> &Ops,
6680 SelectionDAGBuilder &Builder) {
6681 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
6682 SDValue OpVal = Builder.getValue(CS.getArgument(i));
6683 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6685 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
6687 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
6688 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6689 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6690 Ops.push_back(Builder.DAG.getTargetFrameIndex(
6691 FI->getIndex(), TLI.getPointerTy(Builder.DAG.getDataLayout())));
6693 Ops.push_back(OpVal);
6697 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6698 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6699 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6700 // [live variables...])
6702 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6704 SDValue Chain, InFlag, Callee, NullPtr;
6705 SmallVector<SDValue, 32> Ops;
6707 SDLoc DL = getCurSDLoc();
6708 Callee = getValue(CI.getCalledValue());
6709 NullPtr = DAG.getIntPtrConstant(0, DL, true);
6711 // The stackmap intrinsic only records the live variables (the arguemnts
6712 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
6713 // intrinsic, this won't be lowered to a function call. This means we don't
6714 // have to worry about calling conventions and target specific lowering code.
6715 // Instead we perform the call lowering right here.
6717 // chain, flag = CALLSEQ_START(chain, 0)
6718 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
6719 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
6721 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
6722 InFlag = Chain.getValue(1);
6724 // Add the <id> and <numBytes> constants.
6725 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
6726 Ops.push_back(DAG.getTargetConstant(
6727 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
6728 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
6729 Ops.push_back(DAG.getTargetConstant(
6730 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
6733 // Push live variables for the stack map.
6734 addStackMapLiveVars(&CI, 2, DL, Ops, *this);
6736 // We are not pushing any register mask info here on the operands list,
6737 // because the stackmap doesn't clobber anything.
6739 // Push the chain and the glue flag.
6740 Ops.push_back(Chain);
6741 Ops.push_back(InFlag);
6743 // Create the STACKMAP node.
6744 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6745 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
6746 Chain = SDValue(SM, 0);
6747 InFlag = Chain.getValue(1);
6749 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
6751 // Stackmaps don't generate values, so nothing goes into the NodeMap.
6753 // Set the root to the target-lowered call chain.
6756 // Inform the Frame Information that we have a stackmap in this function.
6757 FuncInfo.MF->getFrameInfo()->setHasStackMap();
6760 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6761 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
6762 const BasicBlock *EHPadBB) {
6763 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
6768 // [live variables...])
6770 CallingConv::ID CC = CS.getCallingConv();
6771 bool IsAnyRegCC = CC == CallingConv::AnyReg;
6772 bool HasDef = !CS->getType()->isVoidTy();
6773 SDLoc dl = getCurSDLoc();
6774 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
6776 // Handle immediate and symbolic callees.
6777 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
6778 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
6780 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
6781 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
6782 SDLoc(SymbolicCallee),
6783 SymbolicCallee->getValueType(0));
6785 // Get the real number of arguments participating in the call <numArgs>
6786 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
6787 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
6789 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
6790 // Intrinsics include all meta-operands up to but not including CC.
6791 unsigned NumMetaOpers = PatchPointOpers::CCPos;
6792 assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
6793 "Not enough arguments provided to the patchpoint intrinsic");
6795 // For AnyRegCC the arguments are lowered later on manually.
6796 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
6798 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
6799 std::pair<SDValue, SDValue> Result = lowerCallOperands(
6800 CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy, EHPadBB, true);
6802 SDNode *CallEnd = Result.second.getNode();
6803 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
6804 CallEnd = CallEnd->getOperand(0).getNode();
6806 /// Get a call instruction from the call sequence chain.
6807 /// Tail calls are not allowed.
6808 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6809 "Expected a callseq node.");
6810 SDNode *Call = CallEnd->getOperand(0).getNode();
6811 bool HasGlue = Call->getGluedNode();
6813 // Replace the target specific call node with the patchable intrinsic.
6814 SmallVector<SDValue, 8> Ops;
6816 // Add the <id> and <numBytes> constants.
6817 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
6818 Ops.push_back(DAG.getTargetConstant(
6819 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
6820 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
6821 Ops.push_back(DAG.getTargetConstant(
6822 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
6826 Ops.push_back(Callee);
6828 // Adjust <numArgs> to account for any arguments that have been passed on the
6830 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
6831 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
6832 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
6833 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
6835 // Add the calling convention
6836 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
6838 // Add the arguments we omitted previously. The register allocator should
6839 // place these in any free register.
6841 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
6842 Ops.push_back(getValue(CS.getArgument(i)));
6844 // Push the arguments from the call instruction up to the register mask.
6845 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
6846 Ops.append(Call->op_begin() + 2, e);
6848 // Push live variables for the stack map.
6849 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
6851 // Push the register mask info.
6853 Ops.push_back(*(Call->op_end()-2));
6855 Ops.push_back(*(Call->op_end()-1));
6857 // Push the chain (this is originally the first operand of the call, but
6858 // becomes now the last or second to last operand).
6859 Ops.push_back(*(Call->op_begin()));
6861 // Push the glue flag (last operand).
6863 Ops.push_back(*(Call->op_end()-1));
6866 if (IsAnyRegCC && HasDef) {
6867 // Create the return types based on the intrinsic definition
6868 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6869 SmallVector<EVT, 3> ValueVTs;
6870 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
6871 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
6873 // There is always a chain and a glue type at the end
6874 ValueVTs.push_back(MVT::Other);
6875 ValueVTs.push_back(MVT::Glue);
6876 NodeTys = DAG.getVTList(ValueVTs);
6878 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6880 // Replace the target specific call node with a PATCHPOINT node.
6881 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
6884 // Update the NodeMap.
6887 setValue(CS.getInstruction(), SDValue(MN, 0));
6889 setValue(CS.getInstruction(), Result.first);
6892 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
6893 // call sequence. Furthermore the location of the chain and glue can change
6894 // when the AnyReg calling convention is used and the intrinsic returns a
6896 if (IsAnyRegCC && HasDef) {
6897 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
6898 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
6899 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
6901 DAG.ReplaceAllUsesWith(Call, MN);
6902 DAG.DeleteNode(Call);
6904 // Inform the Frame Information that we have a patchpoint in this function.
6905 FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
6908 /// Returns an AttributeSet representing the attributes applied to the return
6909 /// value of the given call.
6910 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
6911 SmallVector<Attribute::AttrKind, 2> Attrs;
6913 Attrs.push_back(Attribute::SExt);
6915 Attrs.push_back(Attribute::ZExt);
6917 Attrs.push_back(Attribute::InReg);
6919 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
6923 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6924 /// implementation, which just calls LowerCall.
6925 /// FIXME: When all targets are
6926 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6927 std::pair<SDValue, SDValue>
6928 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
6929 // Handle the incoming return values from the call.
6931 Type *OrigRetTy = CLI.RetTy;
6932 SmallVector<EVT, 4> RetTys;
6933 SmallVector<uint64_t, 4> Offsets;
6934 auto &DL = CLI.DAG.getDataLayout();
6935 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
6937 SmallVector<ISD::OutputArg, 4> Outs;
6938 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
6940 bool CanLowerReturn =
6941 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
6942 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
6944 SDValue DemoteStackSlot;
6945 int DemoteStackIdx = -100;
6946 if (!CanLowerReturn) {
6947 // FIXME: equivalent assert?
6948 // assert(!CS.hasInAllocaArgument() &&
6949 // "sret demotion is incompatible with inalloca");
6950 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
6951 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
6952 MachineFunction &MF = CLI.DAG.getMachineFunction();
6953 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6954 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
6956 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy(DL));
6958 Entry.Node = DemoteStackSlot;
6959 Entry.Ty = StackSlotPtrType;
6960 Entry.isSExt = false;
6961 Entry.isZExt = false;
6962 Entry.isInReg = false;
6963 Entry.isSRet = true;
6964 Entry.isNest = false;
6965 Entry.isByVal = false;
6966 Entry.isReturned = false;
6967 Entry.Alignment = Align;
6968 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
6969 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
6971 // sret demotion isn't compatible with tail-calls, since the sret argument
6972 // points into the callers stack frame.
6973 CLI.IsTailCall = false;
6975 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6977 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6978 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
6979 for (unsigned i = 0; i != NumRegs; ++i) {
6980 ISD::InputArg MyFlags;
6981 MyFlags.VT = RegisterVT;
6983 MyFlags.Used = CLI.IsReturnValueUsed;
6985 MyFlags.Flags.setSExt();
6987 MyFlags.Flags.setZExt();
6989 MyFlags.Flags.setInReg();
6990 CLI.Ins.push_back(MyFlags);
6995 // Handle all of the outgoing arguments.
6997 CLI.OutVals.clear();
6998 ArgListTy &Args = CLI.getArgs();
6999 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
7000 SmallVector<EVT, 4> ValueVTs;
7001 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
7002 Type *FinalType = Args[i].Ty;
7003 if (Args[i].isByVal)
7004 FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
7005 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
7006 FinalType, CLI.CallConv, CLI.IsVarArg);
7007 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
7009 EVT VT = ValueVTs[Value];
7010 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
7011 SDValue Op = SDValue(Args[i].Node.getNode(),
7012 Args[i].Node.getResNo() + Value);
7013 ISD::ArgFlagsTy Flags;
7014 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7020 if (Args[i].isInReg)
7024 if (Args[i].isByVal)
7026 if (Args[i].isInAlloca) {
7027 Flags.setInAlloca();
7028 // Set the byval flag for CCAssignFn callbacks that don't know about
7029 // inalloca. This way we can know how many bytes we should've allocated
7030 // and how many bytes a callee cleanup function will pop. If we port
7031 // inalloca to more targets, we'll have to add custom inalloca handling
7032 // in the various CC lowering callbacks.
7035 if (Args[i].isByVal || Args[i].isInAlloca) {
7036 PointerType *Ty = cast<PointerType>(Args[i].Ty);
7037 Type *ElementTy = Ty->getElementType();
7038 Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7039 // For ByVal, alignment should come from FE. BE will guess if this
7040 // info is not there but there are cases it cannot get right.
7041 unsigned FrameAlign;
7042 if (Args[i].Alignment)
7043 FrameAlign = Args[i].Alignment;
7045 FrameAlign = getByValTypeAlignment(ElementTy, DL);
7046 Flags.setByValAlign(FrameAlign);
7051 Flags.setInConsecutiveRegs();
7052 Flags.setOrigAlign(OriginalAlignment);
7054 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
7055 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
7056 SmallVector<SDValue, 4> Parts(NumParts);
7057 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
7060 ExtendKind = ISD::SIGN_EXTEND;
7061 else if (Args[i].isZExt)
7062 ExtendKind = ISD::ZERO_EXTEND;
7064 // Conservatively only handle 'returned' on non-vectors for now
7065 if (Args[i].isReturned && !Op.getValueType().isVector()) {
7066 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
7067 "unexpected use of 'returned'");
7068 // Before passing 'returned' to the target lowering code, ensure that
7069 // either the register MVT and the actual EVT are the same size or that
7070 // the return value and argument are extended in the same way; in these
7071 // cases it's safe to pass the argument register value unchanged as the
7072 // return register value (although it's at the target's option whether
7074 // TODO: allow code generation to take advantage of partially preserved
7075 // registers rather than clobbering the entire register when the
7076 // parameter extension method is not compatible with the return
7078 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
7079 (ExtendKind != ISD::ANY_EXTEND &&
7080 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
7081 Flags.setReturned();
7084 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
7085 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
7087 for (unsigned j = 0; j != NumParts; ++j) {
7088 // if it isn't first piece, alignment must be 1
7089 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
7090 i < CLI.NumFixedArgs,
7091 i, j*Parts[j].getValueType().getStoreSize());
7092 if (NumParts > 1 && j == 0)
7093 MyFlags.Flags.setSplit();
7095 MyFlags.Flags.setOrigAlign(1);
7097 CLI.Outs.push_back(MyFlags);
7098 CLI.OutVals.push_back(Parts[j]);
7101 if (NeedsRegBlock && Value == NumValues - 1)
7102 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
7106 SmallVector<SDValue, 4> InVals;
7107 CLI.Chain = LowerCall(CLI, InVals);
7109 // Verify that the target's LowerCall behaved as expected.
7110 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
7111 "LowerCall didn't return a valid chain!");
7112 assert((!CLI.IsTailCall || InVals.empty()) &&
7113 "LowerCall emitted a return value for a tail call!");
7114 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
7115 "LowerCall didn't emit the correct number of values!");
7117 // For a tail call, the return value is merely live-out and there aren't
7118 // any nodes in the DAG representing it. Return a special value to
7119 // indicate that a tail call has been emitted and no more Instructions
7120 // should be processed in the current block.
7121 if (CLI.IsTailCall) {
7122 CLI.DAG.setRoot(CLI.Chain);
7123 return std::make_pair(SDValue(), SDValue());
7126 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
7127 assert(InVals[i].getNode() &&
7128 "LowerCall emitted a null value!");
7129 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
7130 "LowerCall emitted a value with the wrong type!");
7133 SmallVector<SDValue, 4> ReturnValues;
7134 if (!CanLowerReturn) {
7135 // The instruction result is the result of loading from the
7136 // hidden sret parameter.
7137 SmallVector<EVT, 1> PVTs;
7138 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
7140 ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
7141 assert(PVTs.size() == 1 && "Pointers should fit in one register");
7142 EVT PtrVT = PVTs[0];
7144 unsigned NumValues = RetTys.size();
7145 ReturnValues.resize(NumValues);
7146 SmallVector<SDValue, 4> Chains(NumValues);
7148 for (unsigned i = 0; i < NumValues; ++i) {
7149 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
7150 CLI.DAG.getConstant(Offsets[i], CLI.DL,
7152 SDValue L = CLI.DAG.getLoad(
7153 RetTys[i], CLI.DL, CLI.Chain, Add,
7154 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
7155 DemoteStackIdx, Offsets[i]),
7156 false, false, false, 1);
7157 ReturnValues[i] = L;
7158 Chains[i] = L.getValue(1);
7161 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
7163 // Collect the legal value parts into potentially illegal values
7164 // that correspond to the original function's return values.
7165 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7167 AssertOp = ISD::AssertSext;
7168 else if (CLI.RetZExt)
7169 AssertOp = ISD::AssertZext;
7170 unsigned CurReg = 0;
7171 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
7173 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
7174 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
7176 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
7177 NumRegs, RegisterVT, VT, nullptr,
7182 // For a function returning void, there is no return value. We can't create
7183 // such a node, so we just return a null return value in that case. In
7184 // that case, nothing will actually look at the value.
7185 if (ReturnValues.empty())
7186 return std::make_pair(SDValue(), CLI.Chain);
7189 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
7190 CLI.DAG.getVTList(RetTys), ReturnValues);
7191 return std::make_pair(Res, CLI.Chain);
7194 void TargetLowering::LowerOperationWrapper(SDNode *N,
7195 SmallVectorImpl<SDValue> &Results,
7196 SelectionDAG &DAG) const {
7197 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
7199 Results.push_back(Res);
7202 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7203 llvm_unreachable("LowerOperation not implemented for this target!");
7207 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
7208 SDValue Op = getNonRegisterValue(V);
7209 assert((Op.getOpcode() != ISD::CopyFromReg ||
7210 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
7211 "Copy from a reg to the same reg!");
7212 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7214 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7215 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
7217 SDValue Chain = DAG.getEntryNode();
7219 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7220 FuncInfo.PreferredExtendType.end())
7222 : FuncInfo.PreferredExtendType[V];
7223 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
7224 PendingExports.push_back(Chain);
7227 #include "llvm/CodeGen/SelectionDAGISel.h"
7229 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7230 /// entry block, return true. This includes arguments used by switches, since
7231 /// the switch may expand into multiple basic blocks.
7232 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7233 // With FastISel active, we may be splitting blocks, so force creation
7234 // of virtual registers for all non-dead arguments.
7236 return A->use_empty();
7238 const BasicBlock *Entry = A->getParent()->begin();
7239 for (const User *U : A->users())
7240 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7241 return false; // Use not in entry block.
7246 void SelectionDAGISel::LowerArguments(const Function &F) {
7247 SelectionDAG &DAG = SDB->DAG;
7248 SDLoc dl = SDB->getCurSDLoc();
7249 const DataLayout &DL = DAG.getDataLayout();
7250 SmallVector<ISD::InputArg, 16> Ins;
7252 if (!FuncInfo->CanLowerReturn) {
7253 // Put in an sret pointer parameter before all the other parameters.
7254 SmallVector<EVT, 1> ValueVTs;
7255 ComputeValueVTs(*TLI, DAG.getDataLayout(),
7256 PointerType::getUnqual(F.getReturnType()), ValueVTs);
7258 // NOTE: Assuming that a pointer will never break down to more than one VT
7260 ISD::ArgFlagsTy Flags;
7262 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7263 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
7264 ISD::InputArg::NoArgIndex, 0);
7265 Ins.push_back(RetArg);
7268 // Set up the incoming argument description vector.
7270 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7271 I != E; ++I, ++Idx) {
7272 SmallVector<EVT, 4> ValueVTs;
7273 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7274 bool isArgValueUsed = !I->use_empty();
7275 unsigned PartBase = 0;
7276 Type *FinalType = I->getType();
7277 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7278 FinalType = cast<PointerType>(FinalType)->getElementType();
7279 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7280 FinalType, F.getCallingConv(), F.isVarArg());
7281 for (unsigned Value = 0, NumValues = ValueVTs.size();
7282 Value != NumValues; ++Value) {
7283 EVT VT = ValueVTs[Value];
7284 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7285 ISD::ArgFlagsTy Flags;
7286 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7288 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7290 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7292 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7294 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7296 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7298 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7299 Flags.setInAlloca();
7300 // Set the byval flag for CCAssignFn callbacks that don't know about
7301 // inalloca. This way we can know how many bytes we should've allocated
7302 // and how many bytes a callee cleanup function will pop. If we port
7303 // inalloca to more targets, we'll have to add custom inalloca handling
7304 // in the various CC lowering callbacks.
7307 if (Flags.isByVal() || Flags.isInAlloca()) {
7308 PointerType *Ty = cast<PointerType>(I->getType());
7309 Type *ElementTy = Ty->getElementType();
7310 Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7311 // For ByVal, alignment should be passed from FE. BE will guess if
7312 // this info is not there but there are cases it cannot get right.
7313 unsigned FrameAlign;
7314 if (F.getParamAlignment(Idx))
7315 FrameAlign = F.getParamAlignment(Idx);
7317 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
7318 Flags.setByValAlign(FrameAlign);
7320 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7323 Flags.setInConsecutiveRegs();
7324 Flags.setOrigAlign(OriginalAlignment);
7326 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7327 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7328 for (unsigned i = 0; i != NumRegs; ++i) {
7329 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7330 Idx-1, PartBase+i*RegisterVT.getStoreSize());
7331 if (NumRegs > 1 && i == 0)
7332 MyFlags.Flags.setSplit();
7333 // if it isn't first piece, alignment must be 1
7335 MyFlags.Flags.setOrigAlign(1);
7336 Ins.push_back(MyFlags);
7338 if (NeedsRegBlock && Value == NumValues - 1)
7339 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
7340 PartBase += VT.getStoreSize();
7344 // Call the target to set up the argument values.
7345 SmallVector<SDValue, 8> InVals;
7346 SDValue NewRoot = TLI->LowerFormalArguments(
7347 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
7349 // Verify that the target's LowerFormalArguments behaved as expected.
7350 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7351 "LowerFormalArguments didn't return a valid chain!");
7352 assert(InVals.size() == Ins.size() &&
7353 "LowerFormalArguments didn't emit the correct number of values!");
7355 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7356 assert(InVals[i].getNode() &&
7357 "LowerFormalArguments emitted a null value!");
7358 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7359 "LowerFormalArguments emitted a value with the wrong type!");
7363 // Update the DAG with the new chain value resulting from argument lowering.
7364 DAG.setRoot(NewRoot);
7366 // Set up the argument values.
7369 if (!FuncInfo->CanLowerReturn) {
7370 // Create a virtual register for the sret pointer, and put in a copy
7371 // from the sret argument into it.
7372 SmallVector<EVT, 1> ValueVTs;
7373 ComputeValueVTs(*TLI, DAG.getDataLayout(),
7374 PointerType::getUnqual(F.getReturnType()), ValueVTs);
7375 MVT VT = ValueVTs[0].getSimpleVT();
7376 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7377 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7378 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7379 RegVT, VT, nullptr, AssertOp);
7381 MachineFunction& MF = SDB->DAG.getMachineFunction();
7382 MachineRegisterInfo& RegInfo = MF.getRegInfo();
7383 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7384 FuncInfo->DemoteRegister = SRetReg;
7386 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
7387 DAG.setRoot(NewRoot);
7389 // i indexes lowered arguments. Bump it past the hidden sret argument.
7390 // Idx indexes LLVM arguments. Don't touch it.
7394 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7396 SmallVector<SDValue, 4> ArgValues;
7397 SmallVector<EVT, 4> ValueVTs;
7398 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7399 unsigned NumValues = ValueVTs.size();
7401 // If this argument is unused then remember its value. It is used to generate
7402 // debugging information.
7403 if (I->use_empty() && NumValues) {
7404 SDB->setUnusedArgValue(I, InVals[i]);
7406 // Also remember any frame index for use in FastISel.
7407 if (FrameIndexSDNode *FI =
7408 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7409 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7412 for (unsigned Val = 0; Val != NumValues; ++Val) {
7413 EVT VT = ValueVTs[Val];
7414 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7415 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7417 if (!I->use_empty()) {
7418 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7419 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7420 AssertOp = ISD::AssertSext;
7421 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7422 AssertOp = ISD::AssertZext;
7424 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7425 NumParts, PartVT, VT,
7426 nullptr, AssertOp));
7432 // We don't need to do anything else for unused arguments.
7433 if (ArgValues.empty())
7436 // Note down frame index.
7437 if (FrameIndexSDNode *FI =
7438 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7439 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7441 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
7442 SDB->getCurSDLoc());
7444 SDB->setValue(I, Res);
7445 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7446 if (LoadSDNode *LNode =
7447 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7448 if (FrameIndexSDNode *FI =
7449 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7450 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7453 // If this argument is live outside of the entry block, insert a copy from
7454 // wherever we got it to the vreg that other BB's will reference it as.
7455 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7456 // If we can, though, try to skip creating an unnecessary vreg.
7457 // FIXME: This isn't very clean... it would be nice to make this more
7458 // general. It's also subtly incompatible with the hacks FastISel
7460 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7461 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7462 FuncInfo->ValueMap[I] = Reg;
7466 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
7467 FuncInfo->InitializeRegForValue(I);
7468 SDB->CopyToExportRegsIfNeeded(I);
7472 assert(i == InVals.size() && "Argument register count mismatch!");
7474 // Finally, if the target has anything special to do, allow it to do so.
7475 EmitFunctionEntryCode();
7478 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7479 /// ensure constants are generated when needed. Remember the virtual registers
7480 /// that need to be added to the Machine PHI nodes as input. We cannot just
7481 /// directly add them, because expansion might result in multiple MBB's for one
7482 /// BB. As such, the start of the BB might correspond to a different MBB than
7486 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7487 const TerminatorInst *TI = LLVMBB->getTerminator();
7489 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7491 // Check PHI nodes in successors that expect a value to be available from this
7493 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7494 const BasicBlock *SuccBB = TI->getSuccessor(succ);
7495 if (!isa<PHINode>(SuccBB->begin())) continue;
7496 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7498 // If this terminator has multiple identical successors (common for
7499 // switches), only handle each succ once.
7500 if (!SuccsHandled.insert(SuccMBB).second)
7503 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7505 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7506 // nodes and Machine PHI nodes, but the incoming operands have not been
7508 for (BasicBlock::const_iterator I = SuccBB->begin();
7509 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7510 // Ignore dead phi's.
7511 if (PN->use_empty()) continue;
7514 if (PN->getType()->isEmptyTy())
7518 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7520 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7521 unsigned &RegOut = ConstantsOut[C];
7523 RegOut = FuncInfo.CreateRegs(C->getType());
7524 CopyValueToVirtualRegister(C, RegOut);
7528 DenseMap<const Value *, unsigned>::iterator I =
7529 FuncInfo.ValueMap.find(PHIOp);
7530 if (I != FuncInfo.ValueMap.end())
7533 assert(isa<AllocaInst>(PHIOp) &&
7534 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7535 "Didn't codegen value into a register!??");
7536 Reg = FuncInfo.CreateRegs(PHIOp->getType());
7537 CopyValueToVirtualRegister(PHIOp, Reg);
7541 // Remember that this register needs to added to the machine PHI node as
7542 // the input for this MBB.
7543 SmallVector<EVT, 4> ValueVTs;
7544 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7545 ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
7546 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7547 EVT VT = ValueVTs[vti];
7548 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
7549 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7550 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7551 Reg += NumRegisters;
7556 ConstantsOut.clear();
7559 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7562 SelectionDAGBuilder::StackProtectorDescriptor::
7563 AddSuccessorMBB(const BasicBlock *BB,
7564 MachineBasicBlock *ParentMBB,
7566 MachineBasicBlock *SuccMBB) {
7567 // If SuccBB has not been created yet, create it.
7569 MachineFunction *MF = ParentMBB->getParent();
7570 MachineFunction::iterator BBI = ParentMBB;
7571 SuccMBB = MF->CreateMachineBasicBlock(BB);
7572 MF->insert(++BBI, SuccMBB);
7574 // Add it as a successor of ParentMBB.
7575 ParentMBB->addSuccessor(
7576 SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely));
7580 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
7581 MachineFunction::iterator I = MBB;
7582 if (++I == FuncInfo.MF->end())
7587 /// During lowering new call nodes can be created (such as memset, etc.).
7588 /// Those will become new roots of the current DAG, but complications arise
7589 /// when they are tail calls. In such cases, the call lowering will update
7590 /// the root, but the builder still needs to know that a tail call has been
7591 /// lowered in order to avoid generating an additional return.
7592 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
7593 // If the node is null, we do have a tail call.
7594 if (MaybeTC.getNode() != nullptr)
7595 DAG.setRoot(MaybeTC);
7600 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters,
7601 unsigned *TotalCases, unsigned First,
7603 assert(Last >= First);
7604 assert(TotalCases[Last] >= TotalCases[First]);
7606 APInt LowCase = Clusters[First].Low->getValue();
7607 APInt HighCase = Clusters[Last].High->getValue();
7608 assert(LowCase.getBitWidth() == HighCase.getBitWidth());
7610 // FIXME: A range of consecutive cases has 100% density, but only requires one
7611 // comparison to lower. We should discriminate against such consecutive ranges
7614 uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100);
7615 uint64_t Range = Diff + 1;
7618 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
7620 assert(NumCases < UINT64_MAX / 100);
7621 assert(Range >= NumCases);
7623 return NumCases * 100 >= Range * MinJumpTableDensity;
7626 static inline bool areJTsAllowed(const TargetLowering &TLI) {
7627 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
7628 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
7631 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters,
7632 unsigned First, unsigned Last,
7633 const SwitchInst *SI,
7634 MachineBasicBlock *DefaultMBB,
7635 CaseCluster &JTCluster) {
7636 assert(First <= Last);
7638 uint32_t Weight = 0;
7639 unsigned NumCmps = 0;
7640 std::vector<MachineBasicBlock*> Table;
7641 DenseMap<MachineBasicBlock*, uint32_t> JTWeights;
7642 for (unsigned I = First; I <= Last; ++I) {
7643 assert(Clusters[I].Kind == CC_Range);
7644 Weight += Clusters[I].Weight;
7645 assert(Weight >= Clusters[I].Weight && "Weight overflow!");
7646 APInt Low = Clusters[I].Low->getValue();
7647 APInt High = Clusters[I].High->getValue();
7648 NumCmps += (Low == High) ? 1 : 2;
7650 // Fill the gap between this and the previous cluster.
7651 APInt PreviousHigh = Clusters[I - 1].High->getValue();
7652 assert(PreviousHigh.slt(Low));
7653 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
7654 for (uint64_t J = 0; J < Gap; J++)
7655 Table.push_back(DefaultMBB);
7657 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
7658 for (uint64_t J = 0; J < ClusterSize; ++J)
7659 Table.push_back(Clusters[I].MBB);
7660 JTWeights[Clusters[I].MBB] += Clusters[I].Weight;
7663 unsigned NumDests = JTWeights.size();
7664 if (isSuitableForBitTests(NumDests, NumCmps,
7665 Clusters[First].Low->getValue(),
7666 Clusters[Last].High->getValue())) {
7667 // Clusters[First..Last] should be lowered as bit tests instead.
7671 // Create the MBB that will load from and jump through the table.
7672 // Note: We create it here, but it's not inserted into the function yet.
7673 MachineFunction *CurMF = FuncInfo.MF;
7674 MachineBasicBlock *JumpTableMBB =
7675 CurMF->CreateMachineBasicBlock(SI->getParent());
7677 // Add successors. Note: use table order for determinism.
7678 SmallPtrSet<MachineBasicBlock *, 8> Done;
7679 for (MachineBasicBlock *Succ : Table) {
7680 if (Done.count(Succ))
7682 addSuccessorWithWeight(JumpTableMBB, Succ, JTWeights[Succ]);
7686 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7687 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
7688 ->createJumpTableIndex(Table);
7690 // Set up the jump table info.
7691 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
7692 JumpTableHeader JTH(Clusters[First].Low->getValue(),
7693 Clusters[Last].High->getValue(), SI->getCondition(),
7695 JTCases.emplace_back(std::move(JTH), std::move(JT));
7697 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
7698 JTCases.size() - 1, Weight);
7702 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
7703 const SwitchInst *SI,
7704 MachineBasicBlock *DefaultMBB) {
7706 // Clusters must be non-empty, sorted, and only contain Range clusters.
7707 assert(!Clusters.empty());
7708 for (CaseCluster &C : Clusters)
7709 assert(C.Kind == CC_Range);
7710 for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
7711 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
7714 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7715 if (!areJTsAllowed(TLI))
7718 const int64_t N = Clusters.size();
7719 const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries();
7721 // TotalCases[i]: Total nbr of cases in Clusters[0..i].
7722 SmallVector<unsigned, 8> TotalCases(N);
7724 for (unsigned i = 0; i < N; ++i) {
7725 APInt Hi = Clusters[i].High->getValue();
7726 APInt Lo = Clusters[i].Low->getValue();
7727 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
7729 TotalCases[i] += TotalCases[i - 1];
7732 if (N >= MinJumpTableSize && isDense(Clusters, &TotalCases[0], 0, N - 1)) {
7733 // Cheap case: the whole range might be suitable for jump table.
7734 CaseCluster JTCluster;
7735 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
7736 Clusters[0] = JTCluster;
7742 // The algorithm below is not suitable for -O0.
7743 if (TM.getOptLevel() == CodeGenOpt::None)
7746 // Split Clusters into minimum number of dense partitions. The algorithm uses
7747 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
7748 // for the Case Statement'" (1994), but builds the MinPartitions array in
7749 // reverse order to make it easier to reconstruct the partitions in ascending
7750 // order. In the choice between two optimal partitionings, it picks the one
7751 // which yields more jump tables.
7753 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
7754 SmallVector<unsigned, 8> MinPartitions(N);
7755 // LastElement[i] is the last element of the partition starting at i.
7756 SmallVector<unsigned, 8> LastElement(N);
7757 // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1].
7758 SmallVector<unsigned, 8> NumTables(N);
7760 // Base case: There is only one way to partition Clusters[N-1].
7761 MinPartitions[N - 1] = 1;
7762 LastElement[N - 1] = N - 1;
7763 assert(MinJumpTableSize > 1);
7764 NumTables[N - 1] = 0;
7766 // Note: loop indexes are signed to avoid underflow.
7767 for (int64_t i = N - 2; i >= 0; i--) {
7768 // Find optimal partitioning of Clusters[i..N-1].
7769 // Baseline: Put Clusters[i] into a partition on its own.
7770 MinPartitions[i] = MinPartitions[i + 1] + 1;
7772 NumTables[i] = NumTables[i + 1];
7774 // Search for a solution that results in fewer partitions.
7775 for (int64_t j = N - 1; j > i; j--) {
7776 // Try building a partition from Clusters[i..j].
7777 if (isDense(Clusters, &TotalCases[0], i, j)) {
7778 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
7779 bool IsTable = j - i + 1 >= MinJumpTableSize;
7780 unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]);
7782 // If this j leads to fewer partitions, or same number of partitions
7783 // with more lookup tables, it is a better partitioning.
7784 if (NumPartitions < MinPartitions[i] ||
7785 (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) {
7786 MinPartitions[i] = NumPartitions;
7788 NumTables[i] = Tables;
7794 // Iterate over the partitions, replacing some with jump tables in-place.
7795 unsigned DstIndex = 0;
7796 for (unsigned First = 0, Last; First < N; First = Last + 1) {
7797 Last = LastElement[First];
7798 assert(Last >= First);
7799 assert(DstIndex <= First);
7800 unsigned NumClusters = Last - First + 1;
7802 CaseCluster JTCluster;
7803 if (NumClusters >= MinJumpTableSize &&
7804 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
7805 Clusters[DstIndex++] = JTCluster;
7807 for (unsigned I = First; I <= Last; ++I)
7808 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
7811 Clusters.resize(DstIndex);
7814 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) {
7815 // FIXME: Using the pointer type doesn't seem ideal.
7816 uint64_t BW = DAG.getDataLayout().getPointerSizeInBits();
7817 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
7821 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests,
7824 const APInt &High) {
7825 // FIXME: I don't think NumCmps is the correct metric: a single case and a
7826 // range of cases both require only one branch to lower. Just looking at the
7827 // number of clusters and destinations should be enough to decide whether to
7830 // To lower a range with bit tests, the range must fit the bitwidth of a
7832 if (!rangeFitsInWord(Low, High))
7835 // Decide whether it's profitable to lower this range with bit tests. Each
7836 // destination requires a bit test and branch, and there is an overall range
7837 // check branch. For a small number of clusters, separate comparisons might be
7838 // cheaper, and for many destinations, splitting the range might be better.
7839 return (NumDests == 1 && NumCmps >= 3) ||
7840 (NumDests == 2 && NumCmps >= 5) ||
7841 (NumDests == 3 && NumCmps >= 6);
7844 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
7845 unsigned First, unsigned Last,
7846 const SwitchInst *SI,
7847 CaseCluster &BTCluster) {
7848 assert(First <= Last);
7852 BitVector Dests(FuncInfo.MF->getNumBlockIDs());
7853 unsigned NumCmps = 0;
7854 for (int64_t I = First; I <= Last; ++I) {
7855 assert(Clusters[I].Kind == CC_Range);
7856 Dests.set(Clusters[I].MBB->getNumber());
7857 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
7859 unsigned NumDests = Dests.count();
7861 APInt Low = Clusters[First].Low->getValue();
7862 APInt High = Clusters[Last].High->getValue();
7863 assert(Low.slt(High));
7865 if (!isSuitableForBitTests(NumDests, NumCmps, Low, High))
7871 const int BitWidth = DAG.getTargetLoweringInfo()
7872 .getPointerTy(DAG.getDataLayout())
7874 assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!");
7876 // Check if the clusters cover a contiguous range such that no value in the
7877 // range will jump to the default statement.
7878 bool ContiguousRange = true;
7879 for (int64_t I = First + 1; I <= Last; ++I) {
7880 if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
7881 ContiguousRange = false;
7886 if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
7887 // Optimize the case where all the case values fit in a word without having
7888 // to subtract minValue. In this case, we can optimize away the subtraction.
7889 LowBound = APInt::getNullValue(Low.getBitWidth());
7891 ContiguousRange = false;
7894 CmpRange = High - Low;
7898 uint32_t TotalWeight = 0;
7899 for (unsigned i = First; i <= Last; ++i) {
7900 // Find the CaseBits for this destination.
7902 for (j = 0; j < CBV.size(); ++j)
7903 if (CBV[j].BB == Clusters[i].MBB)
7905 if (j == CBV.size())
7906 CBV.push_back(CaseBits(0, Clusters[i].MBB, 0, 0));
7907 CaseBits *CB = &CBV[j];
7909 // Update Mask, Bits and ExtraWeight.
7910 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
7911 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
7912 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
7913 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
7914 CB->Bits += Hi - Lo + 1;
7915 CB->ExtraWeight += Clusters[i].Weight;
7916 TotalWeight += Clusters[i].Weight;
7917 assert(TotalWeight >= Clusters[i].Weight && "Weight overflow!");
7921 std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
7922 // Sort by weight first, number of bits second.
7923 if (a.ExtraWeight != b.ExtraWeight)
7924 return a.ExtraWeight > b.ExtraWeight;
7925 return a.Bits > b.Bits;
7928 for (auto &CB : CBV) {
7929 MachineBasicBlock *BitTestBB =
7930 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
7931 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraWeight));
7933 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
7934 SI->getCondition(), -1U, MVT::Other, false,
7935 ContiguousRange, nullptr, nullptr, std::move(BTI),
7938 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
7939 BitTestCases.size() - 1, TotalWeight);
7943 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
7944 const SwitchInst *SI) {
7945 // Partition Clusters into as few subsets as possible, where each subset has a
7946 // range that fits in a machine word and has <= 3 unique destinations.
7949 // Clusters must be sorted and contain Range or JumpTable clusters.
7950 assert(!Clusters.empty());
7951 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
7952 for (const CaseCluster &C : Clusters)
7953 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
7954 for (unsigned i = 1; i < Clusters.size(); ++i)
7955 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
7958 // The algorithm below is not suitable for -O0.
7959 if (TM.getOptLevel() == CodeGenOpt::None)
7962 // If target does not have legal shift left, do not emit bit tests at all.
7963 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7964 EVT PTy = TLI.getPointerTy(DAG.getDataLayout());
7965 if (!TLI.isOperationLegal(ISD::SHL, PTy))
7968 int BitWidth = PTy.getSizeInBits();
7969 const int64_t N = Clusters.size();
7971 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
7972 SmallVector<unsigned, 8> MinPartitions(N);
7973 // LastElement[i] is the last element of the partition starting at i.
7974 SmallVector<unsigned, 8> LastElement(N);
7976 // FIXME: This might not be the best algorithm for finding bit test clusters.
7978 // Base case: There is only one way to partition Clusters[N-1].
7979 MinPartitions[N - 1] = 1;
7980 LastElement[N - 1] = N - 1;
7982 // Note: loop indexes are signed to avoid underflow.
7983 for (int64_t i = N - 2; i >= 0; --i) {
7984 // Find optimal partitioning of Clusters[i..N-1].
7985 // Baseline: Put Clusters[i] into a partition on its own.
7986 MinPartitions[i] = MinPartitions[i + 1] + 1;
7989 // Search for a solution that results in fewer partitions.
7990 // Note: the search is limited by BitWidth, reducing time complexity.
7991 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
7992 // Try building a partition from Clusters[i..j].
7995 if (!rangeFitsInWord(Clusters[i].Low->getValue(),
7996 Clusters[j].High->getValue()))
7999 // Check nbr of destinations and cluster types.
8000 // FIXME: This works, but doesn't seem very efficient.
8001 bool RangesOnly = true;
8002 BitVector Dests(FuncInfo.MF->getNumBlockIDs());
8003 for (int64_t k = i; k <= j; k++) {
8004 if (Clusters[k].Kind != CC_Range) {
8008 Dests.set(Clusters[k].MBB->getNumber());
8010 if (!RangesOnly || Dests.count() > 3)
8013 // Check if it's a better partition.
8014 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
8015 if (NumPartitions < MinPartitions[i]) {
8016 // Found a better partition.
8017 MinPartitions[i] = NumPartitions;
8023 // Iterate over the partitions, replacing with bit-test clusters in-place.
8024 unsigned DstIndex = 0;
8025 for (unsigned First = 0, Last; First < N; First = Last + 1) {
8026 Last = LastElement[First];
8027 assert(First <= Last);
8028 assert(DstIndex <= First);
8030 CaseCluster BitTestCluster;
8031 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
8032 Clusters[DstIndex++] = BitTestCluster;
8034 size_t NumClusters = Last - First + 1;
8035 std::memmove(&Clusters[DstIndex], &Clusters[First],
8036 sizeof(Clusters[0]) * NumClusters);
8037 DstIndex += NumClusters;
8040 Clusters.resize(DstIndex);
8043 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
8044 MachineBasicBlock *SwitchMBB,
8045 MachineBasicBlock *DefaultMBB) {
8046 MachineFunction *CurMF = FuncInfo.MF;
8047 MachineBasicBlock *NextMBB = nullptr;
8048 MachineFunction::iterator BBI = W.MBB;
8049 if (++BBI != FuncInfo.MF->end())
8052 unsigned Size = W.LastCluster - W.FirstCluster + 1;
8054 BranchProbabilityInfo *BPI = FuncInfo.BPI;
8056 if (Size == 2 && W.MBB == SwitchMBB) {
8057 // If any two of the cases has the same destination, and if one value
8058 // is the same as the other, but has one bit unset that the other has set,
8059 // use bit manipulation to do two compares at once. For example:
8060 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
8061 // TODO: This could be extended to merge any 2 cases in switches with 3
8063 // TODO: Handle cases where W.CaseBB != SwitchBB.
8064 CaseCluster &Small = *W.FirstCluster;
8065 CaseCluster &Big = *W.LastCluster;
8067 if (Small.Low == Small.High && Big.Low == Big.High &&
8068 Small.MBB == Big.MBB) {
8069 const APInt &SmallValue = Small.Low->getValue();
8070 const APInt &BigValue = Big.Low->getValue();
8072 // Check that there is only one bit different.
8073 APInt CommonBit = BigValue ^ SmallValue;
8074 if (CommonBit.isPowerOf2()) {
8075 SDValue CondLHS = getValue(Cond);
8076 EVT VT = CondLHS.getValueType();
8077 SDLoc DL = getCurSDLoc();
8079 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
8080 DAG.getConstant(CommonBit, DL, VT));
8081 SDValue Cond = DAG.getSetCC(
8082 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
8085 // Update successor info.
8086 // Both Small and Big will jump to Small.BB, so we sum up the weights.
8087 addSuccessorWithWeight(SwitchMBB, Small.MBB, Small.Weight + Big.Weight);
8088 addSuccessorWithWeight(
8089 SwitchMBB, DefaultMBB,
8090 // The default destination is the first successor in IR.
8091 BPI ? BPI->getEdgeWeight(SwitchMBB->getBasicBlock(), (unsigned)0)
8094 // Insert the true branch.
8096 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
8097 DAG.getBasicBlock(Small.MBB));
8098 // Insert the false branch.
8099 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
8100 DAG.getBasicBlock(DefaultMBB));
8102 DAG.setRoot(BrCond);
8108 if (TM.getOptLevel() != CodeGenOpt::None) {
8109 // Order cases by weight so the most likely case will be checked first.
8110 std::sort(W.FirstCluster, W.LastCluster + 1,
8111 [](const CaseCluster &a, const CaseCluster &b) {
8112 return a.Weight > b.Weight;
8115 // Rearrange the case blocks so that the last one falls through if possible
8116 // without without changing the order of weights.
8117 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
8119 if (I->Weight > W.LastCluster->Weight)
8121 if (I->Kind == CC_Range && I->MBB == NextMBB) {
8122 std::swap(*I, *W.LastCluster);
8128 // Compute total weight.
8129 uint32_t DefaultWeight = W.DefaultWeight;
8130 uint32_t UnhandledWeights = DefaultWeight;
8131 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) {
8132 UnhandledWeights += I->Weight;
8133 assert(UnhandledWeights >= I->Weight && "Weight overflow!");
8136 MachineBasicBlock *CurMBB = W.MBB;
8137 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
8138 MachineBasicBlock *Fallthrough;
8139 if (I == W.LastCluster) {
8140 // For the last cluster, fall through to the default destination.
8141 Fallthrough = DefaultMBB;
8143 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
8144 CurMF->insert(BBI, Fallthrough);
8145 // Put Cond in a virtual register to make it available from the new blocks.
8146 ExportFromCurrentBlock(Cond);
8148 UnhandledWeights -= I->Weight;
8151 case CC_JumpTable: {
8152 // FIXME: Optimize away range check based on pivot comparisons.
8153 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
8154 JumpTable *JT = &JTCases[I->JTCasesIndex].second;
8156 // The jump block hasn't been inserted yet; insert it here.
8157 MachineBasicBlock *JumpMBB = JT->MBB;
8158 CurMF->insert(BBI, JumpMBB);
8160 uint32_t JumpWeight = I->Weight;
8161 uint32_t FallthroughWeight = UnhandledWeights;
8163 // If the default statement is a target of the jump table, we evenly
8164 // distribute the default weight to successors of CurMBB. Also update
8165 // the weight on the edge from JumpMBB to Fallthrough.
8166 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
8167 SE = JumpMBB->succ_end();
8169 if (*SI == DefaultMBB) {
8170 JumpWeight += DefaultWeight / 2;
8171 FallthroughWeight -= DefaultWeight / 2;
8172 JumpMBB->setSuccWeight(SI, DefaultWeight / 2);
8177 addSuccessorWithWeight(CurMBB, Fallthrough, FallthroughWeight);
8178 addSuccessorWithWeight(CurMBB, JumpMBB, JumpWeight);
8180 // The jump table header will be inserted in our current block, do the
8181 // range check, and fall through to our fallthrough block.
8182 JTH->HeaderBB = CurMBB;
8183 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
8185 // If we're in the right place, emit the jump table header right now.
8186 if (CurMBB == SwitchMBB) {
8187 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
8188 JTH->Emitted = true;
8193 // FIXME: Optimize away range check based on pivot comparisons.
8194 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
8196 // The bit test blocks haven't been inserted yet; insert them here.
8197 for (BitTestCase &BTC : BTB->Cases)
8198 CurMF->insert(BBI, BTC.ThisBB);
8200 // Fill in fields of the BitTestBlock.
8201 BTB->Parent = CurMBB;
8202 BTB->Default = Fallthrough;
8204 BTB->DefaultWeight = UnhandledWeights;
8205 // If the cases in bit test don't form a contiguous range, we evenly
8206 // distribute the weight on the edge to Fallthrough to two successors
8208 if (!BTB->ContiguousRange) {
8209 BTB->Weight += DefaultWeight / 2;
8210 BTB->DefaultWeight -= DefaultWeight / 2;
8213 // If we're in the right place, emit the bit test header right now.
8214 if (CurMBB == SwitchMBB) {
8215 visitBitTestHeader(*BTB, SwitchMBB);
8216 BTB->Emitted = true;
8221 const Value *RHS, *LHS, *MHS;
8223 if (I->Low == I->High) {
8224 // Check Cond == I->Low.
8230 // Check I->Low <= Cond <= I->High.
8237 // The false weight is the sum of all unhandled cases.
8238 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Weight,
8241 if (CurMBB == SwitchMBB)
8242 visitSwitchCase(CB, SwitchMBB);
8244 SwitchCases.push_back(CB);
8249 CurMBB = Fallthrough;
8253 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
8254 CaseClusterIt First,
8255 CaseClusterIt Last) {
8256 return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
8257 if (X.Weight != CC.Weight)
8258 return X.Weight > CC.Weight;
8260 // Ties are broken by comparing the case value.
8261 return X.Low->getValue().slt(CC.Low->getValue());
8265 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
8266 const SwitchWorkListItem &W,
8268 MachineBasicBlock *SwitchMBB) {
8269 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
8270 "Clusters not sorted?");
8272 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
8274 // Balance the tree based on branch weights to create a near-optimal (in terms
8275 // of search time given key frequency) binary search tree. See e.g. Kurt
8276 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
8277 CaseClusterIt LastLeft = W.FirstCluster;
8278 CaseClusterIt FirstRight = W.LastCluster;
8279 uint32_t LeftWeight = LastLeft->Weight + W.DefaultWeight / 2;
8280 uint32_t RightWeight = FirstRight->Weight + W.DefaultWeight / 2;
8282 // Move LastLeft and FirstRight towards each other from opposite directions to
8283 // find a partitioning of the clusters which balances the weight on both
8284 // sides. If LeftWeight and RightWeight are equal, alternate which side is
8285 // taken to ensure 0-weight nodes are distributed evenly.
8287 while (LastLeft + 1 < FirstRight) {
8288 if (LeftWeight < RightWeight || (LeftWeight == RightWeight && (I & 1)))
8289 LeftWeight += (++LastLeft)->Weight;
8291 RightWeight += (--FirstRight)->Weight;
8296 // Our binary search tree differs from a typical BST in that ours can have up
8297 // to three values in each leaf. The pivot selection above doesn't take that
8298 // into account, which means the tree might require more nodes and be less
8299 // efficient. We compensate for this here.
8301 unsigned NumLeft = LastLeft - W.FirstCluster + 1;
8302 unsigned NumRight = W.LastCluster - FirstRight + 1;
8304 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
8305 // If one side has less than 3 clusters, and the other has more than 3,
8306 // consider taking a cluster from the other side.
8308 if (NumLeft < NumRight) {
8309 // Consider moving the first cluster on the right to the left side.
8310 CaseCluster &CC = *FirstRight;
8311 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8312 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8313 if (LeftSideRank <= RightSideRank) {
8314 // Moving the cluster to the left does not demote it.
8320 assert(NumRight < NumLeft);
8321 // Consider moving the last element on the left to the right side.
8322 CaseCluster &CC = *LastLeft;
8323 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8324 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8325 if (RightSideRank <= LeftSideRank) {
8326 // Moving the cluster to the right does not demot it.
8336 assert(LastLeft + 1 == FirstRight);
8337 assert(LastLeft >= W.FirstCluster);
8338 assert(FirstRight <= W.LastCluster);
8340 // Use the first element on the right as pivot since we will make less-than
8341 // comparisons against it.
8342 CaseClusterIt PivotCluster = FirstRight;
8343 assert(PivotCluster > W.FirstCluster);
8344 assert(PivotCluster <= W.LastCluster);
8346 CaseClusterIt FirstLeft = W.FirstCluster;
8347 CaseClusterIt LastRight = W.LastCluster;
8349 const ConstantInt *Pivot = PivotCluster->Low;
8351 // New blocks will be inserted immediately after the current one.
8352 MachineFunction::iterator BBI = W.MBB;
8355 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
8356 // we can branch to its destination directly if it's squeezed exactly in
8357 // between the known lower bound and Pivot - 1.
8358 MachineBasicBlock *LeftMBB;
8359 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
8360 FirstLeft->Low == W.GE &&
8361 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
8362 LeftMBB = FirstLeft->MBB;
8364 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8365 FuncInfo.MF->insert(BBI, LeftMBB);
8367 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultWeight / 2});
8368 // Put Cond in a virtual register to make it available from the new blocks.
8369 ExportFromCurrentBlock(Cond);
8372 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
8373 // single cluster, RHS.Low == Pivot, and we can branch to its destination
8374 // directly if RHS.High equals the current upper bound.
8375 MachineBasicBlock *RightMBB;
8376 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
8377 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
8378 RightMBB = FirstRight->MBB;
8380 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8381 FuncInfo.MF->insert(BBI, RightMBB);
8383 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultWeight / 2});
8384 // Put Cond in a virtual register to make it available from the new blocks.
8385 ExportFromCurrentBlock(Cond);
8388 // Create the CaseBlock record that will be used to lower the branch.
8389 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
8390 LeftWeight, RightWeight);
8392 if (W.MBB == SwitchMBB)
8393 visitSwitchCase(CB, SwitchMBB);
8395 SwitchCases.push_back(CB);
8398 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
8399 // Extract cases from the switch.
8400 BranchProbabilityInfo *BPI = FuncInfo.BPI;
8401 CaseClusterVector Clusters;
8402 Clusters.reserve(SI.getNumCases());
8403 for (auto I : SI.cases()) {
8404 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
8405 const ConstantInt *CaseVal = I.getCaseValue();
8407 BPI ? BPI->getEdgeWeight(SI.getParent(), I.getSuccessorIndex()) : 0;
8408 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Weight));
8411 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
8413 // Cluster adjacent cases with the same destination. We do this at all
8414 // optimization levels because it's cheap to do and will make codegen faster
8415 // if there are many clusters.
8416 sortAndRangeify(Clusters);
8418 if (TM.getOptLevel() != CodeGenOpt::None) {
8419 // Replace an unreachable default with the most popular destination.
8420 // FIXME: Exploit unreachable default more aggressively.
8421 bool UnreachableDefault =
8422 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
8423 if (UnreachableDefault && !Clusters.empty()) {
8424 DenseMap<const BasicBlock *, unsigned> Popularity;
8425 unsigned MaxPop = 0;
8426 const BasicBlock *MaxBB = nullptr;
8427 for (auto I : SI.cases()) {
8428 const BasicBlock *BB = I.getCaseSuccessor();
8429 if (++Popularity[BB] > MaxPop) {
8430 MaxPop = Popularity[BB];
8435 assert(MaxPop > 0 && MaxBB);
8436 DefaultMBB = FuncInfo.MBBMap[MaxBB];
8438 // Remove cases that were pointing to the destination that is now the
8440 CaseClusterVector New;
8441 New.reserve(Clusters.size());
8442 for (CaseCluster &CC : Clusters) {
8443 if (CC.MBB != DefaultMBB)
8446 Clusters = std::move(New);
8450 // If there is only the default destination, jump there directly.
8451 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
8452 if (Clusters.empty()) {
8453 SwitchMBB->addSuccessor(DefaultMBB);
8454 if (DefaultMBB != NextBlock(SwitchMBB)) {
8455 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
8456 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
8461 findJumpTables(Clusters, &SI, DefaultMBB);
8462 findBitTestClusters(Clusters, &SI);
8465 dbgs() << "Case clusters: ";
8466 for (const CaseCluster &C : Clusters) {
8467 if (C.Kind == CC_JumpTable) dbgs() << "JT:";
8468 if (C.Kind == CC_BitTests) dbgs() << "BT:";
8470 C.Low->getValue().print(dbgs(), true);
8471 if (C.Low != C.High) {
8473 C.High->getValue().print(dbgs(), true);
8480 assert(!Clusters.empty());
8481 SwitchWorkList WorkList;
8482 CaseClusterIt First = Clusters.begin();
8483 CaseClusterIt Last = Clusters.end() - 1;
8484 uint32_t DefaultWeight = getEdgeWeight(SwitchMBB, DefaultMBB);
8485 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultWeight});
8487 while (!WorkList.empty()) {
8488 SwitchWorkListItem W = WorkList.back();
8489 WorkList.pop_back();
8490 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
8492 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) {
8493 // For optimized builds, lower large range as a balanced binary tree.
8494 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
8498 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);