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/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GCMetadata.h"
28 #include "llvm/CodeGen/GCStrategy.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/StackMaps.h"
37 #include "llvm/CodeGen/WinEHFuncInfo.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DebugInfo.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/InlineAsm.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/IR/LLVMContext.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/IR/Statepoint.h"
52 #include "llvm/MC/MCSymbol.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetFrameLowering.h"
59 #include "llvm/Target/TargetInstrInfo.h"
60 #include "llvm/Target/TargetIntrinsicInfo.h"
61 #include "llvm/Target/TargetLowering.h"
62 #include "llvm/Target/TargetOptions.h"
63 #include "llvm/Target/TargetSelectionDAGInfo.h"
64 #include "llvm/Target/TargetSubtargetInfo.h"
68 #define DEBUG_TYPE "isel"
70 /// LimitFloatPrecision - Generate low-precision inline sequences for
71 /// some float libcalls (6, 8 or 12 bits).
72 static unsigned LimitFloatPrecision;
74 static cl::opt<unsigned, true>
75 LimitFPPrecision("limit-float-precision",
76 cl::desc("Generate low-precision inline sequences "
77 "for some float libcalls"),
78 cl::location(LimitFloatPrecision),
82 EnableFMFInDAG("enable-fmf-dag", cl::init(false), cl::Hidden,
83 cl::desc("Enable fast-math-flags for DAG nodes"));
85 // Limit the width of DAG chains. This is important in general to prevent
86 // DAG-based analysis from blowing up. For example, alias analysis and
87 // load clustering may not complete in reasonable time. It is difficult to
88 // recognize and avoid this situation within each individual analysis, and
89 // future analyses are likely to have the same behavior. Limiting DAG width is
90 // the safe approach and will be especially important with global DAGs.
92 // MaxParallelChains default is arbitrarily high to avoid affecting
93 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
94 // sequence over this should have been converted to llvm.memcpy by the
95 // frontend. It easy to induce this behavior with .ll code such as:
96 // %buffer = alloca [4096 x i8]
97 // %data = load [4096 x i8]* %argPtr
98 // store [4096 x i8] %data, [4096 x i8]* %buffer
99 static const unsigned MaxParallelChains = 64;
101 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
102 const SDValue *Parts, unsigned NumParts,
103 MVT PartVT, EVT ValueVT, const Value *V);
105 /// getCopyFromParts - Create a value that contains the specified legal parts
106 /// combined into the value they represent. If the parts combine to a type
107 /// larger then ValueVT then AssertOp can be used to specify whether the extra
108 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
109 /// (ISD::AssertSext).
110 static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
111 const SDValue *Parts,
112 unsigned NumParts, MVT PartVT, EVT ValueVT,
114 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
115 if (ValueVT.isVector())
116 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
119 assert(NumParts > 0 && "No parts to assemble!");
120 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
121 SDValue Val = Parts[0];
124 // Assemble the value from multiple parts.
125 if (ValueVT.isInteger()) {
126 unsigned PartBits = PartVT.getSizeInBits();
127 unsigned ValueBits = ValueVT.getSizeInBits();
129 // Assemble the power of 2 part.
130 unsigned RoundParts = NumParts & (NumParts - 1) ?
131 1 << Log2_32(NumParts) : NumParts;
132 unsigned RoundBits = PartBits * RoundParts;
133 EVT RoundVT = RoundBits == ValueBits ?
134 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
137 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
139 if (RoundParts > 2) {
140 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
142 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
143 RoundParts / 2, PartVT, HalfVT, V);
145 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
146 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
149 if (DAG.getDataLayout().isBigEndian())
152 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
154 if (RoundParts < NumParts) {
155 // Assemble the trailing non-power-of-2 part.
156 unsigned OddParts = NumParts - RoundParts;
157 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
158 Hi = getCopyFromParts(DAG, DL,
159 Parts + RoundParts, OddParts, PartVT, OddVT, V);
161 // Combine the round and odd parts.
163 if (DAG.getDataLayout().isBigEndian())
165 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
166 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
167 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
168 DAG.getConstant(Lo.getValueType().getSizeInBits(), DL,
169 TLI.getPointerTy()));
170 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
171 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
173 } else if (PartVT.isFloatingPoint()) {
174 // FP split into multiple FP parts (for ppcf128)
175 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
178 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
179 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
180 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
182 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
184 // FP split into integer parts (soft fp)
185 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
186 !PartVT.isVector() && "Unexpected split");
187 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
188 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
192 // There is now one part, held in Val. Correct it to match ValueVT.
193 EVT PartEVT = Val.getValueType();
195 if (PartEVT == ValueVT)
198 if (PartEVT.isInteger() && ValueVT.isInteger()) {
199 if (ValueVT.bitsLT(PartEVT)) {
200 // For a truncate, see if we have any information to
201 // indicate whether the truncated bits will always be
202 // zero or sign-extension.
203 if (AssertOp != ISD::DELETED_NODE)
204 Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
205 DAG.getValueType(ValueVT));
206 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
208 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
211 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
212 // FP_ROUND's are always exact here.
213 if (ValueVT.bitsLT(Val.getValueType()))
214 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
215 DAG.getTargetConstant(1, DL, TLI.getPointerTy()));
217 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
220 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
221 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
223 llvm_unreachable("Unknown mismatch!");
226 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
227 const Twine &ErrMsg) {
228 const Instruction *I = dyn_cast_or_null<Instruction>(V);
230 return Ctx.emitError(ErrMsg);
232 const char *AsmError = ", possible invalid constraint for vector type";
233 if (const CallInst *CI = dyn_cast<CallInst>(I))
234 if (isa<InlineAsm>(CI->getCalledValue()))
235 return Ctx.emitError(I, ErrMsg + AsmError);
237 return Ctx.emitError(I, ErrMsg);
240 /// getCopyFromPartsVector - Create a value that contains the specified legal
241 /// parts combined into the value they represent. If the parts combine to a
242 /// type larger then ValueVT then AssertOp can be used to specify whether the
243 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
244 /// ValueVT (ISD::AssertSext).
245 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
246 const SDValue *Parts, unsigned NumParts,
247 MVT PartVT, EVT ValueVT, const Value *V) {
248 assert(ValueVT.isVector() && "Not a vector value");
249 assert(NumParts > 0 && "No parts to assemble!");
250 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
251 SDValue Val = Parts[0];
253 // Handle a multi-element vector.
257 unsigned NumIntermediates;
259 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
260 NumIntermediates, RegisterVT);
261 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
262 NumParts = NumRegs; // Silence a compiler warning.
263 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
264 assert(RegisterVT.getSizeInBits() ==
265 Parts[0].getSimpleValueType().getSizeInBits() &&
266 "Part type sizes don't match!");
268 // Assemble the parts into intermediate operands.
269 SmallVector<SDValue, 8> Ops(NumIntermediates);
270 if (NumIntermediates == NumParts) {
271 // If the register was not expanded, truncate or copy the value,
273 for (unsigned i = 0; i != NumParts; ++i)
274 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
275 PartVT, IntermediateVT, V);
276 } else if (NumParts > 0) {
277 // If the intermediate type was expanded, build the intermediate
278 // operands from the parts.
279 assert(NumParts % NumIntermediates == 0 &&
280 "Must expand into a divisible number of parts!");
281 unsigned Factor = NumParts / NumIntermediates;
282 for (unsigned i = 0; i != NumIntermediates; ++i)
283 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
284 PartVT, IntermediateVT, V);
287 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
288 // intermediate operands.
289 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
294 // There is now one part, held in Val. Correct it to match ValueVT.
295 EVT PartEVT = Val.getValueType();
297 if (PartEVT == ValueVT)
300 if (PartEVT.isVector()) {
301 // If the element type of the source/dest vectors are the same, but the
302 // parts vector has more elements than the value vector, then we have a
303 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
305 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
306 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
307 "Cannot narrow, it would be a lossy transformation");
308 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
309 DAG.getConstant(0, DL, TLI.getVectorIdxTy()));
312 // Vector/Vector bitcast.
313 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
314 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
316 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
317 "Cannot handle this kind of promotion");
318 // Promoted vector extract
319 bool Smaller = ValueVT.bitsLE(PartEVT);
320 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
325 // Trivial bitcast if the types are the same size and the destination
326 // vector type is legal.
327 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
328 TLI.isTypeLegal(ValueVT))
329 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
331 // Handle cases such as i8 -> <1 x i1>
332 if (ValueVT.getVectorNumElements() != 1) {
333 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
334 "non-trivial scalar-to-vector conversion");
335 return DAG.getUNDEF(ValueVT);
338 if (ValueVT.getVectorNumElements() == 1 &&
339 ValueVT.getVectorElementType() != PartEVT) {
340 bool Smaller = ValueVT.bitsLE(PartEVT);
341 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
342 DL, ValueVT.getScalarType(), Val);
345 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
348 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
349 SDValue Val, SDValue *Parts, unsigned NumParts,
350 MVT PartVT, const Value *V);
352 /// getCopyToParts - Create a series of nodes that contain the specified value
353 /// split into legal parts. If the parts contain more bits than Val, then, for
354 /// integers, ExtendKind can be used to specify how to generate the extra bits.
355 static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
356 SDValue Val, SDValue *Parts, unsigned NumParts,
357 MVT PartVT, const Value *V,
358 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
359 EVT ValueVT = Val.getValueType();
361 // Handle the vector case separately.
362 if (ValueVT.isVector())
363 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
365 unsigned PartBits = PartVT.getSizeInBits();
366 unsigned OrigNumParts = NumParts;
367 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
368 "Copying to an illegal type!");
373 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
374 EVT PartEVT = PartVT;
375 if (PartEVT == ValueVT) {
376 assert(NumParts == 1 && "No-op copy with multiple parts!");
381 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
382 // If the parts cover more bits than the value has, promote the value.
383 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
384 assert(NumParts == 1 && "Do not know what to promote to!");
385 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
387 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
388 ValueVT.isInteger() &&
389 "Unknown mismatch!");
390 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
391 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
392 if (PartVT == MVT::x86mmx)
393 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
395 } else if (PartBits == ValueVT.getSizeInBits()) {
396 // Different types of the same size.
397 assert(NumParts == 1 && PartEVT != ValueVT);
398 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
399 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
400 // If the parts cover less bits than value has, truncate the value.
401 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
402 ValueVT.isInteger() &&
403 "Unknown mismatch!");
404 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
405 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
406 if (PartVT == MVT::x86mmx)
407 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
410 // The value may have changed - recompute ValueVT.
411 ValueVT = Val.getValueType();
412 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
413 "Failed to tile the value with PartVT!");
416 if (PartEVT != ValueVT)
417 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
418 "scalar-to-vector conversion failed");
424 // Expand the value into multiple parts.
425 if (NumParts & (NumParts - 1)) {
426 // The number of parts is not a power of 2. Split off and copy the tail.
427 assert(PartVT.isInteger() && ValueVT.isInteger() &&
428 "Do not know what to expand to!");
429 unsigned RoundParts = 1 << Log2_32(NumParts);
430 unsigned RoundBits = RoundParts * PartBits;
431 unsigned OddParts = NumParts - RoundParts;
432 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
433 DAG.getIntPtrConstant(RoundBits, DL));
434 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
436 if (DAG.getDataLayout().isBigEndian())
437 // The odd parts were reversed by getCopyToParts - unreverse them.
438 std::reverse(Parts + RoundParts, Parts + NumParts);
440 NumParts = RoundParts;
441 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
442 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
445 // The number of parts is a power of 2. Repeatedly bisect the value using
447 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
448 EVT::getIntegerVT(*DAG.getContext(),
449 ValueVT.getSizeInBits()),
452 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
453 for (unsigned i = 0; i < NumParts; i += StepSize) {
454 unsigned ThisBits = StepSize * PartBits / 2;
455 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
456 SDValue &Part0 = Parts[i];
457 SDValue &Part1 = Parts[i+StepSize/2];
459 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
460 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
461 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
462 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
464 if (ThisBits == PartBits && ThisVT != PartVT) {
465 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
466 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
471 if (DAG.getDataLayout().isBigEndian())
472 std::reverse(Parts, Parts + OrigNumParts);
476 /// getCopyToPartsVector - Create a series of nodes that contain the specified
477 /// value split into legal parts.
478 static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
479 SDValue Val, SDValue *Parts, unsigned NumParts,
480 MVT PartVT, const Value *V) {
481 EVT ValueVT = Val.getValueType();
482 assert(ValueVT.isVector() && "Not a vector");
483 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
486 EVT PartEVT = PartVT;
487 if (PartEVT == ValueVT) {
489 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
490 // Bitconvert vector->vector case.
491 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
492 } else if (PartVT.isVector() &&
493 PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
494 PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
495 EVT ElementVT = PartVT.getVectorElementType();
496 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
498 SmallVector<SDValue, 16> Ops;
499 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
500 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
501 ElementVT, Val, DAG.getConstant(i, DL,
502 TLI.getVectorIdxTy())));
504 for (unsigned i = ValueVT.getVectorNumElements(),
505 e = PartVT.getVectorNumElements(); i != e; ++i)
506 Ops.push_back(DAG.getUNDEF(ElementVT));
508 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, Ops);
510 // FIXME: Use CONCAT for 2x -> 4x.
512 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
513 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
514 } else if (PartVT.isVector() &&
515 PartEVT.getVectorElementType().bitsGE(
516 ValueVT.getVectorElementType()) &&
517 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
519 // Promoted vector extract
520 bool Smaller = PartEVT.bitsLE(ValueVT);
521 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
524 // Vector -> scalar conversion.
525 assert(ValueVT.getVectorNumElements() == 1 &&
526 "Only trivial vector-to-scalar conversions should get here!");
527 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
529 DAG.getConstant(0, DL, TLI.getVectorIdxTy()));
531 bool Smaller = ValueVT.bitsLE(PartVT);
532 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
540 // Handle a multi-element vector.
543 unsigned NumIntermediates;
544 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
546 NumIntermediates, RegisterVT);
547 unsigned NumElements = ValueVT.getVectorNumElements();
549 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
550 NumParts = NumRegs; // Silence a compiler warning.
551 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
553 // Split the vector into intermediate operands.
554 SmallVector<SDValue, 8> Ops(NumIntermediates);
555 for (unsigned i = 0; i != NumIntermediates; ++i) {
556 if (IntermediateVT.isVector())
557 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
559 DAG.getConstant(i * (NumElements / NumIntermediates), DL,
560 TLI.getVectorIdxTy()));
562 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
564 DAG.getConstant(i, DL, TLI.getVectorIdxTy()));
567 // Split the intermediate operands into legal parts.
568 if (NumParts == NumIntermediates) {
569 // If the register was not expanded, promote or copy the value,
571 for (unsigned i = 0; i != NumParts; ++i)
572 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
573 } else if (NumParts > 0) {
574 // If the intermediate type was expanded, split each the value into
576 assert(NumIntermediates != 0 && "division by zero");
577 assert(NumParts % NumIntermediates == 0 &&
578 "Must expand into a divisible number of parts!");
579 unsigned Factor = NumParts / NumIntermediates;
580 for (unsigned i = 0; i != NumIntermediates; ++i)
581 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
585 RegsForValue::RegsForValue() {}
587 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt,
589 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
591 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
592 const DataLayout &DL, unsigned Reg, Type *Ty) {
593 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
595 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
596 EVT ValueVT = ValueVTs[Value];
597 unsigned NumRegs = TLI.getNumRegisters(Context, ValueVT);
598 MVT RegisterVT = TLI.getRegisterType(Context, ValueVT);
599 for (unsigned i = 0; i != NumRegs; ++i)
600 Regs.push_back(Reg + i);
601 RegVTs.push_back(RegisterVT);
606 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
607 /// this value and returns the result as a ValueVT value. This uses
608 /// Chain/Flag as the input and updates them for the output Chain/Flag.
609 /// If the Flag pointer is NULL, no flag is used.
610 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
611 FunctionLoweringInfo &FuncInfo,
613 SDValue &Chain, SDValue *Flag,
614 const Value *V) const {
615 // A Value with type {} or [0 x %t] needs no registers.
616 if (ValueVTs.empty())
619 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
621 // Assemble the legal parts into the final values.
622 SmallVector<SDValue, 4> Values(ValueVTs.size());
623 SmallVector<SDValue, 8> Parts;
624 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
625 // Copy the legal parts from the registers.
626 EVT ValueVT = ValueVTs[Value];
627 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
628 MVT RegisterVT = RegVTs[Value];
630 Parts.resize(NumRegs);
631 for (unsigned i = 0; i != NumRegs; ++i) {
634 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
636 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
637 *Flag = P.getValue(2);
640 Chain = P.getValue(1);
643 // If the source register was virtual and if we know something about it,
644 // add an assert node.
645 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
646 !RegisterVT.isInteger() || RegisterVT.isVector())
649 const FunctionLoweringInfo::LiveOutInfo *LOI =
650 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
654 unsigned RegSize = RegisterVT.getSizeInBits();
655 unsigned NumSignBits = LOI->NumSignBits;
656 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
658 if (NumZeroBits == RegSize) {
659 // The current value is a zero.
660 // Explicitly express that as it would be easier for
661 // optimizations to kick in.
662 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
666 // FIXME: We capture more information than the dag can represent. For
667 // now, just use the tightest assertzext/assertsext possible.
669 EVT FromVT(MVT::Other);
670 if (NumSignBits == RegSize)
671 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
672 else if (NumZeroBits >= RegSize-1)
673 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
674 else if (NumSignBits > RegSize-8)
675 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
676 else if (NumZeroBits >= RegSize-8)
677 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
678 else if (NumSignBits > RegSize-16)
679 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
680 else if (NumZeroBits >= RegSize-16)
681 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
682 else if (NumSignBits > RegSize-32)
683 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
684 else if (NumZeroBits >= RegSize-32)
685 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
689 // Add an assertion node.
690 assert(FromVT != MVT::Other);
691 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
692 RegisterVT, P, DAG.getValueType(FromVT));
695 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
696 NumRegs, RegisterVT, ValueVT, V);
701 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
704 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
705 /// specified value into the registers specified by this object. This uses
706 /// Chain/Flag as the input and updates them for the output Chain/Flag.
707 /// If the Flag pointer is NULL, no flag is used.
708 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
709 SDValue &Chain, SDValue *Flag, const Value *V,
710 ISD::NodeType PreferredExtendType) const {
711 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
712 ISD::NodeType ExtendKind = PreferredExtendType;
714 // Get the list of the values's legal parts.
715 unsigned NumRegs = Regs.size();
716 SmallVector<SDValue, 8> Parts(NumRegs);
717 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
718 EVT ValueVT = ValueVTs[Value];
719 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
720 MVT RegisterVT = RegVTs[Value];
722 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
723 ExtendKind = ISD::ZERO_EXTEND;
725 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
726 &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
730 // Copy the parts into the registers.
731 SmallVector<SDValue, 8> Chains(NumRegs);
732 for (unsigned i = 0; i != NumRegs; ++i) {
735 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
737 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
738 *Flag = Part.getValue(1);
741 Chains[i] = Part.getValue(0);
744 if (NumRegs == 1 || Flag)
745 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
746 // flagged to it. That is the CopyToReg nodes and the user are considered
747 // a single scheduling unit. If we create a TokenFactor and return it as
748 // chain, then the TokenFactor is both a predecessor (operand) of the
749 // user as well as a successor (the TF operands are flagged to the user).
750 // c1, f1 = CopyToReg
751 // c2, f2 = CopyToReg
752 // c3 = TokenFactor c1, c2
755 Chain = Chains[NumRegs-1];
757 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
760 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
761 /// operand list. This adds the code marker and includes the number of
762 /// values added into it.
763 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
764 unsigned MatchingIdx, SDLoc dl,
766 std::vector<SDValue> &Ops) const {
767 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
769 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
771 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
772 else if (!Regs.empty() &&
773 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
774 // Put the register class of the virtual registers in the flag word. That
775 // way, later passes can recompute register class constraints for inline
776 // assembly as well as normal instructions.
777 // Don't do this for tied operands that can use the regclass information
779 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
780 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
781 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
784 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
787 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
788 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
789 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
790 MVT RegisterVT = RegVTs[Value];
791 for (unsigned i = 0; i != NumRegs; ++i) {
792 assert(Reg < Regs.size() && "Mismatch in # registers expected");
793 unsigned TheReg = Regs[Reg++];
794 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
796 if (TheReg == SP && Code == InlineAsm::Kind_Clobber) {
797 // If we clobbered the stack pointer, MFI should know about it.
798 assert(DAG.getMachineFunction().getFrameInfo()->
799 hasOpaqueSPAdjustment());
805 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
806 const TargetLibraryInfo *li) {
810 DL = &DAG.getDataLayout();
811 Context = DAG.getContext();
812 LPadToCallSiteMap.clear();
815 /// clear - Clear out the current SelectionDAG and the associated
816 /// state and prepare this SelectionDAGBuilder object to be used
817 /// for a new block. This doesn't clear out information about
818 /// additional blocks that are needed to complete switch lowering
819 /// or PHI node updating; that information is cleared out as it is
821 void SelectionDAGBuilder::clear() {
823 UnusedArgNodeMap.clear();
824 PendingLoads.clear();
825 PendingExports.clear();
828 SDNodeOrder = LowestSDNodeOrder;
829 StatepointLowering.clear();
832 /// clearDanglingDebugInfo - Clear the dangling debug information
833 /// map. This function is separated from the clear so that debug
834 /// information that is dangling in a basic block can be properly
835 /// resolved in a different basic block. This allows the
836 /// SelectionDAG to resolve dangling debug information attached
838 void SelectionDAGBuilder::clearDanglingDebugInfo() {
839 DanglingDebugInfoMap.clear();
842 /// getRoot - Return the current virtual root of the Selection DAG,
843 /// flushing any PendingLoad items. This must be done before emitting
844 /// a store or any other node that may need to be ordered after any
845 /// prior load instructions.
847 SDValue SelectionDAGBuilder::getRoot() {
848 if (PendingLoads.empty())
849 return DAG.getRoot();
851 if (PendingLoads.size() == 1) {
852 SDValue Root = PendingLoads[0];
854 PendingLoads.clear();
858 // Otherwise, we have to make a token factor node.
859 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
861 PendingLoads.clear();
866 /// getControlRoot - Similar to getRoot, but instead of flushing all the
867 /// PendingLoad items, flush all the PendingExports items. It is necessary
868 /// to do this before emitting a terminator instruction.
870 SDValue SelectionDAGBuilder::getControlRoot() {
871 SDValue Root = DAG.getRoot();
873 if (PendingExports.empty())
876 // Turn all of the CopyToReg chains into one factored node.
877 if (Root.getOpcode() != ISD::EntryToken) {
878 unsigned i = 0, e = PendingExports.size();
879 for (; i != e; ++i) {
880 assert(PendingExports[i].getNode()->getNumOperands() > 1);
881 if (PendingExports[i].getNode()->getOperand(0) == Root)
882 break; // Don't add the root if we already indirectly depend on it.
886 PendingExports.push_back(Root);
889 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
891 PendingExports.clear();
896 void SelectionDAGBuilder::visit(const Instruction &I) {
897 // Set up outgoing PHI node register values before emitting the terminator.
898 if (isa<TerminatorInst>(&I))
899 HandlePHINodesInSuccessorBlocks(I.getParent());
905 visit(I.getOpcode(), I);
907 if (!isa<TerminatorInst>(&I) && !HasTailCall)
908 CopyToExportRegsIfNeeded(&I);
913 void SelectionDAGBuilder::visitPHI(const PHINode &) {
914 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
917 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
918 // Note: this doesn't use InstVisitor, because it has to work with
919 // ConstantExpr's in addition to instructions.
921 default: llvm_unreachable("Unknown instruction type encountered!");
922 // Build the switch statement using the Instruction.def file.
923 #define HANDLE_INST(NUM, OPCODE, CLASS) \
924 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
925 #include "llvm/IR/Instruction.def"
929 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
930 // generate the debug data structures now that we've seen its definition.
931 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
933 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
935 const DbgValueInst *DI = DDI.getDI();
936 DebugLoc dl = DDI.getdl();
937 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
938 DILocalVariable *Variable = DI->getVariable();
939 DIExpression *Expr = DI->getExpression();
940 assert(Variable->isValidLocationForIntrinsic(dl) &&
941 "Expected inlined-at fields to agree");
942 uint64_t Offset = DI->getOffset();
943 // A dbg.value for an alloca is always indirect.
944 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
947 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, Offset, IsIndirect,
949 SDV = DAG.getDbgValue(Variable, Expr, Val.getNode(), Val.getResNo(),
950 IsIndirect, Offset, dl, DbgSDNodeOrder);
951 DAG.AddDbgValue(SDV, Val.getNode(), false);
954 DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
955 DanglingDebugInfoMap[V] = DanglingDebugInfo();
959 /// getCopyFromRegs - If there was virtual register allocated for the value V
960 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
961 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
962 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
965 if (It != FuncInfo.ValueMap.end()) {
966 unsigned InReg = It->second;
967 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
968 DAG.getDataLayout(), InReg, Ty);
969 SDValue Chain = DAG.getEntryNode();
970 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
971 resolveDanglingDebugInfo(V, Result);
977 /// getValue - Return an SDValue for the given Value.
978 SDValue SelectionDAGBuilder::getValue(const Value *V) {
979 // If we already have an SDValue for this value, use it. It's important
980 // to do this first, so that we don't create a CopyFromReg if we already
981 // have a regular SDValue.
982 SDValue &N = NodeMap[V];
983 if (N.getNode()) return N;
985 // If there's a virtual register allocated and initialized for this
987 SDValue copyFromReg = getCopyFromRegs(V, V->getType());
988 if (copyFromReg.getNode()) {
992 // Otherwise create a new SDValue and remember it.
993 SDValue Val = getValueImpl(V);
995 resolveDanglingDebugInfo(V, Val);
999 // Return true if SDValue exists for the given Value
1000 bool SelectionDAGBuilder::findValue(const Value *V) const {
1001 return (NodeMap.find(V) != NodeMap.end()) ||
1002 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1005 /// getNonRegisterValue - Return an SDValue for the given Value, but
1006 /// don't look in FuncInfo.ValueMap for a virtual register.
1007 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1008 // If we already have an SDValue for this value, use it.
1009 SDValue &N = NodeMap[V];
1011 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1012 // Remove the debug location from the node as the node is about to be used
1013 // in a location which may differ from the original debug location. This
1014 // is relevant to Constant and ConstantFP nodes because they can appear
1015 // as constant expressions inside PHI nodes.
1016 N->setDebugLoc(DebugLoc());
1021 // Otherwise create a new SDValue and remember it.
1022 SDValue Val = getValueImpl(V);
1024 resolveDanglingDebugInfo(V, Val);
1028 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1029 /// Create an SDValue for the given value.
1030 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1031 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1033 if (const Constant *C = dyn_cast<Constant>(V)) {
1034 EVT VT = TLI.getValueType(V->getType(), true);
1036 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1037 return DAG.getConstant(*CI, getCurSDLoc(), VT);
1039 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1040 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1042 if (isa<ConstantPointerNull>(C)) {
1043 unsigned AS = V->getType()->getPointerAddressSpace();
1044 return DAG.getConstant(0, getCurSDLoc(), TLI.getPointerTy(AS));
1047 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1048 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1050 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1051 return DAG.getUNDEF(VT);
1053 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1054 visit(CE->getOpcode(), *CE);
1055 SDValue N1 = NodeMap[V];
1056 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1060 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1061 SmallVector<SDValue, 4> Constants;
1062 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1064 SDNode *Val = getValue(*OI).getNode();
1065 // If the operand is an empty aggregate, there are no values.
1067 // Add each leaf value from the operand to the Constants list
1068 // to form a flattened list of all the values.
1069 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1070 Constants.push_back(SDValue(Val, i));
1073 return DAG.getMergeValues(Constants, getCurSDLoc());
1076 if (const ConstantDataSequential *CDS =
1077 dyn_cast<ConstantDataSequential>(C)) {
1078 SmallVector<SDValue, 4> Ops;
1079 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1080 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1081 // Add each leaf value from the operand to the Constants list
1082 // to form a flattened list of all the values.
1083 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1084 Ops.push_back(SDValue(Val, i));
1087 if (isa<ArrayType>(CDS->getType()))
1088 return DAG.getMergeValues(Ops, getCurSDLoc());
1089 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
1093 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1094 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1095 "Unknown struct or array constant!");
1097 SmallVector<EVT, 4> ValueVTs;
1098 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1099 unsigned NumElts = ValueVTs.size();
1101 return SDValue(); // empty struct
1102 SmallVector<SDValue, 4> Constants(NumElts);
1103 for (unsigned i = 0; i != NumElts; ++i) {
1104 EVT EltVT = ValueVTs[i];
1105 if (isa<UndefValue>(C))
1106 Constants[i] = DAG.getUNDEF(EltVT);
1107 else if (EltVT.isFloatingPoint())
1108 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1110 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1113 return DAG.getMergeValues(Constants, getCurSDLoc());
1116 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1117 return DAG.getBlockAddress(BA, VT);
1119 VectorType *VecTy = cast<VectorType>(V->getType());
1120 unsigned NumElements = VecTy->getNumElements();
1122 // Now that we know the number and type of the elements, get that number of
1123 // elements into the Ops array based on what kind of constant it is.
1124 SmallVector<SDValue, 16> Ops;
1125 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1126 for (unsigned i = 0; i != NumElements; ++i)
1127 Ops.push_back(getValue(CV->getOperand(i)));
1129 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1130 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1133 if (EltVT.isFloatingPoint())
1134 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1136 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1137 Ops.assign(NumElements, Op);
1140 // Create a BUILD_VECTOR node.
1141 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(), VT, Ops);
1144 // If this is a static alloca, generate it as the frameindex instead of
1146 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1147 DenseMap<const AllocaInst*, int>::iterator SI =
1148 FuncInfo.StaticAllocaMap.find(AI);
1149 if (SI != FuncInfo.StaticAllocaMap.end())
1150 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1153 // If this is an instruction which fast-isel has deferred, select it now.
1154 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1155 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1156 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1158 SDValue Chain = DAG.getEntryNode();
1159 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1162 llvm_unreachable("Can't get register for value!");
1165 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1166 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1167 auto &DL = DAG.getDataLayout();
1168 SDValue Chain = getControlRoot();
1169 SmallVector<ISD::OutputArg, 8> Outs;
1170 SmallVector<SDValue, 8> OutVals;
1172 if (!FuncInfo.CanLowerReturn) {
1173 unsigned DemoteReg = FuncInfo.DemoteRegister;
1174 const Function *F = I.getParent()->getParent();
1176 // Emit a store of the return value through the virtual register.
1177 // Leave Outs empty so that LowerReturn won't try to load return
1178 // registers the usual way.
1179 SmallVector<EVT, 1> PtrValueVTs;
1180 ComputeValueVTs(TLI, DL, PointerType::getUnqual(F->getReturnType()),
1183 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1184 SDValue RetOp = getValue(I.getOperand(0));
1186 SmallVector<EVT, 4> ValueVTs;
1187 SmallVector<uint64_t, 4> Offsets;
1188 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1189 unsigned NumValues = ValueVTs.size();
1191 SmallVector<SDValue, 4> Chains(NumValues);
1192 for (unsigned i = 0; i != NumValues; ++i) {
1193 SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
1194 RetPtr.getValueType(), RetPtr,
1195 DAG.getIntPtrConstant(Offsets[i],
1198 DAG.getStore(Chain, getCurSDLoc(),
1199 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1200 // FIXME: better loc info would be nice.
1201 Add, MachinePointerInfo(), false, false, 0);
1204 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1205 MVT::Other, Chains);
1206 } else if (I.getNumOperands() != 0) {
1207 SmallVector<EVT, 4> ValueVTs;
1208 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1209 unsigned NumValues = ValueVTs.size();
1211 SDValue RetOp = getValue(I.getOperand(0));
1213 const Function *F = I.getParent()->getParent();
1215 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1216 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1218 ExtendKind = ISD::SIGN_EXTEND;
1219 else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1221 ExtendKind = ISD::ZERO_EXTEND;
1223 LLVMContext &Context = F->getContext();
1224 bool RetInReg = F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
1227 for (unsigned j = 0; j != NumValues; ++j) {
1228 EVT VT = ValueVTs[j];
1230 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1231 VT = TLI.getTypeForExtArgOrReturn(Context, VT, ExtendKind);
1233 unsigned NumParts = TLI.getNumRegisters(Context, VT);
1234 MVT PartVT = TLI.getRegisterType(Context, VT);
1235 SmallVector<SDValue, 4> Parts(NumParts);
1236 getCopyToParts(DAG, getCurSDLoc(),
1237 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1238 &Parts[0], NumParts, PartVT, &I, ExtendKind);
1240 // 'inreg' on function refers to return value
1241 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1245 // Propagate extension type if any
1246 if (ExtendKind == ISD::SIGN_EXTEND)
1248 else if (ExtendKind == ISD::ZERO_EXTEND)
1251 for (unsigned i = 0; i < NumParts; ++i) {
1252 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1253 VT, /*isfixed=*/true, 0, 0));
1254 OutVals.push_back(Parts[i]);
1260 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1261 CallingConv::ID CallConv =
1262 DAG.getMachineFunction().getFunction()->getCallingConv();
1263 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1264 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1266 // Verify that the target's LowerReturn behaved as expected.
1267 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1268 "LowerReturn didn't return a valid chain!");
1270 // Update the DAG with the new chain value resulting from return lowering.
1274 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1275 /// created for it, emit nodes to copy the value into the virtual
1277 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1279 if (V->getType()->isEmptyTy())
1282 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1283 if (VMI != FuncInfo.ValueMap.end()) {
1284 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1285 CopyValueToVirtualRegister(V, VMI->second);
1289 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1290 /// the current basic block, add it to ValueMap now so that we'll get a
1292 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1293 // No need to export constants.
1294 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1296 // Already exported?
1297 if (FuncInfo.isExportedInst(V)) return;
1299 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1300 CopyValueToVirtualRegister(V, Reg);
1303 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1304 const BasicBlock *FromBB) {
1305 // The operands of the setcc have to be in this block. We don't know
1306 // how to export them from some other block.
1307 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1308 // Can export from current BB.
1309 if (VI->getParent() == FromBB)
1312 // Is already exported, noop.
1313 return FuncInfo.isExportedInst(V);
1316 // If this is an argument, we can export it if the BB is the entry block or
1317 // if it is already exported.
1318 if (isa<Argument>(V)) {
1319 if (FromBB == &FromBB->getParent()->getEntryBlock())
1322 // Otherwise, can only export this if it is already exported.
1323 return FuncInfo.isExportedInst(V);
1326 // Otherwise, constants can always be exported.
1330 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1331 uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1332 const MachineBasicBlock *Dst) const {
1333 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1336 const BasicBlock *SrcBB = Src->getBasicBlock();
1337 const BasicBlock *DstBB = Dst->getBasicBlock();
1338 return BPI->getEdgeWeight(SrcBB, DstBB);
1341 void SelectionDAGBuilder::
1342 addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1343 uint32_t Weight /* = 0 */) {
1345 Weight = getEdgeWeight(Src, Dst);
1346 Src->addSuccessor(Dst, Weight);
1350 static bool InBlock(const Value *V, const BasicBlock *BB) {
1351 if (const Instruction *I = dyn_cast<Instruction>(V))
1352 return I->getParent() == BB;
1356 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1357 /// This function emits a branch and is used at the leaves of an OR or an
1358 /// AND operator tree.
1361 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1362 MachineBasicBlock *TBB,
1363 MachineBasicBlock *FBB,
1364 MachineBasicBlock *CurBB,
1365 MachineBasicBlock *SwitchBB,
1368 const BasicBlock *BB = CurBB->getBasicBlock();
1370 // If the leaf of the tree is a comparison, merge the condition into
1372 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1373 // The operands of the cmp have to be in this block. We don't know
1374 // how to export them from some other block. If this is the first block
1375 // of the sequence, no exporting is needed.
1376 if (CurBB == SwitchBB ||
1377 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1378 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1379 ISD::CondCode Condition;
1380 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1381 Condition = getICmpCondCode(IC->getPredicate());
1382 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1383 Condition = getFCmpCondCode(FC->getPredicate());
1384 if (TM.Options.NoNaNsFPMath)
1385 Condition = getFCmpCodeWithoutNaN(Condition);
1387 (void)Condition; // silence warning.
1388 llvm_unreachable("Unknown compare instruction");
1391 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1392 TBB, FBB, CurBB, TWeight, FWeight);
1393 SwitchCases.push_back(CB);
1398 // Create a CaseBlock record representing this branch.
1399 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1400 nullptr, TBB, FBB, CurBB, TWeight, FWeight);
1401 SwitchCases.push_back(CB);
1404 /// Scale down both weights to fit into uint32_t.
1405 static void ScaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
1406 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
1407 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
1408 NewTrue = NewTrue / Scale;
1409 NewFalse = NewFalse / Scale;
1412 /// FindMergedConditions - If Cond is an expression like
1413 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1414 MachineBasicBlock *TBB,
1415 MachineBasicBlock *FBB,
1416 MachineBasicBlock *CurBB,
1417 MachineBasicBlock *SwitchBB,
1418 unsigned Opc, uint32_t TWeight,
1420 // If this node is not part of the or/and tree, emit it as a branch.
1421 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1422 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1423 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1424 BOp->getParent() != CurBB->getBasicBlock() ||
1425 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1426 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1427 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1432 // Create TmpBB after CurBB.
1433 MachineFunction::iterator BBI = CurBB;
1434 MachineFunction &MF = DAG.getMachineFunction();
1435 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1436 CurBB->getParent()->insert(++BBI, TmpBB);
1438 if (Opc == Instruction::Or) {
1439 // Codegen X | Y as:
1448 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1449 // The requirement is that
1450 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1451 // = TrueProb for original BB.
1452 // Assuming the original weights are A and B, one choice is to set BB1's
1453 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
1455 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1456 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1457 // TmpBB, but the math is more complicated.
1459 uint64_t NewTrueWeight = TWeight;
1460 uint64_t NewFalseWeight = (uint64_t)TWeight + 2 * (uint64_t)FWeight;
1461 ScaleWeights(NewTrueWeight, NewFalseWeight);
1462 // Emit the LHS condition.
1463 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1464 NewTrueWeight, NewFalseWeight);
1466 NewTrueWeight = TWeight;
1467 NewFalseWeight = 2 * (uint64_t)FWeight;
1468 ScaleWeights(NewTrueWeight, NewFalseWeight);
1469 // Emit the RHS condition into TmpBB.
1470 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1471 NewTrueWeight, NewFalseWeight);
1473 assert(Opc == Instruction::And && "Unknown merge op!");
1474 // Codegen X & Y as:
1482 // This requires creation of TmpBB after CurBB.
1484 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1485 // The requirement is that
1486 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1487 // = FalseProb for original BB.
1488 // Assuming the original weights are A and B, one choice is to set BB1's
1489 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
1491 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
1493 uint64_t NewTrueWeight = 2 * (uint64_t)TWeight + (uint64_t)FWeight;
1494 uint64_t NewFalseWeight = FWeight;
1495 ScaleWeights(NewTrueWeight, NewFalseWeight);
1496 // Emit the LHS condition.
1497 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1498 NewTrueWeight, NewFalseWeight);
1500 NewTrueWeight = 2 * (uint64_t)TWeight;
1501 NewFalseWeight = FWeight;
1502 ScaleWeights(NewTrueWeight, NewFalseWeight);
1503 // Emit the RHS condition into TmpBB.
1504 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1505 NewTrueWeight, NewFalseWeight);
1509 /// If the set of cases should be emitted as a series of branches, return true.
1510 /// If we should emit this as a bunch of and/or'd together conditions, return
1513 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1514 if (Cases.size() != 2) return true;
1516 // If this is two comparisons of the same values or'd or and'd together, they
1517 // will get folded into a single comparison, so don't emit two blocks.
1518 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1519 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1520 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1521 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1525 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1526 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1527 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1528 Cases[0].CC == Cases[1].CC &&
1529 isa<Constant>(Cases[0].CmpRHS) &&
1530 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1531 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1533 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1540 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1541 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1543 // Update machine-CFG edges.
1544 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1546 if (I.isUnconditional()) {
1547 // Update machine-CFG edges.
1548 BrMBB->addSuccessor(Succ0MBB);
1550 // If this is not a fall-through branch or optimizations are switched off,
1552 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1553 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1554 MVT::Other, getControlRoot(),
1555 DAG.getBasicBlock(Succ0MBB)));
1560 // If this condition is one of the special cases we handle, do special stuff
1562 const Value *CondVal = I.getCondition();
1563 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1565 // If this is a series of conditions that are or'd or and'd together, emit
1566 // this as a sequence of branches instead of setcc's with and/or operations.
1567 // As long as jumps are not expensive, this should improve performance.
1568 // For example, instead of something like:
1581 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1582 if (!DAG.getTargetLoweringInfo().isJumpExpensive() &&
1583 BOp->hasOneUse() && (BOp->getOpcode() == Instruction::And ||
1584 BOp->getOpcode() == Instruction::Or)) {
1585 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1586 BOp->getOpcode(), getEdgeWeight(BrMBB, Succ0MBB),
1587 getEdgeWeight(BrMBB, Succ1MBB));
1588 // If the compares in later blocks need to use values not currently
1589 // exported from this block, export them now. This block should always
1590 // be the first entry.
1591 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1593 // Allow some cases to be rejected.
1594 if (ShouldEmitAsBranches(SwitchCases)) {
1595 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1596 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1597 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1600 // Emit the branch for this block.
1601 visitSwitchCase(SwitchCases[0], BrMBB);
1602 SwitchCases.erase(SwitchCases.begin());
1606 // Okay, we decided not to do this, remove any inserted MBB's and clear
1608 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1609 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1611 SwitchCases.clear();
1615 // Create a CaseBlock record representing this branch.
1616 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1617 nullptr, Succ0MBB, Succ1MBB, BrMBB);
1619 // Use visitSwitchCase to actually insert the fast branch sequence for this
1621 visitSwitchCase(CB, BrMBB);
1624 /// visitSwitchCase - Emits the necessary code to represent a single node in
1625 /// the binary search tree resulting from lowering a switch instruction.
1626 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1627 MachineBasicBlock *SwitchBB) {
1629 SDValue CondLHS = getValue(CB.CmpLHS);
1630 SDLoc dl = getCurSDLoc();
1632 // Build the setcc now.
1634 // Fold "(X == true)" to X and "(X == false)" to !X to
1635 // handle common cases produced by branch lowering.
1636 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1637 CB.CC == ISD::SETEQ)
1639 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1640 CB.CC == ISD::SETEQ) {
1641 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
1642 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1644 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1646 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1648 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1649 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1651 SDValue CmpOp = getValue(CB.CmpMHS);
1652 EVT VT = CmpOp.getValueType();
1654 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1655 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
1658 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1659 VT, CmpOp, DAG.getConstant(Low, dl, VT));
1660 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1661 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
1665 // Update successor info
1666 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
1667 // TrueBB and FalseBB are always different unless the incoming IR is
1668 // degenerate. This only happens when running llc on weird IR.
1669 if (CB.TrueBB != CB.FalseBB)
1670 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
1672 // If the lhs block is the next block, invert the condition so that we can
1673 // fall through to the lhs instead of the rhs block.
1674 if (CB.TrueBB == NextBlock(SwitchBB)) {
1675 std::swap(CB.TrueBB, CB.FalseBB);
1676 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
1677 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1680 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1681 MVT::Other, getControlRoot(), Cond,
1682 DAG.getBasicBlock(CB.TrueBB));
1684 // Insert the false branch. Do this even if it's a fall through branch,
1685 // this makes it easier to do DAG optimizations which require inverting
1686 // the branch condition.
1687 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1688 DAG.getBasicBlock(CB.FalseBB));
1690 DAG.setRoot(BrCond);
1693 /// visitJumpTable - Emit JumpTable node in the current MBB
1694 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1695 // Emit the code for the jump table
1696 assert(JT.Reg != -1U && "Should lower JT Header first!");
1697 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy();
1698 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
1700 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1701 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
1702 MVT::Other, Index.getValue(1),
1704 DAG.setRoot(BrJumpTable);
1707 /// visitJumpTableHeader - This function emits necessary code to produce index
1708 /// in the JumpTable from switch case.
1709 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1710 JumpTableHeader &JTH,
1711 MachineBasicBlock *SwitchBB) {
1712 SDLoc dl = getCurSDLoc();
1714 // Subtract the lowest switch case value from the value being switched on and
1715 // conditional branch to default mbb if the result is greater than the
1716 // difference between smallest and largest cases.
1717 SDValue SwitchOp = getValue(JTH.SValue);
1718 EVT VT = SwitchOp.getValueType();
1719 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
1720 DAG.getConstant(JTH.First, dl, VT));
1722 // The SDNode we just created, which holds the value being switched on minus
1723 // the smallest case value, needs to be copied to a virtual register so it
1724 // can be used as an index into the jump table in a subsequent basic block.
1725 // This value may be smaller or larger than the target's pointer type, and
1726 // therefore require extension or truncating.
1727 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1728 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy());
1730 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1731 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
1732 JumpTableReg, SwitchOp);
1733 JT.Reg = JumpTableReg;
1735 // Emit the range check for the jump table, and branch to the default block
1736 // for the switch statement if the value being switched on exceeds the largest
1737 // case in the switch.
1739 DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(),
1740 Sub.getValueType()),
1741 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT),
1744 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1745 MVT::Other, CopyTo, CMP,
1746 DAG.getBasicBlock(JT.Default));
1748 // Avoid emitting unnecessary branches to the next block.
1749 if (JT.MBB != NextBlock(SwitchBB))
1750 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1751 DAG.getBasicBlock(JT.MBB));
1753 DAG.setRoot(BrCond);
1756 /// Codegen a new tail for a stack protector check ParentMBB which has had its
1757 /// tail spliced into a stack protector check success bb.
1759 /// For a high level explanation of how this fits into the stack protector
1760 /// generation see the comment on the declaration of class
1761 /// StackProtectorDescriptor.
1762 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
1763 MachineBasicBlock *ParentBB) {
1765 // First create the loads to the guard/stack slot for the comparison.
1766 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1767 EVT PtrTy = TLI.getPointerTy();
1769 MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
1770 int FI = MFI->getStackProtectorIndex();
1772 const Value *IRGuard = SPD.getGuard();
1773 SDValue GuardPtr = getValue(IRGuard);
1774 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
1776 unsigned Align = DL->getPrefTypeAlignment(IRGuard->getType());
1779 SDLoc dl = getCurSDLoc();
1781 // If GuardReg is set and useLoadStackGuardNode returns true, retrieve the
1782 // guard value from the virtual register holding the value. Otherwise, emit a
1783 // volatile load to retrieve the stack guard value.
1784 unsigned GuardReg = SPD.getGuardReg();
1786 if (GuardReg && TLI.useLoadStackGuardNode())
1787 Guard = DAG.getCopyFromReg(DAG.getEntryNode(), dl, GuardReg,
1790 Guard = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
1791 GuardPtr, MachinePointerInfo(IRGuard, 0),
1792 true, false, false, Align);
1794 SDValue StackSlot = DAG.getLoad(PtrTy, dl, DAG.getEntryNode(),
1796 MachinePointerInfo::getFixedStack(FI),
1797 true, false, false, Align);
1799 // Perform the comparison via a subtract/getsetcc.
1800 EVT VT = Guard.getValueType();
1801 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, StackSlot);
1804 DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(),
1805 Sub.getValueType()),
1806 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
1808 // If the sub is not 0, then we know the guard/stackslot do not equal, so
1809 // branch to failure MBB.
1810 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1811 MVT::Other, StackSlot.getOperand(0),
1812 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
1813 // Otherwise branch to success MBB.
1814 SDValue Br = DAG.getNode(ISD::BR, dl,
1816 DAG.getBasicBlock(SPD.getSuccessMBB()));
1821 /// Codegen the failure basic block for a stack protector check.
1823 /// A failure stack protector machine basic block consists simply of a call to
1824 /// __stack_chk_fail().
1826 /// For a high level explanation of how this fits into the stack protector
1827 /// generation see the comment on the declaration of class
1828 /// StackProtectorDescriptor.
1830 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
1831 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1833 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
1834 nullptr, 0, false, getCurSDLoc(), false, false).second;
1838 /// visitBitTestHeader - This function emits necessary code to produce value
1839 /// suitable for "bit tests"
1840 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1841 MachineBasicBlock *SwitchBB) {
1842 SDLoc dl = getCurSDLoc();
1844 // Subtract the minimum value
1845 SDValue SwitchOp = getValue(B.SValue);
1846 EVT VT = SwitchOp.getValueType();
1847 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
1848 DAG.getConstant(B.First, dl, VT));
1851 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1853 DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(),
1854 Sub.getValueType()),
1855 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
1857 // Determine the type of the test operands.
1858 bool UsePtrType = false;
1859 if (!TLI.isTypeLegal(VT))
1862 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1863 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
1864 // Switch table case range are encoded into series of masks.
1865 // Just use pointer type, it's guaranteed to fit.
1871 VT = TLI.getPointerTy();
1872 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
1875 B.RegVT = VT.getSimpleVT();
1876 B.Reg = FuncInfo.CreateReg(B.RegVT);
1877 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
1879 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1881 addSuccessorWithWeight(SwitchBB, B.Default);
1882 addSuccessorWithWeight(SwitchBB, MBB);
1884 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
1885 MVT::Other, CopyTo, RangeCmp,
1886 DAG.getBasicBlock(B.Default));
1888 // Avoid emitting unnecessary branches to the next block.
1889 if (MBB != NextBlock(SwitchBB))
1890 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
1891 DAG.getBasicBlock(MBB));
1893 DAG.setRoot(BrRange);
1896 /// visitBitTestCase - this function produces one "bit test"
1897 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1898 MachineBasicBlock* NextMBB,
1899 uint32_t BranchWeightToNext,
1902 MachineBasicBlock *SwitchBB) {
1903 SDLoc dl = getCurSDLoc();
1905 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
1907 unsigned PopCount = countPopulation(B.Mask);
1908 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1909 if (PopCount == 1) {
1910 // Testing for a single bit; just compare the shift count with what it
1911 // would need to be to shift a 1 bit in that position.
1913 dl, TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1914 DAG.getConstant(countTrailingZeros(B.Mask), dl, VT), ISD::SETEQ);
1915 } else if (PopCount == BB.Range) {
1916 // There is only one zero bit in the range, test for it directly.
1918 dl, TLI.getSetCCResultType(*DAG.getContext(), VT), ShiftOp,
1919 DAG.getConstant(countTrailingOnes(B.Mask), dl, VT), ISD::SETNE);
1921 // Make desired shift
1922 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
1923 DAG.getConstant(1, dl, VT), ShiftOp);
1925 // Emit bit tests and jumps
1926 SDValue AndOp = DAG.getNode(ISD::AND, dl,
1927 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
1928 Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(*DAG.getContext(), VT), AndOp,
1929 DAG.getConstant(0, dl, VT), ISD::SETNE);
1932 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1933 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1934 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1935 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
1937 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
1938 MVT::Other, getControlRoot(),
1939 Cmp, DAG.getBasicBlock(B.TargetBB));
1941 // Avoid emitting unnecessary branches to the next block.
1942 if (NextMBB != NextBlock(SwitchBB))
1943 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
1944 DAG.getBasicBlock(NextMBB));
1949 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1950 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1952 // Retrieve successors.
1953 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1954 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1956 const Value *Callee(I.getCalledValue());
1957 const Function *Fn = dyn_cast<Function>(Callee);
1958 if (isa<InlineAsm>(Callee))
1960 else if (Fn && Fn->isIntrinsic()) {
1961 switch (Fn->getIntrinsicID()) {
1963 llvm_unreachable("Cannot invoke this intrinsic");
1964 case Intrinsic::donothing:
1965 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
1967 case Intrinsic::experimental_patchpoint_void:
1968 case Intrinsic::experimental_patchpoint_i64:
1969 visitPatchpoint(&I, LandingPad);
1971 case Intrinsic::experimental_gc_statepoint:
1972 LowerStatepoint(ImmutableStatepoint(&I), LandingPad);
1976 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1978 // If the value of the invoke is used outside of its defining block, make it
1979 // available as a virtual register.
1980 // We already took care of the exported value for the statepoint instruction
1981 // during call to the LowerStatepoint.
1982 if (!isStatepoint(I)) {
1983 CopyToExportRegsIfNeeded(&I);
1986 // Update successor info
1987 addSuccessorWithWeight(InvokeMBB, Return);
1988 addSuccessorWithWeight(InvokeMBB, LandingPad);
1990 // Drop into normal successor.
1991 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1992 MVT::Other, getControlRoot(),
1993 DAG.getBasicBlock(Return)));
1996 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
1997 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2000 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2001 assert(FuncInfo.MBB->isLandingPad() &&
2002 "Call to landingpad not in landing pad!");
2004 MachineBasicBlock *MBB = FuncInfo.MBB;
2005 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
2006 AddLandingPadInfo(LP, MMI, MBB);
2008 // If there aren't registers to copy the values into (e.g., during SjLj
2009 // exceptions), then don't bother to create these DAG nodes.
2010 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2011 if (TLI.getExceptionPointerRegister() == 0 &&
2012 TLI.getExceptionSelectorRegister() == 0)
2015 SmallVector<EVT, 2> ValueVTs;
2016 SDLoc dl = getCurSDLoc();
2017 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2018 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2020 // Get the two live-in registers as SDValues. The physregs have already been
2021 // copied into virtual registers.
2023 if (FuncInfo.ExceptionPointerVirtReg) {
2024 Ops[0] = DAG.getZExtOrTrunc(
2025 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2026 FuncInfo.ExceptionPointerVirtReg, TLI.getPointerTy()),
2029 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy());
2031 Ops[1] = DAG.getZExtOrTrunc(
2032 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2033 FuncInfo.ExceptionSelectorVirtReg, TLI.getPointerTy()),
2037 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2038 DAG.getVTList(ValueVTs), Ops);
2043 SelectionDAGBuilder::visitLandingPadClauseBB(GlobalValue *ClauseGV,
2044 MachineBasicBlock *LPadBB) {
2045 SDValue Chain = getControlRoot();
2046 SDLoc dl = getCurSDLoc();
2048 // Get the typeid that we will dispatch on later.
2049 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2050 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy());
2051 unsigned VReg = FuncInfo.MF->getRegInfo().createVirtualRegister(RC);
2052 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(ClauseGV);
2053 SDValue Sel = DAG.getConstant(TypeID, dl, TLI.getPointerTy());
2054 Chain = DAG.getCopyToReg(Chain, dl, VReg, Sel);
2056 // Branch to the main landing pad block.
2057 MachineBasicBlock *ClauseMBB = FuncInfo.MBB;
2058 ClauseMBB->addSuccessor(LPadBB);
2059 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, Chain,
2060 DAG.getBasicBlock(LPadBB)));
2064 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2066 for (const CaseCluster &CC : Clusters)
2067 assert(CC.Low == CC.High && "Input clusters must be single-case");
2070 std::sort(Clusters.begin(), Clusters.end(),
2071 [](const CaseCluster &a, const CaseCluster &b) {
2072 return a.Low->getValue().slt(b.Low->getValue());
2075 // Merge adjacent clusters with the same destination.
2076 const unsigned N = Clusters.size();
2077 unsigned DstIndex = 0;
2078 for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2079 CaseCluster &CC = Clusters[SrcIndex];
2080 const ConstantInt *CaseVal = CC.Low;
2081 MachineBasicBlock *Succ = CC.MBB;
2083 if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2084 (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2085 // If this case has the same successor and is a neighbour, merge it into
2086 // the previous cluster.
2087 Clusters[DstIndex - 1].High = CaseVal;
2088 Clusters[DstIndex - 1].Weight += CC.Weight;
2089 assert(Clusters[DstIndex - 1].Weight >= CC.Weight && "Weight overflow!");
2091 std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2092 sizeof(Clusters[SrcIndex]));
2095 Clusters.resize(DstIndex);
2098 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2099 MachineBasicBlock *Last) {
2101 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2102 if (JTCases[i].first.HeaderBB == First)
2103 JTCases[i].first.HeaderBB = Last;
2105 // Update BitTestCases.
2106 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2107 if (BitTestCases[i].Parent == First)
2108 BitTestCases[i].Parent = Last;
2111 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2112 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2114 // Update machine-CFG edges with unique successors.
2115 SmallSet<BasicBlock*, 32> Done;
2116 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2117 BasicBlock *BB = I.getSuccessor(i);
2118 bool Inserted = Done.insert(BB).second;
2122 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2123 addSuccessorWithWeight(IndirectBrMBB, Succ);
2126 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2127 MVT::Other, getControlRoot(),
2128 getValue(I.getAddress())));
2131 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2132 if (DAG.getTarget().Options.TrapUnreachable)
2133 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2136 void SelectionDAGBuilder::visitFSub(const User &I) {
2137 // -0.0 - X --> fneg
2138 Type *Ty = I.getType();
2139 if (isa<Constant>(I.getOperand(0)) &&
2140 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2141 SDValue Op2 = getValue(I.getOperand(1));
2142 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2143 Op2.getValueType(), Op2));
2147 visitBinary(I, ISD::FSUB);
2150 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2151 SDValue Op1 = getValue(I.getOperand(0));
2152 SDValue Op2 = getValue(I.getOperand(1));
2159 if (const OverflowingBinaryOperator *OFBinOp =
2160 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2161 nuw = OFBinOp->hasNoUnsignedWrap();
2162 nsw = OFBinOp->hasNoSignedWrap();
2164 if (const PossiblyExactOperator *ExactOp =
2165 dyn_cast<const PossiblyExactOperator>(&I))
2166 exact = ExactOp->isExact();
2167 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(&I))
2168 FMF = FPOp->getFastMathFlags();
2171 Flags.setExact(exact);
2172 Flags.setNoSignedWrap(nsw);
2173 Flags.setNoUnsignedWrap(nuw);
2174 if (EnableFMFInDAG) {
2175 Flags.setAllowReciprocal(FMF.allowReciprocal());
2176 Flags.setNoInfs(FMF.noInfs());
2177 Flags.setNoNaNs(FMF.noNaNs());
2178 Flags.setNoSignedZeros(FMF.noSignedZeros());
2179 Flags.setUnsafeAlgebra(FMF.unsafeAlgebra());
2181 SDValue BinNodeValue = DAG.getNode(OpCode, getCurSDLoc(), Op1.getValueType(),
2183 setValue(&I, BinNodeValue);
2186 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2187 SDValue Op1 = getValue(I.getOperand(0));
2188 SDValue Op2 = getValue(I.getOperand(1));
2191 DAG.getTargetLoweringInfo().getShiftAmountTy(Op2.getValueType());
2193 // Coerce the shift amount to the right type if we can.
2194 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2195 unsigned ShiftSize = ShiftTy.getSizeInBits();
2196 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2197 SDLoc DL = getCurSDLoc();
2199 // If the operand is smaller than the shift count type, promote it.
2200 if (ShiftSize > Op2Size)
2201 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2203 // If the operand is larger than the shift count type but the shift
2204 // count type has enough bits to represent any shift value, truncate
2205 // it now. This is a common case and it exposes the truncate to
2206 // optimization early.
2207 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2208 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2209 // Otherwise we'll need to temporarily settle for some other convenient
2210 // type. Type legalization will make adjustments once the shiftee is split.
2212 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2219 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2221 if (const OverflowingBinaryOperator *OFBinOp =
2222 dyn_cast<const OverflowingBinaryOperator>(&I)) {
2223 nuw = OFBinOp->hasNoUnsignedWrap();
2224 nsw = OFBinOp->hasNoSignedWrap();
2226 if (const PossiblyExactOperator *ExactOp =
2227 dyn_cast<const PossiblyExactOperator>(&I))
2228 exact = ExactOp->isExact();
2231 Flags.setExact(exact);
2232 Flags.setNoSignedWrap(nsw);
2233 Flags.setNoUnsignedWrap(nuw);
2234 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2239 void SelectionDAGBuilder::visitSDiv(const User &I) {
2240 SDValue Op1 = getValue(I.getOperand(0));
2241 SDValue Op2 = getValue(I.getOperand(1));
2244 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2245 cast<PossiblyExactOperator>(&I)->isExact());
2246 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2250 void SelectionDAGBuilder::visitICmp(const User &I) {
2251 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2252 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2253 predicate = IC->getPredicate();
2254 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2255 predicate = ICmpInst::Predicate(IC->getPredicate());
2256 SDValue Op1 = getValue(I.getOperand(0));
2257 SDValue Op2 = getValue(I.getOperand(1));
2258 ISD::CondCode Opcode = getICmpCondCode(predicate);
2260 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2261 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2264 void SelectionDAGBuilder::visitFCmp(const User &I) {
2265 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2266 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2267 predicate = FC->getPredicate();
2268 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2269 predicate = FCmpInst::Predicate(FC->getPredicate());
2270 SDValue Op1 = getValue(I.getOperand(0));
2271 SDValue Op2 = getValue(I.getOperand(1));
2272 ISD::CondCode Condition = getFCmpCondCode(predicate);
2273 if (TM.Options.NoNaNsFPMath)
2274 Condition = getFCmpCodeWithoutNaN(Condition);
2275 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2276 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2279 void SelectionDAGBuilder::visitSelect(const User &I) {
2280 SmallVector<EVT, 4> ValueVTs;
2281 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2283 unsigned NumValues = ValueVTs.size();
2284 if (NumValues == 0) return;
2286 SmallVector<SDValue, 4> Values(NumValues);
2287 SDValue Cond = getValue(I.getOperand(0));
2288 SDValue LHSVal = getValue(I.getOperand(1));
2289 SDValue RHSVal = getValue(I.getOperand(2));
2290 auto BaseOps = {Cond};
2291 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2292 ISD::VSELECT : ISD::SELECT;
2294 // Min/max matching is only viable if all output VTs are the same.
2295 if (std::equal(ValueVTs.begin(), ValueVTs.end(), ValueVTs.begin())) {
2297 SelectPatternFlavor SPF = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2298 ISD::NodeType Opc = ISD::DELETED_NODE;
2300 case SPF_UMAX: Opc = ISD::UMAX; break;
2301 case SPF_UMIN: Opc = ISD::UMIN; break;
2302 case SPF_SMAX: Opc = ISD::SMAX; break;
2303 case SPF_SMIN: Opc = ISD::SMIN; break;
2307 EVT VT = ValueVTs[0];
2308 LLVMContext &Ctx = *DAG.getContext();
2309 auto &TLI = DAG.getTargetLoweringInfo();
2310 while (TLI.getTypeAction(Ctx, VT) == TargetLoweringBase::TypeSplitVector)
2311 VT = TLI.getTypeToTransformTo(Ctx, VT);
2313 if (Opc != ISD::DELETED_NODE && TLI.isOperationLegalOrCustom(Opc, VT) &&
2314 // If the underlying comparison instruction is used by any other instruction,
2315 // the consumed instructions won't be destroyed, so it is not profitable
2316 // to convert to a min/max.
2317 cast<SelectInst>(&I)->getCondition()->hasOneUse()) {
2319 LHSVal = getValue(LHS);
2320 RHSVal = getValue(RHS);
2325 for (unsigned i = 0; i != NumValues; ++i) {
2326 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
2327 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
2328 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
2329 Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
2330 LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
2334 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2335 DAG.getVTList(ValueVTs), Values));
2338 void SelectionDAGBuilder::visitTrunc(const User &I) {
2339 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2340 SDValue N = getValue(I.getOperand(0));
2341 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2342 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
2345 void SelectionDAGBuilder::visitZExt(const User &I) {
2346 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2347 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2348 SDValue N = getValue(I.getOperand(0));
2349 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2350 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
2353 void SelectionDAGBuilder::visitSExt(const User &I) {
2354 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2355 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2356 SDValue N = getValue(I.getOperand(0));
2357 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2358 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
2361 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2362 // FPTrunc is never a no-op cast, no need to check
2363 SDValue N = getValue(I.getOperand(0));
2364 SDLoc dl = getCurSDLoc();
2365 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2366 EVT DestVT = TLI.getValueType(I.getType());
2367 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
2368 DAG.getTargetConstant(0, dl, TLI.getPointerTy())));
2371 void SelectionDAGBuilder::visitFPExt(const User &I) {
2372 // FPExt is never a no-op cast, no need to check
2373 SDValue N = getValue(I.getOperand(0));
2374 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2375 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
2378 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2379 // FPToUI is never a no-op cast, no need to check
2380 SDValue N = getValue(I.getOperand(0));
2381 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2382 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
2385 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2386 // FPToSI is never a no-op cast, no need to check
2387 SDValue N = getValue(I.getOperand(0));
2388 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2389 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
2392 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2393 // UIToFP is never a no-op cast, no need to check
2394 SDValue N = getValue(I.getOperand(0));
2395 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2396 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
2399 void SelectionDAGBuilder::visitSIToFP(const User &I) {
2400 // SIToFP is never a no-op cast, no need to check
2401 SDValue N = getValue(I.getOperand(0));
2402 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2403 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
2406 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2407 // What to do depends on the size of the integer and the size of the pointer.
2408 // We can either truncate, zero extend, or no-op, accordingly.
2409 SDValue N = getValue(I.getOperand(0));
2410 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2411 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2414 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2415 // What to do depends on the size of the integer and the size of the pointer.
2416 // We can either truncate, zero extend, or no-op, accordingly.
2417 SDValue N = getValue(I.getOperand(0));
2418 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2419 setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
2422 void SelectionDAGBuilder::visitBitCast(const User &I) {
2423 SDValue N = getValue(I.getOperand(0));
2424 SDLoc dl = getCurSDLoc();
2425 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(I.getType());
2427 // BitCast assures us that source and destination are the same size so this is
2428 // either a BITCAST or a no-op.
2429 if (DestVT != N.getValueType())
2430 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
2431 DestVT, N)); // convert types.
2432 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
2433 // might fold any kind of constant expression to an integer constant and that
2434 // is not what we are looking for. Only regcognize a bitcast of a genuine
2435 // constant integer as an opaque constant.
2436 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
2437 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
2440 setValue(&I, N); // noop cast.
2443 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
2444 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2445 const Value *SV = I.getOperand(0);
2446 SDValue N = getValue(SV);
2447 EVT DestVT = TLI.getValueType(I.getType());
2449 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
2450 unsigned DestAS = I.getType()->getPointerAddressSpace();
2452 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2453 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
2458 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2459 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2460 SDValue InVec = getValue(I.getOperand(0));
2461 SDValue InVal = getValue(I.getOperand(1));
2462 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
2463 getCurSDLoc(), TLI.getVectorIdxTy());
2464 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
2465 TLI.getValueType(I.getType()), InVec, InVal, InIdx));
2468 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2469 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2470 SDValue InVec = getValue(I.getOperand(0));
2471 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
2472 getCurSDLoc(), TLI.getVectorIdxTy());
2473 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
2474 TLI.getValueType(I.getType()), InVec, InIdx));
2477 // Utility for visitShuffleVector - Return true if every element in Mask,
2478 // beginning from position Pos and ending in Pos+Size, falls within the
2479 // specified sequential range [L, L+Pos). or is undef.
2480 static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
2481 unsigned Pos, unsigned Size, int Low) {
2482 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
2483 if (Mask[i] >= 0 && Mask[i] != Low)
2488 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2489 SDValue Src1 = getValue(I.getOperand(0));
2490 SDValue Src2 = getValue(I.getOperand(1));
2492 SmallVector<int, 8> Mask;
2493 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2494 unsigned MaskNumElts = Mask.size();
2496 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2497 EVT VT = TLI.getValueType(I.getType());
2498 EVT SrcVT = Src1.getValueType();
2499 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2501 if (SrcNumElts == MaskNumElts) {
2502 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2507 // Normalize the shuffle vector since mask and vector length don't match.
2508 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2509 // Mask is longer than the source vectors and is a multiple of the source
2510 // vectors. We can use concatenate vector to make the mask and vectors
2512 if (SrcNumElts*2 == MaskNumElts) {
2513 // First check for Src1 in low and Src2 in high
2514 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
2515 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
2516 // The shuffle is concatenating two vectors together.
2517 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
2521 // Then check for Src2 in low and Src1 in high
2522 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
2523 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
2524 // The shuffle is concatenating two vectors together.
2525 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
2531 // Pad both vectors with undefs to make them the same length as the mask.
2532 unsigned NumConcat = MaskNumElts / SrcNumElts;
2533 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2534 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2535 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2537 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2538 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2542 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2543 getCurSDLoc(), VT, MOps1);
2544 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2545 getCurSDLoc(), VT, MOps2);
2547 // Readjust mask for new input vector length.
2548 SmallVector<int, 8> MappedOps;
2549 for (unsigned i = 0; i != MaskNumElts; ++i) {
2551 if (Idx >= (int)SrcNumElts)
2552 Idx -= SrcNumElts - MaskNumElts;
2553 MappedOps.push_back(Idx);
2556 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2561 if (SrcNumElts > MaskNumElts) {
2562 // Analyze the access pattern of the vector to see if we can extract
2563 // two subvectors and do the shuffle. The analysis is done by calculating
2564 // the range of elements the mask access on both vectors.
2565 int MinRange[2] = { static_cast<int>(SrcNumElts),
2566 static_cast<int>(SrcNumElts)};
2567 int MaxRange[2] = {-1, -1};
2569 for (unsigned i = 0; i != MaskNumElts; ++i) {
2575 if (Idx >= (int)SrcNumElts) {
2579 if (Idx > MaxRange[Input])
2580 MaxRange[Input] = Idx;
2581 if (Idx < MinRange[Input])
2582 MinRange[Input] = Idx;
2585 // Check if the access is smaller than the vector size and can we find
2586 // a reasonable extract index.
2587 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
2589 int StartIdx[2]; // StartIdx to extract from
2590 for (unsigned Input = 0; Input < 2; ++Input) {
2591 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
2592 RangeUse[Input] = 0; // Unused
2593 StartIdx[Input] = 0;
2597 // Find a good start index that is a multiple of the mask length. Then
2598 // see if the rest of the elements are in range.
2599 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2600 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2601 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2602 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2605 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2606 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2609 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
2610 // Extract appropriate subvector and generate a vector shuffle
2611 for (unsigned Input = 0; Input < 2; ++Input) {
2612 SDValue &Src = Input == 0 ? Src1 : Src2;
2613 if (RangeUse[Input] == 0)
2614 Src = DAG.getUNDEF(VT);
2616 SDLoc dl = getCurSDLoc();
2618 ISD::EXTRACT_SUBVECTOR, dl, VT, Src,
2619 DAG.getConstant(StartIdx[Input], dl, TLI.getVectorIdxTy()));
2623 // Calculate new mask.
2624 SmallVector<int, 8> MappedOps;
2625 for (unsigned i = 0; i != MaskNumElts; ++i) {
2628 if (Idx < (int)SrcNumElts)
2631 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
2633 MappedOps.push_back(Idx);
2636 setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
2642 // We can't use either concat vectors or extract subvectors so fall back to
2643 // replacing the shuffle with extract and build vector.
2644 // to insert and build vector.
2645 EVT EltVT = VT.getVectorElementType();
2646 EVT IdxVT = TLI.getVectorIdxTy();
2647 SDLoc dl = getCurSDLoc();
2648 SmallVector<SDValue,8> Ops;
2649 for (unsigned i = 0; i != MaskNumElts; ++i) {
2654 Res = DAG.getUNDEF(EltVT);
2656 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
2657 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
2659 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2660 EltVT, Src, DAG.getConstant(Idx, dl, IdxVT));
2666 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops));
2669 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2670 const Value *Op0 = I.getOperand(0);
2671 const Value *Op1 = I.getOperand(1);
2672 Type *AggTy = I.getType();
2673 Type *ValTy = Op1->getType();
2674 bool IntoUndef = isa<UndefValue>(Op0);
2675 bool FromUndef = isa<UndefValue>(Op1);
2677 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
2679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2680 SmallVector<EVT, 4> AggValueVTs;
2681 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
2682 SmallVector<EVT, 4> ValValueVTs;
2683 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
2685 unsigned NumAggValues = AggValueVTs.size();
2686 unsigned NumValValues = ValValueVTs.size();
2687 SmallVector<SDValue, 4> Values(NumAggValues);
2689 // Ignore an insertvalue that produces an empty object
2690 if (!NumAggValues) {
2691 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
2695 SDValue Agg = getValue(Op0);
2697 // Copy the beginning value(s) from the original aggregate.
2698 for (; i != LinearIndex; ++i)
2699 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2700 SDValue(Agg.getNode(), Agg.getResNo() + i);
2701 // Copy values from the inserted value(s).
2703 SDValue Val = getValue(Op1);
2704 for (; i != LinearIndex + NumValValues; ++i)
2705 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2706 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2708 // Copy remaining value(s) from the original aggregate.
2709 for (; i != NumAggValues; ++i)
2710 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2711 SDValue(Agg.getNode(), Agg.getResNo() + i);
2713 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2714 DAG.getVTList(AggValueVTs), Values));
2717 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2718 const Value *Op0 = I.getOperand(0);
2719 Type *AggTy = Op0->getType();
2720 Type *ValTy = I.getType();
2721 bool OutOfUndef = isa<UndefValue>(Op0);
2723 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
2725 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2726 SmallVector<EVT, 4> ValValueVTs;
2727 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
2729 unsigned NumValValues = ValValueVTs.size();
2731 // Ignore a extractvalue that produces an empty object
2732 if (!NumValValues) {
2733 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
2737 SmallVector<SDValue, 4> Values(NumValValues);
2739 SDValue Agg = getValue(Op0);
2740 // Copy out the selected value(s).
2741 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2742 Values[i - LinearIndex] =
2744 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2745 SDValue(Agg.getNode(), Agg.getResNo() + i);
2747 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
2748 DAG.getVTList(ValValueVTs), Values));
2751 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2752 Value *Op0 = I.getOperand(0);
2753 // Note that the pointer operand may be a vector of pointers. Take the scalar
2754 // element which holds a pointer.
2755 Type *Ty = Op0->getType()->getScalarType();
2756 unsigned AS = Ty->getPointerAddressSpace();
2757 SDValue N = getValue(Op0);
2758 SDLoc dl = getCurSDLoc();
2760 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2762 const Value *Idx = *OI;
2763 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
2764 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
2767 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
2768 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
2769 DAG.getConstant(Offset, dl, N.getValueType()));
2772 Ty = StTy->getElementType(Field);
2774 Ty = cast<SequentialType>(Ty)->getElementType();
2775 MVT PtrTy = DAG.getTargetLoweringInfo().getPointerTy(AS);
2776 unsigned PtrSize = PtrTy.getSizeInBits();
2777 APInt ElementSize(PtrSize, DL->getTypeAllocSize(Ty));
2779 // If this is a constant subscript, handle it quickly.
2780 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
2783 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(PtrSize);
2784 SDValue OffsVal = DAG.getConstant(Offs, dl, PtrTy);
2785 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal);
2789 // N = N + Idx * ElementSize;
2790 SDValue IdxN = getValue(Idx);
2792 // If the index is smaller or larger than intptr_t, truncate or extend
2794 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
2796 // If this is a multiply by a power of two, turn it into a shl
2797 // immediately. This is a very common case.
2798 if (ElementSize != 1) {
2799 if (ElementSize.isPowerOf2()) {
2800 unsigned Amt = ElementSize.logBase2();
2801 IdxN = DAG.getNode(ISD::SHL, dl,
2802 N.getValueType(), IdxN,
2803 DAG.getConstant(Amt, dl, IdxN.getValueType()));
2805 SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
2806 IdxN = DAG.getNode(ISD::MUL, dl,
2807 N.getValueType(), IdxN, Scale);
2811 N = DAG.getNode(ISD::ADD, dl,
2812 N.getValueType(), N, IdxN);
2819 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
2820 // If this is a fixed sized alloca in the entry block of the function,
2821 // allocate it statically on the stack.
2822 if (FuncInfo.StaticAllocaMap.count(&I))
2823 return; // getValue will auto-populate this.
2825 SDLoc dl = getCurSDLoc();
2826 Type *Ty = I.getAllocatedType();
2827 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2828 auto &DL = DAG.getDataLayout();
2829 uint64_t TySize = DL.getTypeAllocSize(Ty);
2831 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
2833 SDValue AllocSize = getValue(I.getArraySize());
2835 EVT IntPtr = TLI.getPointerTy();
2836 if (AllocSize.getValueType() != IntPtr)
2837 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
2839 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
2841 DAG.getConstant(TySize, dl, IntPtr));
2843 // Handle alignment. If the requested alignment is less than or equal to
2844 // the stack alignment, ignore it. If the size is greater than or equal to
2845 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2846 unsigned StackAlign =
2847 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
2848 if (Align <= StackAlign)
2851 // Round the size of the allocation up to the stack alignment size
2852 // by add SA-1 to the size.
2853 AllocSize = DAG.getNode(ISD::ADD, dl,
2854 AllocSize.getValueType(), AllocSize,
2855 DAG.getIntPtrConstant(StackAlign - 1, dl));
2857 // Mask out the low bits for alignment purposes.
2858 AllocSize = DAG.getNode(ISD::AND, dl,
2859 AllocSize.getValueType(), AllocSize,
2860 DAG.getIntPtrConstant(~(uint64_t)(StackAlign - 1),
2863 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align, dl) };
2864 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2865 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
2867 DAG.setRoot(DSA.getValue(1));
2869 assert(FuncInfo.MF->getFrameInfo()->hasVarSizedObjects());
2872 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
2874 return visitAtomicLoad(I);
2876 const Value *SV = I.getOperand(0);
2877 SDValue Ptr = getValue(SV);
2879 Type *Ty = I.getType();
2881 bool isVolatile = I.isVolatile();
2882 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
2884 // The IR notion of invariant_load only guarantees that all *non-faulting*
2885 // invariant loads result in the same value. The MI notion of invariant load
2886 // guarantees that the load can be legally moved to any location within its
2887 // containing function. The MI notion of invariant_load is stronger than the
2888 // IR notion of invariant_load -- an MI invariant_load is an IR invariant_load
2889 // with a guarantee that the location being loaded from is dereferenceable
2890 // throughout the function's lifetime.
2892 bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr &&
2893 isDereferenceablePointer(SV, *DAG.getTarget().getDataLayout());
2894 unsigned Alignment = I.getAlignment();
2897 I.getAAMetadata(AAInfo);
2898 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
2900 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2901 SmallVector<EVT, 4> ValueVTs;
2902 SmallVector<uint64_t, 4> Offsets;
2903 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
2904 unsigned NumValues = ValueVTs.size();
2909 bool ConstantMemory = false;
2910 if (isVolatile || NumValues > MaxParallelChains)
2911 // Serialize volatile loads with other side effects.
2913 else if (AA->pointsToConstantMemory(
2914 MemoryLocation(SV, AA->getTypeStoreSize(Ty), AAInfo))) {
2915 // Do not serialize (non-volatile) loads of constant memory with anything.
2916 Root = DAG.getEntryNode();
2917 ConstantMemory = true;
2919 // Do not serialize non-volatile loads against each other.
2920 Root = DAG.getRoot();
2923 SDLoc dl = getCurSDLoc();
2926 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
2928 SmallVector<SDValue, 4> Values(NumValues);
2929 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
2930 EVT PtrVT = Ptr.getValueType();
2931 unsigned ChainI = 0;
2932 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
2933 // Serializing loads here may result in excessive register pressure, and
2934 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
2935 // could recover a bit by hoisting nodes upward in the chain by recognizing
2936 // they are side-effect free or do not alias. The optimizer should really
2937 // avoid this case by converting large object/array copies to llvm.memcpy
2938 // (MaxParallelChains should always remain as failsafe).
2939 if (ChainI == MaxParallelChains) {
2940 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
2941 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2942 makeArrayRef(Chains.data(), ChainI));
2946 SDValue A = DAG.getNode(ISD::ADD, dl,
2948 DAG.getConstant(Offsets[i], dl, PtrVT));
2949 SDValue L = DAG.getLoad(ValueVTs[i], dl, Root,
2950 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
2951 isNonTemporal, isInvariant, Alignment, AAInfo,
2955 Chains[ChainI] = L.getValue(1);
2958 if (!ConstantMemory) {
2959 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2960 makeArrayRef(Chains.data(), ChainI));
2964 PendingLoads.push_back(Chain);
2967 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
2968 DAG.getVTList(ValueVTs), Values));
2971 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
2973 return visitAtomicStore(I);
2975 const Value *SrcV = I.getOperand(0);
2976 const Value *PtrV = I.getOperand(1);
2978 SmallVector<EVT, 4> ValueVTs;
2979 SmallVector<uint64_t, 4> Offsets;
2980 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
2981 SrcV->getType(), ValueVTs, &Offsets);
2982 unsigned NumValues = ValueVTs.size();
2986 // Get the lowered operands. Note that we do this after
2987 // checking if NumResults is zero, because with zero results
2988 // the operands won't have values in the map.
2989 SDValue Src = getValue(SrcV);
2990 SDValue Ptr = getValue(PtrV);
2992 SDValue Root = getRoot();
2993 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
2994 EVT PtrVT = Ptr.getValueType();
2995 bool isVolatile = I.isVolatile();
2996 bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
2997 unsigned Alignment = I.getAlignment();
2998 SDLoc dl = getCurSDLoc();
3001 I.getAAMetadata(AAInfo);
3003 unsigned ChainI = 0;
3004 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3005 // See visitLoad comments.
3006 if (ChainI == MaxParallelChains) {
3007 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3008 makeArrayRef(Chains.data(), ChainI));
3012 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3013 DAG.getConstant(Offsets[i], dl, PtrVT));
3014 SDValue St = DAG.getStore(Root, dl,
3015 SDValue(Src.getNode(), Src.getResNo() + i),
3016 Add, MachinePointerInfo(PtrV, Offsets[i]),
3017 isVolatile, isNonTemporal, Alignment, AAInfo);
3018 Chains[ChainI] = St;
3021 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3022 makeArrayRef(Chains.data(), ChainI));
3023 DAG.setRoot(StoreNode);
3026 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I) {
3027 SDLoc sdl = getCurSDLoc();
3029 // llvm.masked.store.*(Src0, Ptr, alignemt, Mask)
3030 Value *PtrOperand = I.getArgOperand(1);
3031 SDValue Ptr = getValue(PtrOperand);
3032 SDValue Src0 = getValue(I.getArgOperand(0));
3033 SDValue Mask = getValue(I.getArgOperand(3));
3034 EVT VT = Src0.getValueType();
3035 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3037 Alignment = DAG.getEVTAlignment(VT);
3040 I.getAAMetadata(AAInfo);
3042 MachineMemOperand *MMO =
3043 DAG.getMachineFunction().
3044 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3045 MachineMemOperand::MOStore, VT.getStoreSize(),
3047 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3049 DAG.setRoot(StoreNode);
3050 setValue(&I, StoreNode);
3053 // Gather/scatter receive a vector of pointers.
3054 // This vector of pointers may be represented as a base pointer + vector of
3055 // indices, it depends on GEP and instruction preceeding GEP
3056 // that calculates indices
3057 static bool getUniformBase(Value *& Ptr, SDValue& Base, SDValue& Index,
3058 SelectionDAGBuilder* SDB) {
3060 assert (Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3061 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
3062 if (!Gep || Gep->getNumOperands() > 2)
3064 ShuffleVectorInst *ShuffleInst =
3065 dyn_cast<ShuffleVectorInst>(Gep->getPointerOperand());
3066 if (!ShuffleInst || !ShuffleInst->getMask()->isNullValue() ||
3067 cast<Instruction>(ShuffleInst->getOperand(0))->getOpcode() !=
3068 Instruction::InsertElement)
3071 Ptr = cast<InsertElementInst>(ShuffleInst->getOperand(0))->getOperand(1);
3073 SelectionDAG& DAG = SDB->DAG;
3074 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3075 // Check is the Ptr is inside current basic block
3076 // If not, look for the shuffle instruction
3077 if (SDB->findValue(Ptr))
3078 Base = SDB->getValue(Ptr);
3079 else if (SDB->findValue(ShuffleInst)) {
3080 SDValue ShuffleNode = SDB->getValue(ShuffleInst);
3081 SDLoc sdl = ShuffleNode;
3082 Base = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl,
3083 ShuffleNode.getValueType().getScalarType(), ShuffleNode,
3084 DAG.getConstant(0, sdl, TLI.getVectorIdxTy()));
3085 SDB->setValue(Ptr, Base);
3090 Value *IndexVal = Gep->getOperand(1);
3091 if (SDB->findValue(IndexVal)) {
3092 Index = SDB->getValue(IndexVal);
3094 if (SExtInst* Sext = dyn_cast<SExtInst>(IndexVal)) {
3095 IndexVal = Sext->getOperand(0);
3096 if (SDB->findValue(IndexVal))
3097 Index = SDB->getValue(IndexVal);
3104 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
3105 SDLoc sdl = getCurSDLoc();
3107 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
3108 Value *Ptr = I.getArgOperand(1);
3109 SDValue Src0 = getValue(I.getArgOperand(0));
3110 SDValue Mask = getValue(I.getArgOperand(3));
3111 EVT VT = Src0.getValueType();
3112 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
3114 Alignment = DAG.getEVTAlignment(VT);
3115 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3118 I.getAAMetadata(AAInfo);
3122 Value *BasePtr = Ptr;
3123 bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3125 Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
3126 MachineMemOperand *MMO = DAG.getMachineFunction().
3127 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
3128 MachineMemOperand::MOStore, VT.getStoreSize(),
3131 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy());
3132 Index = getValue(Ptr);
3134 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index };
3135 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
3137 DAG.setRoot(Scatter);
3138 setValue(&I, Scatter);
3141 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I) {
3142 SDLoc sdl = getCurSDLoc();
3144 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
3145 Value *PtrOperand = I.getArgOperand(0);
3146 SDValue Ptr = getValue(PtrOperand);
3147 SDValue Src0 = getValue(I.getArgOperand(3));
3148 SDValue Mask = getValue(I.getArgOperand(2));
3150 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3151 EVT VT = TLI.getValueType(I.getType());
3152 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3154 Alignment = DAG.getEVTAlignment(VT);
3157 I.getAAMetadata(AAInfo);
3158 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3160 SDValue InChain = DAG.getRoot();
3161 if (AA->pointsToConstantMemory(MemoryLocation(
3162 PtrOperand, AA->getTypeStoreSize(I.getType()), AAInfo))) {
3163 // Do not serialize (non-volatile) loads of constant memory with anything.
3164 InChain = DAG.getEntryNode();
3167 MachineMemOperand *MMO =
3168 DAG.getMachineFunction().
3169 getMachineMemOperand(MachinePointerInfo(PtrOperand),
3170 MachineMemOperand::MOLoad, VT.getStoreSize(),
3171 Alignment, AAInfo, Ranges);
3173 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
3175 SDValue OutChain = Load.getValue(1);
3176 DAG.setRoot(OutChain);
3180 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
3181 SDLoc sdl = getCurSDLoc();
3183 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
3184 Value *Ptr = I.getArgOperand(0);
3185 SDValue Src0 = getValue(I.getArgOperand(3));
3186 SDValue Mask = getValue(I.getArgOperand(2));
3188 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3189 EVT VT = TLI.getValueType(I.getType());
3190 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
3192 Alignment = DAG.getEVTAlignment(VT);
3195 I.getAAMetadata(AAInfo);
3196 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3198 SDValue Root = DAG.getRoot();
3201 Value *BasePtr = Ptr;
3202 bool UniformBase = getUniformBase(BasePtr, Base, Index, this);
3203 bool ConstantMemory = false;
3205 AA->pointsToConstantMemory(
3206 MemoryLocation(BasePtr, AA->getTypeStoreSize(I.getType()), AAInfo))) {
3207 // Do not serialize (non-volatile) loads of constant memory with anything.
3208 Root = DAG.getEntryNode();
3209 ConstantMemory = true;
3212 MachineMemOperand *MMO =
3213 DAG.getMachineFunction().
3214 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
3215 MachineMemOperand::MOLoad, VT.getStoreSize(),
3216 Alignment, AAInfo, Ranges);
3219 Base = DAG.getTargetConstant(0, sdl, TLI.getPointerTy());
3220 Index = getValue(Ptr);
3222 SDValue Ops[] = { Root, Src0, Mask, Base, Index };
3223 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
3226 SDValue OutChain = Gather.getValue(1);
3227 if (!ConstantMemory)
3228 PendingLoads.push_back(OutChain);
3229 setValue(&I, Gather);
3232 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
3233 SDLoc dl = getCurSDLoc();
3234 AtomicOrdering SuccessOrder = I.getSuccessOrdering();
3235 AtomicOrdering FailureOrder = I.getFailureOrdering();
3236 SynchronizationScope Scope = I.getSynchScope();
3238 SDValue InChain = getRoot();
3240 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
3241 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
3242 SDValue L = DAG.getAtomicCmpSwap(
3243 ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
3244 getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
3245 getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
3246 /*Alignment=*/ 0, SuccessOrder, FailureOrder, Scope);
3248 SDValue OutChain = L.getValue(2);
3251 DAG.setRoot(OutChain);
3254 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
3255 SDLoc dl = getCurSDLoc();
3257 switch (I.getOperation()) {
3258 default: llvm_unreachable("Unknown atomicrmw operation");
3259 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3260 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3261 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3262 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3263 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3264 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3265 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3266 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3267 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3268 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3269 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3271 AtomicOrdering Order = I.getOrdering();
3272 SynchronizationScope Scope = I.getSynchScope();
3274 SDValue InChain = getRoot();
3277 DAG.getAtomic(NT, dl,
3278 getValue(I.getValOperand()).getSimpleValueType(),
3280 getValue(I.getPointerOperand()),
3281 getValue(I.getValOperand()),
3282 I.getPointerOperand(),
3283 /* Alignment=*/ 0, Order, Scope);
3285 SDValue OutChain = L.getValue(1);
3288 DAG.setRoot(OutChain);
3291 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
3292 SDLoc dl = getCurSDLoc();
3293 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3296 Ops[1] = DAG.getConstant(I.getOrdering(), dl, TLI.getPointerTy());
3297 Ops[2] = DAG.getConstant(I.getSynchScope(), dl, TLI.getPointerTy());
3298 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
3301 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3302 SDLoc dl = getCurSDLoc();
3303 AtomicOrdering Order = I.getOrdering();
3304 SynchronizationScope Scope = I.getSynchScope();
3306 SDValue InChain = getRoot();
3308 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3309 EVT VT = TLI.getValueType(I.getType());
3311 if (I.getAlignment() < VT.getSizeInBits() / 8)
3312 report_fatal_error("Cannot generate unaligned atomic load");
3314 MachineMemOperand *MMO =
3315 DAG.getMachineFunction().
3316 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
3317 MachineMemOperand::MOVolatile |
3318 MachineMemOperand::MOLoad,
3320 I.getAlignment() ? I.getAlignment() :
3321 DAG.getEVTAlignment(VT));
3323 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
3325 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3326 getValue(I.getPointerOperand()), MMO,
3329 SDValue OutChain = L.getValue(1);
3332 DAG.setRoot(OutChain);
3335 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3336 SDLoc dl = getCurSDLoc();
3338 AtomicOrdering Order = I.getOrdering();
3339 SynchronizationScope Scope = I.getSynchScope();
3341 SDValue InChain = getRoot();
3343 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3344 EVT VT = TLI.getValueType(I.getValueOperand()->getType());
3346 if (I.getAlignment() < VT.getSizeInBits() / 8)
3347 report_fatal_error("Cannot generate unaligned atomic store");
3350 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
3352 getValue(I.getPointerOperand()),
3353 getValue(I.getValueOperand()),
3354 I.getPointerOperand(), I.getAlignment(),
3357 DAG.setRoot(OutChain);
3360 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3362 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3363 unsigned Intrinsic) {
3364 bool HasChain = !I.doesNotAccessMemory();
3365 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3367 // Build the operand list.
3368 SmallVector<SDValue, 8> Ops;
3369 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3371 // We don't need to serialize loads against other loads.
3372 Ops.push_back(DAG.getRoot());
3374 Ops.push_back(getRoot());
3378 // Info is set by getTgtMemInstrinsic
3379 TargetLowering::IntrinsicInfo Info;
3380 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3381 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3383 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3384 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3385 Info.opc == ISD::INTRINSIC_W_CHAIN)
3386 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
3387 TLI.getPointerTy()));
3389 // Add all operands of the call to the operand list.
3390 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3391 SDValue Op = getValue(I.getArgOperand(i));
3395 SmallVector<EVT, 4> ValueVTs;
3396 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
3399 ValueVTs.push_back(MVT::Other);
3401 SDVTList VTs = DAG.getVTList(ValueVTs);
3405 if (IsTgtIntrinsic) {
3406 // This is target intrinsic that touches memory
3407 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
3408 VTs, Ops, Info.memVT,
3409 MachinePointerInfo(Info.ptrVal, Info.offset),
3410 Info.align, Info.vol,
3411 Info.readMem, Info.writeMem, Info.size);
3412 } else if (!HasChain) {
3413 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
3414 } else if (!I.getType()->isVoidTy()) {
3415 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
3417 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
3421 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3423 PendingLoads.push_back(Chain);
3428 if (!I.getType()->isVoidTy()) {
3429 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3430 EVT VT = TLI.getValueType(PTy);
3431 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
3434 setValue(&I, Result);
3438 /// GetSignificand - Get the significand and build it into a floating-point
3439 /// number with exponent of 1:
3441 /// Op = (Op & 0x007fffff) | 0x3f800000;
3443 /// where Op is the hexadecimal representation of floating point value.
3445 GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
3446 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3447 DAG.getConstant(0x007fffff, dl, MVT::i32));
3448 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3449 DAG.getConstant(0x3f800000, dl, MVT::i32));
3450 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3453 /// GetExponent - Get the exponent:
3455 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3457 /// where Op is the hexadecimal representation of floating point value.
3459 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3461 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3462 DAG.getConstant(0x7f800000, dl, MVT::i32));
3463 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3464 DAG.getConstant(23, dl, TLI.getPointerTy()));
3465 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3466 DAG.getConstant(127, dl, MVT::i32));
3467 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3470 /// getF32Constant - Get 32-bit floating point constant.
3472 getF32Constant(SelectionDAG &DAG, unsigned Flt, SDLoc dl) {
3473 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)), dl,
3477 static SDValue getLimitedPrecisionExp2(SDValue t0, SDLoc dl,
3478 SelectionDAG &DAG) {
3479 // IntegerPartOfX = ((int32_t)(t0);
3480 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3482 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
3483 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3484 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3486 // IntegerPartOfX <<= 23;
3487 IntegerPartOfX = DAG.getNode(
3488 ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3489 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy()));
3491 SDValue TwoToFractionalPartOfX;
3492 if (LimitFloatPrecision <= 6) {
3493 // For floating-point precision of 6:
3495 // TwoToFractionalPartOfX =
3497 // (0.735607626f + 0.252464424f * x) * x;
3499 // error 0.0144103317, which is 6 bits
3500 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3501 getF32Constant(DAG, 0x3e814304, dl));
3502 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3503 getF32Constant(DAG, 0x3f3c50c8, dl));
3504 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3505 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3506 getF32Constant(DAG, 0x3f7f5e7e, dl));
3507 } else if (LimitFloatPrecision <= 12) {
3508 // For floating-point precision of 12:
3510 // TwoToFractionalPartOfX =
3513 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3515 // error 0.000107046256, which is 13 to 14 bits
3516 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3517 getF32Constant(DAG, 0x3da235e3, dl));
3518 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3519 getF32Constant(DAG, 0x3e65b8f3, dl));
3520 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3521 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3522 getF32Constant(DAG, 0x3f324b07, dl));
3523 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3524 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3525 getF32Constant(DAG, 0x3f7ff8fd, dl));
3526 } else { // LimitFloatPrecision <= 18
3527 // For floating-point precision of 18:
3529 // TwoToFractionalPartOfX =
3533 // (0.554906021e-1f +
3534 // (0.961591928e-2f +
3535 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3536 // error 2.47208000*10^(-7), which is better than 18 bits
3537 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3538 getF32Constant(DAG, 0x3924b03e, dl));
3539 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3540 getF32Constant(DAG, 0x3ab24b87, dl));
3541 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3542 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3543 getF32Constant(DAG, 0x3c1d8c17, dl));
3544 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3545 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3546 getF32Constant(DAG, 0x3d634a1d, dl));
3547 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3548 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3549 getF32Constant(DAG, 0x3e75fe14, dl));
3550 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3551 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3552 getF32Constant(DAG, 0x3f317234, dl));
3553 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3554 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3555 getF32Constant(DAG, 0x3f800000, dl));
3558 // Add the exponent into the result in integer domain.
3559 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
3560 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3561 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
3564 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
3565 /// limited-precision mode.
3566 static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3567 const TargetLowering &TLI) {
3568 if (Op.getValueType() == MVT::f32 &&
3569 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3571 // Put the exponent in the right bit position for later addition to the
3574 // #define LOG2OFe 1.4426950f
3575 // t0 = Op * LOG2OFe
3576 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3577 getF32Constant(DAG, 0x3fb8aa3b, dl));
3578 return getLimitedPrecisionExp2(t0, dl, DAG);
3581 // No special expansion.
3582 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
3585 /// expandLog - Lower a log intrinsic. Handles the special sequences for
3586 /// limited-precision mode.
3587 static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3588 const TargetLowering &TLI) {
3589 if (Op.getValueType() == MVT::f32 &&
3590 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3591 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3593 // Scale the exponent by log(2) [0.69314718f].
3594 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3595 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3596 getF32Constant(DAG, 0x3f317218, dl));
3598 // Get the significand and build it into a floating-point number with
3600 SDValue X = GetSignificand(DAG, Op1, dl);
3602 SDValue LogOfMantissa;
3603 if (LimitFloatPrecision <= 6) {
3604 // For floating-point precision of 6:
3608 // (1.4034025f - 0.23903021f * x) * x;
3610 // error 0.0034276066, which is better than 8 bits
3611 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3612 getF32Constant(DAG, 0xbe74c456, dl));
3613 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3614 getF32Constant(DAG, 0x3fb3a2b1, dl));
3615 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3616 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3617 getF32Constant(DAG, 0x3f949a29, dl));
3618 } else if (LimitFloatPrecision <= 12) {
3619 // For floating-point precision of 12:
3625 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3627 // error 0.000061011436, which is 14 bits
3628 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3629 getF32Constant(DAG, 0xbd67b6d6, dl));
3630 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3631 getF32Constant(DAG, 0x3ee4f4b8, dl));
3632 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3633 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3634 getF32Constant(DAG, 0x3fbc278b, dl));
3635 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3636 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3637 getF32Constant(DAG, 0x40348e95, dl));
3638 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3639 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3640 getF32Constant(DAG, 0x3fdef31a, dl));
3641 } else { // LimitFloatPrecision <= 18
3642 // For floating-point precision of 18:
3650 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3652 // error 0.0000023660568, which is better than 18 bits
3653 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3654 getF32Constant(DAG, 0xbc91e5ac, dl));
3655 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3656 getF32Constant(DAG, 0x3e4350aa, dl));
3657 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3658 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3659 getF32Constant(DAG, 0x3f60d3e3, dl));
3660 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3661 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3662 getF32Constant(DAG, 0x4011cdf0, dl));
3663 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3664 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3665 getF32Constant(DAG, 0x406cfd1c, dl));
3666 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3667 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3668 getF32Constant(DAG, 0x408797cb, dl));
3669 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3670 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3671 getF32Constant(DAG, 0x4006dcab, dl));
3674 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
3677 // No special expansion.
3678 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
3681 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
3682 /// limited-precision mode.
3683 static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3684 const TargetLowering &TLI) {
3685 if (Op.getValueType() == MVT::f32 &&
3686 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3687 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3689 // Get the exponent.
3690 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3692 // Get the significand and build it into a floating-point number with
3694 SDValue X = GetSignificand(DAG, Op1, dl);
3696 // Different possible minimax approximations of significand in
3697 // floating-point for various degrees of accuracy over [1,2].
3698 SDValue Log2ofMantissa;
3699 if (LimitFloatPrecision <= 6) {
3700 // For floating-point precision of 6:
3702 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3704 // error 0.0049451742, which is more than 7 bits
3705 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3706 getF32Constant(DAG, 0xbeb08fe0, dl));
3707 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3708 getF32Constant(DAG, 0x40019463, dl));
3709 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3710 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3711 getF32Constant(DAG, 0x3fd6633d, dl));
3712 } else if (LimitFloatPrecision <= 12) {
3713 // For floating-point precision of 12:
3719 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3721 // error 0.0000876136000, which is better than 13 bits
3722 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3723 getF32Constant(DAG, 0xbda7262e, dl));
3724 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3725 getF32Constant(DAG, 0x3f25280b, dl));
3726 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3727 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3728 getF32Constant(DAG, 0x4007b923, dl));
3729 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3730 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3731 getF32Constant(DAG, 0x40823e2f, dl));
3732 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3733 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3734 getF32Constant(DAG, 0x4020d29c, dl));
3735 } else { // LimitFloatPrecision <= 18
3736 // For floating-point precision of 18:
3745 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3747 // error 0.0000018516, which is better than 18 bits
3748 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3749 getF32Constant(DAG, 0xbcd2769e, dl));
3750 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3751 getF32Constant(DAG, 0x3e8ce0b9, dl));
3752 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3753 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3754 getF32Constant(DAG, 0x3fa22ae7, dl));
3755 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3756 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3757 getF32Constant(DAG, 0x40525723, dl));
3758 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3759 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3760 getF32Constant(DAG, 0x40aaf200, dl));
3761 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3762 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3763 getF32Constant(DAG, 0x40c39dad, dl));
3764 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3765 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3766 getF32Constant(DAG, 0x4042902c, dl));
3769 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
3772 // No special expansion.
3773 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
3776 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
3777 /// limited-precision mode.
3778 static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3779 const TargetLowering &TLI) {
3780 if (Op.getValueType() == MVT::f32 &&
3781 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3782 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3784 // Scale the exponent by log10(2) [0.30102999f].
3785 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3786 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3787 getF32Constant(DAG, 0x3e9a209a, dl));
3789 // Get the significand and build it into a floating-point number with
3791 SDValue X = GetSignificand(DAG, Op1, dl);
3793 SDValue Log10ofMantissa;
3794 if (LimitFloatPrecision <= 6) {
3795 // For floating-point precision of 6:
3797 // Log10ofMantissa =
3799 // (0.60948995f - 0.10380950f * x) * x;
3801 // error 0.0014886165, which is 6 bits
3802 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3803 getF32Constant(DAG, 0xbdd49a13, dl));
3804 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3805 getF32Constant(DAG, 0x3f1c0789, dl));
3806 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3807 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3808 getF32Constant(DAG, 0x3f011300, dl));
3809 } else if (LimitFloatPrecision <= 12) {
3810 // For floating-point precision of 12:
3812 // Log10ofMantissa =
3815 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3817 // error 0.00019228036, which is better than 12 bits
3818 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3819 getF32Constant(DAG, 0x3d431f31, dl));
3820 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3821 getF32Constant(DAG, 0x3ea21fb2, dl));
3822 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3823 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3824 getF32Constant(DAG, 0x3f6ae232, dl));
3825 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3826 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3827 getF32Constant(DAG, 0x3f25f7c3, dl));
3828 } else { // LimitFloatPrecision <= 18
3829 // For floating-point precision of 18:
3831 // Log10ofMantissa =
3836 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3838 // error 0.0000037995730, which is better than 18 bits
3839 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3840 getF32Constant(DAG, 0x3c5d51ce, dl));
3841 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3842 getF32Constant(DAG, 0x3e00685a, dl));
3843 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3844 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3845 getF32Constant(DAG, 0x3efb6798, dl));
3846 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3847 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3848 getF32Constant(DAG, 0x3f88d192, dl));
3849 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3850 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3851 getF32Constant(DAG, 0x3fc4316c, dl));
3852 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3853 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3854 getF32Constant(DAG, 0x3f57ce70, dl));
3857 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
3860 // No special expansion.
3861 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
3864 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3865 /// limited-precision mode.
3866 static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
3867 const TargetLowering &TLI) {
3868 if (Op.getValueType() == MVT::f32 &&
3869 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
3870 return getLimitedPrecisionExp2(Op, dl, DAG);
3872 // No special expansion.
3873 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
3876 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3877 /// limited-precision mode with x == 10.0f.
3878 static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
3879 SelectionDAG &DAG, const TargetLowering &TLI) {
3880 bool IsExp10 = false;
3881 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
3882 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3883 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
3885 IsExp10 = LHSC->isExactlyValue(Ten);
3890 // Put the exponent in the right bit position for later addition to the
3893 // #define LOG2OF10 3.3219281f
3894 // t0 = Op * LOG2OF10;
3895 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
3896 getF32Constant(DAG, 0x40549a78, dl));
3897 return getLimitedPrecisionExp2(t0, dl, DAG);
3900 // No special expansion.
3901 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
3905 /// ExpandPowI - Expand a llvm.powi intrinsic.
3906 static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
3907 SelectionDAG &DAG) {
3908 // If RHS is a constant, we can expand this out to a multiplication tree,
3909 // otherwise we end up lowering to a call to __powidf2 (for example). When
3910 // optimizing for size, we only want to do this if the expansion would produce
3911 // a small number of multiplies, otherwise we do the full expansion.
3912 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3913 // Get the exponent as a positive value.
3914 unsigned Val = RHSC->getSExtValue();
3915 if ((int)Val < 0) Val = -Val;
3917 // powi(x, 0) -> 1.0
3919 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
3921 const Function *F = DAG.getMachineFunction().getFunction();
3922 if (!F->hasFnAttribute(Attribute::OptimizeForSize) ||
3923 // If optimizing for size, don't insert too many multiplies. This
3924 // inserts up to 5 multiplies.
3925 countPopulation(Val) + Log2_32(Val) < 7) {
3926 // We use the simple binary decomposition method to generate the multiply
3927 // sequence. There are more optimal ways to do this (for example,
3928 // powi(x,15) generates one more multiply than it should), but this has
3929 // the benefit of being both really simple and much better than a libcall.
3930 SDValue Res; // Logically starts equal to 1.0
3931 SDValue CurSquare = LHS;
3935 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3937 Res = CurSquare; // 1.0*CurSquare.
3940 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3941 CurSquare, CurSquare);
3945 // If the original was negative, invert the result, producing 1/(x*x*x).
3946 if (RHSC->getSExtValue() < 0)
3947 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3948 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
3953 // Otherwise, expand to a libcall.
3954 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3957 // getTruncatedArgReg - Find underlying register used for an truncated
3959 static unsigned getTruncatedArgReg(const SDValue &N) {
3960 if (N.getOpcode() != ISD::TRUNCATE)
3963 const SDValue &Ext = N.getOperand(0);
3964 if (Ext.getOpcode() == ISD::AssertZext ||
3965 Ext.getOpcode() == ISD::AssertSext) {
3966 const SDValue &CFR = Ext.getOperand(0);
3967 if (CFR.getOpcode() == ISD::CopyFromReg)
3968 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
3969 if (CFR.getOpcode() == ISD::TRUNCATE)
3970 return getTruncatedArgReg(CFR);
3975 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
3976 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
3977 /// At the end of instruction selection, they will be inserted to the entry BB.
3978 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
3979 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
3980 DILocation *DL, int64_t Offset, bool IsIndirect, const SDValue &N) {
3981 const Argument *Arg = dyn_cast<Argument>(V);
3985 MachineFunction &MF = DAG.getMachineFunction();
3986 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
3988 // Ignore inlined function arguments here.
3990 // FIXME: Should we be checking DL->inlinedAt() to determine this?
3991 if (!Variable->getScope()->getSubprogram()->describes(MF.getFunction()))
3994 Optional<MachineOperand> Op;
3995 // Some arguments' frame index is recorded during argument lowering.
3996 if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
3997 Op = MachineOperand::CreateFI(FI);
3999 if (!Op && N.getNode()) {
4001 if (N.getOpcode() == ISD::CopyFromReg)
4002 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4004 Reg = getTruncatedArgReg(N);
4005 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4006 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4007 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4012 Op = MachineOperand::CreateReg(Reg, false);
4016 // Check if ValueMap has reg number.
4017 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4018 if (VMI != FuncInfo.ValueMap.end())
4019 Op = MachineOperand::CreateReg(VMI->second, false);
4022 if (!Op && N.getNode())
4023 // Check if frame index is available.
4024 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4025 if (FrameIndexSDNode *FINode =
4026 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4027 Op = MachineOperand::CreateFI(FINode->getIndex());
4032 assert(Variable->isValidLocationForIntrinsic(DL) &&
4033 "Expected inlined-at fields to agree");
4035 FuncInfo.ArgDbgValues.push_back(
4036 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
4037 Op->getReg(), Offset, Variable, Expr));
4039 FuncInfo.ArgDbgValues.push_back(
4040 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE))
4043 .addMetadata(Variable)
4044 .addMetadata(Expr));
4049 // VisualStudio defines setjmp as _setjmp
4050 #if defined(_MSC_VER) && defined(setjmp) && \
4051 !defined(setjmp_undefined_for_msvc)
4052 # pragma push_macro("setjmp")
4054 # define setjmp_undefined_for_msvc
4057 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4058 /// we want to emit this as a call to a named external function, return the name
4059 /// otherwise lower it and return null.
4061 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4062 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4063 SDLoc sdl = getCurSDLoc();
4064 DebugLoc dl = getCurDebugLoc();
4067 switch (Intrinsic) {
4069 // By default, turn this into a target intrinsic node.
4070 visitTargetIntrinsic(I, Intrinsic);
4072 case Intrinsic::vastart: visitVAStart(I); return nullptr;
4073 case Intrinsic::vaend: visitVAEnd(I); return nullptr;
4074 case Intrinsic::vacopy: visitVACopy(I); return nullptr;
4075 case Intrinsic::returnaddress:
4076 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI.getPointerTy(),
4077 getValue(I.getArgOperand(0))));
4079 case Intrinsic::frameaddress:
4080 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4081 getValue(I.getArgOperand(0))));
4083 case Intrinsic::read_register: {
4084 Value *Reg = I.getArgOperand(0);
4085 SDValue Chain = getRoot();
4087 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4088 EVT VT = TLI.getValueType(I.getType());
4089 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
4090 DAG.getVTList(VT, MVT::Other), Chain, RegName);
4092 DAG.setRoot(Res.getValue(1));
4095 case Intrinsic::write_register: {
4096 Value *Reg = I.getArgOperand(0);
4097 Value *RegValue = I.getArgOperand(1);
4098 SDValue Chain = getRoot();
4100 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
4101 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
4102 RegName, getValue(RegValue)));
4105 case Intrinsic::setjmp:
4106 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
4107 case Intrinsic::longjmp:
4108 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
4109 case Intrinsic::memcpy: {
4110 // FIXME: this definition of "user defined address space" is x86-specific
4111 // Assert for address < 256 since we support only user defined address
4113 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4115 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4117 "Unknown address space");
4118 SDValue Op1 = getValue(I.getArgOperand(0));
4119 SDValue Op2 = getValue(I.getArgOperand(1));
4120 SDValue Op3 = getValue(I.getArgOperand(2));
4121 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4123 Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
4124 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4125 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4126 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4128 MachinePointerInfo(I.getArgOperand(0)),
4129 MachinePointerInfo(I.getArgOperand(1)));
4130 updateDAGForMaybeTailCall(MC);
4133 case Intrinsic::memset: {
4134 // FIXME: this definition of "user defined address space" is x86-specific
4135 // Assert for address < 256 since we support only user defined address
4137 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4139 "Unknown address space");
4140 SDValue Op1 = getValue(I.getArgOperand(0));
4141 SDValue Op2 = getValue(I.getArgOperand(1));
4142 SDValue Op3 = getValue(I.getArgOperand(2));
4143 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4145 Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
4146 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4147 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4148 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4149 isTC, MachinePointerInfo(I.getArgOperand(0)));
4150 updateDAGForMaybeTailCall(MS);
4153 case Intrinsic::memmove: {
4154 // FIXME: this definition of "user defined address space" is x86-specific
4155 // Assert for address < 256 since we support only user defined address
4157 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4159 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4161 "Unknown address space");
4162 SDValue Op1 = getValue(I.getArgOperand(0));
4163 SDValue Op2 = getValue(I.getArgOperand(1));
4164 SDValue Op3 = getValue(I.getArgOperand(2));
4165 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4167 Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
4168 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4169 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
4170 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
4171 isTC, MachinePointerInfo(I.getArgOperand(0)),
4172 MachinePointerInfo(I.getArgOperand(1)));
4173 updateDAGForMaybeTailCall(MM);
4176 case Intrinsic::dbg_declare: {
4177 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4178 DILocalVariable *Variable = DI.getVariable();
4179 DIExpression *Expression = DI.getExpression();
4180 const Value *Address = DI.getAddress();
4181 assert(Variable && "Missing variable");
4183 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4187 // Check if address has undef value.
4188 if (isa<UndefValue>(Address) ||
4189 (Address->use_empty() && !isa<Argument>(Address))) {
4190 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4194 SDValue &N = NodeMap[Address];
4195 if (!N.getNode() && isa<Argument>(Address))
4196 // Check unused arguments map.
4197 N = UnusedArgNodeMap[Address];
4200 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4201 Address = BCI->getOperand(0);
4202 // Parameters are handled specially.
4203 bool isParameter = Variable->getTag() == dwarf::DW_TAG_arg_variable ||
4204 isa<Argument>(Address);
4206 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4208 if (isParameter && !AI) {
4209 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4211 // Byval parameter. We have a frame index at this point.
4212 SDV = DAG.getFrameIndexDbgValue(
4213 Variable, Expression, FINode->getIndex(), 0, dl, SDNodeOrder);
4215 // Address is an argument, so try to emit its dbg value using
4216 // virtual register info from the FuncInfo.ValueMap.
4217 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4222 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4223 true, 0, dl, SDNodeOrder);
4225 // Can't do anything with other non-AI cases yet.
4226 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4227 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4228 DEBUG(Address->dump());
4231 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4233 // If Address is an argument then try to emit its dbg value using
4234 // virtual register info from the FuncInfo.ValueMap.
4235 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, 0, false,
4237 // If variable is pinned by a alloca in dominating bb then
4238 // use StaticAllocaMap.
4239 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4240 if (AI->getParent() != DI.getParent()) {
4241 DenseMap<const AllocaInst*, int>::iterator SI =
4242 FuncInfo.StaticAllocaMap.find(AI);
4243 if (SI != FuncInfo.StaticAllocaMap.end()) {
4244 SDV = DAG.getFrameIndexDbgValue(Variable, Expression, SI->second,
4245 0, dl, SDNodeOrder);
4246 DAG.AddDbgValue(SDV, nullptr, false);
4251 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4256 case Intrinsic::dbg_value: {
4257 const DbgValueInst &DI = cast<DbgValueInst>(I);
4258 assert(DI.getVariable() && "Missing variable");
4260 DILocalVariable *Variable = DI.getVariable();
4261 DIExpression *Expression = DI.getExpression();
4262 uint64_t Offset = DI.getOffset();
4263 const Value *V = DI.getValue();
4268 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
4269 SDV = DAG.getConstantDbgValue(Variable, Expression, V, Offset, dl,
4271 DAG.AddDbgValue(SDV, nullptr, false);
4273 // Do not use getValue() in here; we don't want to generate code at
4274 // this point if it hasn't been done yet.
4275 SDValue N = NodeMap[V];
4276 if (!N.getNode() && isa<Argument>(V))
4277 // Check unused arguments map.
4278 N = UnusedArgNodeMap[V];
4280 // A dbg.value for an alloca is always indirect.
4281 bool IsIndirect = isa<AllocaInst>(V) || Offset != 0;
4282 if (!EmitFuncArgumentDbgValue(V, Variable, Expression, dl, Offset,
4284 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
4285 IsIndirect, Offset, dl, SDNodeOrder);
4286 DAG.AddDbgValue(SDV, N.getNode(), false);
4288 } else if (!V->use_empty() ) {
4289 // Do not call getValue(V) yet, as we don't want to generate code.
4290 // Remember it for later.
4291 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4292 DanglingDebugInfoMap[V] = DDI;
4294 // We may expand this to cover more cases. One case where we have no
4295 // data available is an unreferenced parameter.
4296 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
4300 // Build a debug info table entry.
4301 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4302 V = BCI->getOperand(0);
4303 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4304 // Don't handle byval struct arguments or VLAs, for example.
4306 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4307 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
4310 DenseMap<const AllocaInst*, int>::iterator SI =
4311 FuncInfo.StaticAllocaMap.find(AI);
4312 if (SI == FuncInfo.StaticAllocaMap.end())
4313 return nullptr; // VLAs.
4317 case Intrinsic::eh_typeid_for: {
4318 // Find the type id for the given typeinfo.
4319 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
4320 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4321 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
4326 case Intrinsic::eh_return_i32:
4327 case Intrinsic::eh_return_i64:
4328 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4329 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
4332 getValue(I.getArgOperand(0)),
4333 getValue(I.getArgOperand(1))));
4335 case Intrinsic::eh_unwind_init:
4336 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4338 case Intrinsic::eh_dwarf_cfa: {
4339 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
4340 TLI.getPointerTy());
4341 SDValue Offset = DAG.getNode(ISD::ADD, sdl,
4342 CfaArg.getValueType(),
4343 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
4344 CfaArg.getValueType()),
4346 SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl, TLI.getPointerTy(),
4347 DAG.getConstant(0, sdl, TLI.getPointerTy()));
4348 setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
4352 case Intrinsic::eh_sjlj_callsite: {
4353 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4354 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4355 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4356 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4358 MMI.setCurrentCallSite(CI->getZExtValue());
4361 case Intrinsic::eh_sjlj_functioncontext: {
4362 // Get and store the index of the function context.
4363 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4365 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
4366 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4367 MFI->setFunctionContextIndex(FI);
4370 case Intrinsic::eh_sjlj_setjmp: {
4373 Ops[1] = getValue(I.getArgOperand(0));
4374 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
4375 DAG.getVTList(MVT::i32, MVT::Other), Ops);
4376 setValue(&I, Op.getValue(0));
4377 DAG.setRoot(Op.getValue(1));
4380 case Intrinsic::eh_sjlj_longjmp: {
4381 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
4382 getRoot(), getValue(I.getArgOperand(0))));
4386 case Intrinsic::masked_gather:
4387 visitMaskedGather(I);
4389 case Intrinsic::masked_load:
4392 case Intrinsic::masked_scatter:
4393 visitMaskedScatter(I);
4395 case Intrinsic::masked_store:
4396 visitMaskedStore(I);
4398 case Intrinsic::x86_mmx_pslli_w:
4399 case Intrinsic::x86_mmx_pslli_d:
4400 case Intrinsic::x86_mmx_pslli_q:
4401 case Intrinsic::x86_mmx_psrli_w:
4402 case Intrinsic::x86_mmx_psrli_d:
4403 case Intrinsic::x86_mmx_psrli_q:
4404 case Intrinsic::x86_mmx_psrai_w:
4405 case Intrinsic::x86_mmx_psrai_d: {
4406 SDValue ShAmt = getValue(I.getArgOperand(1));
4407 if (isa<ConstantSDNode>(ShAmt)) {
4408 visitTargetIntrinsic(I, Intrinsic);
4411 unsigned NewIntrinsic = 0;
4412 EVT ShAmtVT = MVT::v2i32;
4413 switch (Intrinsic) {
4414 case Intrinsic::x86_mmx_pslli_w:
4415 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4417 case Intrinsic::x86_mmx_pslli_d:
4418 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4420 case Intrinsic::x86_mmx_pslli_q:
4421 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4423 case Intrinsic::x86_mmx_psrli_w:
4424 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4426 case Intrinsic::x86_mmx_psrli_d:
4427 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4429 case Intrinsic::x86_mmx_psrli_q:
4430 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4432 case Intrinsic::x86_mmx_psrai_w:
4433 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4435 case Intrinsic::x86_mmx_psrai_d:
4436 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4438 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4441 // The vector shift intrinsics with scalars uses 32b shift amounts but
4442 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4444 // We must do this early because v2i32 is not a legal type.
4447 ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
4448 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, ShOps);
4449 EVT DestVT = TLI.getValueType(I.getType());
4450 ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
4451 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
4452 DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
4453 getValue(I.getArgOperand(0)), ShAmt);
4457 case Intrinsic::convertff:
4458 case Intrinsic::convertfsi:
4459 case Intrinsic::convertfui:
4460 case Intrinsic::convertsif:
4461 case Intrinsic::convertuif:
4462 case Intrinsic::convertss:
4463 case Intrinsic::convertsu:
4464 case Intrinsic::convertus:
4465 case Intrinsic::convertuu: {
4466 ISD::CvtCode Code = ISD::CVT_INVALID;
4467 switch (Intrinsic) {
4468 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4469 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4470 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4471 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4472 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4473 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4474 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4475 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4476 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4477 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4479 EVT DestVT = TLI.getValueType(I.getType());
4480 const Value *Op1 = I.getArgOperand(0);
4481 Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
4482 DAG.getValueType(DestVT),
4483 DAG.getValueType(getValue(Op1).getValueType()),
4484 getValue(I.getArgOperand(1)),
4485 getValue(I.getArgOperand(2)),
4490 case Intrinsic::powi:
4491 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
4492 getValue(I.getArgOperand(1)), DAG));
4494 case Intrinsic::log:
4495 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4497 case Intrinsic::log2:
4498 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4500 case Intrinsic::log10:
4501 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4503 case Intrinsic::exp:
4504 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4506 case Intrinsic::exp2:
4507 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
4509 case Intrinsic::pow:
4510 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
4511 getValue(I.getArgOperand(1)), DAG, TLI));
4513 case Intrinsic::sqrt:
4514 case Intrinsic::fabs:
4515 case Intrinsic::sin:
4516 case Intrinsic::cos:
4517 case Intrinsic::floor:
4518 case Intrinsic::ceil:
4519 case Intrinsic::trunc:
4520 case Intrinsic::rint:
4521 case Intrinsic::nearbyint:
4522 case Intrinsic::round: {
4524 switch (Intrinsic) {
4525 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4526 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
4527 case Intrinsic::fabs: Opcode = ISD::FABS; break;
4528 case Intrinsic::sin: Opcode = ISD::FSIN; break;
4529 case Intrinsic::cos: Opcode = ISD::FCOS; break;
4530 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
4531 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
4532 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
4533 case Intrinsic::rint: Opcode = ISD::FRINT; break;
4534 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
4535 case Intrinsic::round: Opcode = ISD::FROUND; break;
4538 setValue(&I, DAG.getNode(Opcode, sdl,
4539 getValue(I.getArgOperand(0)).getValueType(),
4540 getValue(I.getArgOperand(0))));
4543 case Intrinsic::minnum:
4544 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
4545 getValue(I.getArgOperand(0)).getValueType(),
4546 getValue(I.getArgOperand(0)),
4547 getValue(I.getArgOperand(1))));
4549 case Intrinsic::maxnum:
4550 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
4551 getValue(I.getArgOperand(0)).getValueType(),
4552 getValue(I.getArgOperand(0)),
4553 getValue(I.getArgOperand(1))));
4555 case Intrinsic::copysign:
4556 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
4557 getValue(I.getArgOperand(0)).getValueType(),
4558 getValue(I.getArgOperand(0)),
4559 getValue(I.getArgOperand(1))));
4561 case Intrinsic::fma:
4562 setValue(&I, DAG.getNode(ISD::FMA, sdl,
4563 getValue(I.getArgOperand(0)).getValueType(),
4564 getValue(I.getArgOperand(0)),
4565 getValue(I.getArgOperand(1)),
4566 getValue(I.getArgOperand(2))));
4568 case Intrinsic::fmuladd: {
4569 EVT VT = TLI.getValueType(I.getType());
4570 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
4571 TLI.isFMAFasterThanFMulAndFAdd(VT)) {
4572 setValue(&I, DAG.getNode(ISD::FMA, sdl,
4573 getValue(I.getArgOperand(0)).getValueType(),
4574 getValue(I.getArgOperand(0)),
4575 getValue(I.getArgOperand(1)),
4576 getValue(I.getArgOperand(2))));
4578 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
4579 getValue(I.getArgOperand(0)).getValueType(),
4580 getValue(I.getArgOperand(0)),
4581 getValue(I.getArgOperand(1)));
4582 SDValue Add = DAG.getNode(ISD::FADD, sdl,
4583 getValue(I.getArgOperand(0)).getValueType(),
4585 getValue(I.getArgOperand(2)));
4590 case Intrinsic::convert_to_fp16:
4591 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
4592 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
4593 getValue(I.getArgOperand(0)),
4594 DAG.getTargetConstant(0, sdl,
4597 case Intrinsic::convert_from_fp16:
4599 DAG.getNode(ISD::FP_EXTEND, sdl, TLI.getValueType(I.getType()),
4600 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
4601 getValue(I.getArgOperand(0)))));
4603 case Intrinsic::pcmarker: {
4604 SDValue Tmp = getValue(I.getArgOperand(0));
4605 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
4608 case Intrinsic::readcyclecounter: {
4609 SDValue Op = getRoot();
4610 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
4611 DAG.getVTList(MVT::i64, MVT::Other), Op);
4613 DAG.setRoot(Res.getValue(1));
4616 case Intrinsic::bswap:
4617 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
4618 getValue(I.getArgOperand(0)).getValueType(),
4619 getValue(I.getArgOperand(0))));
4621 case Intrinsic::cttz: {
4622 SDValue Arg = getValue(I.getArgOperand(0));
4623 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
4624 EVT Ty = Arg.getValueType();
4625 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
4629 case Intrinsic::ctlz: {
4630 SDValue Arg = getValue(I.getArgOperand(0));
4631 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
4632 EVT Ty = Arg.getValueType();
4633 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
4637 case Intrinsic::ctpop: {
4638 SDValue Arg = getValue(I.getArgOperand(0));
4639 EVT Ty = Arg.getValueType();
4640 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
4643 case Intrinsic::stacksave: {
4644 SDValue Op = getRoot();
4645 Res = DAG.getNode(ISD::STACKSAVE, sdl,
4646 DAG.getVTList(TLI.getPointerTy(), MVT::Other), Op);
4648 DAG.setRoot(Res.getValue(1));
4651 case Intrinsic::stackrestore: {
4652 Res = getValue(I.getArgOperand(0));
4653 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
4656 case Intrinsic::stackprotector: {
4657 // Emit code into the DAG to store the stack guard onto the stack.
4658 MachineFunction &MF = DAG.getMachineFunction();
4659 MachineFrameInfo *MFI = MF.getFrameInfo();
4660 EVT PtrTy = TLI.getPointerTy();
4661 SDValue Src, Chain = getRoot();
4662 const Value *Ptr = cast<LoadInst>(I.getArgOperand(0))->getPointerOperand();
4663 const GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr);
4665 // See if Ptr is a bitcast. If it is, look through it and see if we can get
4666 // global variable __stack_chk_guard.
4668 if (const Operator *BC = dyn_cast<Operator>(Ptr))
4669 if (BC->getOpcode() == Instruction::BitCast)
4670 GV = dyn_cast<GlobalVariable>(BC->getOperand(0));
4672 if (GV && TLI.useLoadStackGuardNode()) {
4673 // Emit a LOAD_STACK_GUARD node.
4674 MachineSDNode *Node = DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD,
4676 MachinePointerInfo MPInfo(GV);
4677 MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
4678 unsigned Flags = MachineMemOperand::MOLoad |
4679 MachineMemOperand::MOInvariant;
4680 *MemRefs = MF.getMachineMemOperand(MPInfo, Flags,
4681 PtrTy.getSizeInBits() / 8,
4682 DAG.getEVTAlignment(PtrTy));
4683 Node->setMemRefs(MemRefs, MemRefs + 1);
4685 // Copy the guard value to a virtual register so that it can be
4686 // retrieved in the epilogue.
4687 Src = SDValue(Node, 0);
4688 const TargetRegisterClass *RC =
4689 TLI.getRegClassFor(Src.getSimpleValueType());
4690 unsigned Reg = MF.getRegInfo().createVirtualRegister(RC);
4692 SPDescriptor.setGuardReg(Reg);
4693 Chain = DAG.getCopyToReg(Chain, sdl, Reg, Src);
4695 Src = getValue(I.getArgOperand(0)); // The guard's value.
4698 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4700 int FI = FuncInfo.StaticAllocaMap[Slot];
4701 MFI->setStackProtectorIndex(FI);
4703 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4705 // Store the stack protector onto the stack.
4706 Res = DAG.getStore(Chain, sdl, Src, FIN,
4707 MachinePointerInfo::getFixedStack(FI),
4713 case Intrinsic::objectsize: {
4714 // If we don't know by now, we're never going to know.
4715 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
4717 assert(CI && "Non-constant type in __builtin_object_size?");
4719 SDValue Arg = getValue(I.getCalledValue());
4720 EVT Ty = Arg.getValueType();
4723 Res = DAG.getConstant(-1ULL, sdl, Ty);
4725 Res = DAG.getConstant(0, sdl, Ty);
4730 case Intrinsic::annotation:
4731 case Intrinsic::ptr_annotation:
4732 // Drop the intrinsic, but forward the value
4733 setValue(&I, getValue(I.getOperand(0)));
4735 case Intrinsic::assume:
4736 case Intrinsic::var_annotation:
4737 // Discard annotate attributes and assumptions
4740 case Intrinsic::init_trampoline: {
4741 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
4745 Ops[1] = getValue(I.getArgOperand(0));
4746 Ops[2] = getValue(I.getArgOperand(1));
4747 Ops[3] = getValue(I.getArgOperand(2));
4748 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
4749 Ops[5] = DAG.getSrcValue(F);
4751 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
4756 case Intrinsic::adjust_trampoline: {
4757 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
4759 getValue(I.getArgOperand(0))));
4762 case Intrinsic::gcroot:
4764 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
4765 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
4767 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4768 GFI->addStackRoot(FI->getIndex(), TypeMap);
4771 case Intrinsic::gcread:
4772 case Intrinsic::gcwrite:
4773 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4774 case Intrinsic::flt_rounds:
4775 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
4778 case Intrinsic::expect: {
4779 // Just replace __builtin_expect(exp, c) with EXP.
4780 setValue(&I, getValue(I.getArgOperand(0)));
4784 case Intrinsic::debugtrap:
4785 case Intrinsic::trap: {
4786 StringRef TrapFuncName =
4788 .getAttribute(AttributeSet::FunctionIndex, "trap-func-name")
4789 .getValueAsString();
4790 if (TrapFuncName.empty()) {
4791 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
4792 ISD::TRAP : ISD::DEBUGTRAP;
4793 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
4796 TargetLowering::ArgListTy Args;
4798 TargetLowering::CallLoweringInfo CLI(DAG);
4799 CLI.setDebugLoc(sdl).setChain(getRoot())
4800 .setCallee(CallingConv::C, I.getType(),
4801 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
4802 std::move(Args), 0);
4804 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
4805 DAG.setRoot(Result.second);
4809 case Intrinsic::uadd_with_overflow:
4810 case Intrinsic::sadd_with_overflow:
4811 case Intrinsic::usub_with_overflow:
4812 case Intrinsic::ssub_with_overflow:
4813 case Intrinsic::umul_with_overflow:
4814 case Intrinsic::smul_with_overflow: {
4816 switch (Intrinsic) {
4817 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4818 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
4819 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
4820 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
4821 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
4822 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
4823 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
4825 SDValue Op1 = getValue(I.getArgOperand(0));
4826 SDValue Op2 = getValue(I.getArgOperand(1));
4828 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
4829 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
4832 case Intrinsic::prefetch: {
4834 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4836 Ops[1] = getValue(I.getArgOperand(0));
4837 Ops[2] = getValue(I.getArgOperand(1));
4838 Ops[3] = getValue(I.getArgOperand(2));
4839 Ops[4] = getValue(I.getArgOperand(3));
4840 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
4841 DAG.getVTList(MVT::Other), Ops,
4842 EVT::getIntegerVT(*Context, 8),
4843 MachinePointerInfo(I.getArgOperand(0)),
4845 false, /* volatile */
4847 rw==1)); /* write */
4850 case Intrinsic::lifetime_start:
4851 case Intrinsic::lifetime_end: {
4852 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
4853 // Stack coloring is not enabled in O0, discard region information.
4854 if (TM.getOptLevel() == CodeGenOpt::None)
4857 SmallVector<Value *, 4> Allocas;
4858 GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
4860 for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
4861 E = Allocas.end(); Object != E; ++Object) {
4862 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
4864 // Could not find an Alloca.
4865 if (!LifetimeObject)
4868 // First check that the Alloca is static, otherwise it won't have a
4869 // valid frame index.
4870 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
4871 if (SI == FuncInfo.StaticAllocaMap.end())
4874 int FI = SI->second;
4878 Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
4879 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
4881 Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
4886 case Intrinsic::invariant_start:
4887 // Discard region information.
4888 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4890 case Intrinsic::invariant_end:
4891 // Discard region information.
4893 case Intrinsic::stackprotectorcheck: {
4894 // Do not actually emit anything for this basic block. Instead we initialize
4895 // the stack protector descriptor and export the guard variable so we can
4896 // access it in FinishBasicBlock.
4897 const BasicBlock *BB = I.getParent();
4898 SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
4899 ExportFromCurrentBlock(SPDescriptor.getGuard());
4901 // Flush our exports since we are going to process a terminator.
4902 (void)getControlRoot();
4905 case Intrinsic::clear_cache:
4906 return TLI.getClearCacheBuiltinName();
4907 case Intrinsic::eh_actions:
4908 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4910 case Intrinsic::donothing:
4913 case Intrinsic::experimental_stackmap: {
4917 case Intrinsic::experimental_patchpoint_void:
4918 case Intrinsic::experimental_patchpoint_i64: {
4919 visitPatchpoint(&I);
4922 case Intrinsic::experimental_gc_statepoint: {
4926 case Intrinsic::experimental_gc_result_int:
4927 case Intrinsic::experimental_gc_result_float:
4928 case Intrinsic::experimental_gc_result_ptr:
4929 case Intrinsic::experimental_gc_result: {
4933 case Intrinsic::experimental_gc_relocate: {
4937 case Intrinsic::instrprof_increment:
4938 llvm_unreachable("instrprof failed to lower an increment");
4940 case Intrinsic::localescape: {
4941 MachineFunction &MF = DAG.getMachineFunction();
4942 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4944 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
4945 // is the same on all targets.
4946 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
4947 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
4948 if (isa<ConstantPointerNull>(Arg))
4949 continue; // Skip null pointers. They represent a hole in index space.
4950 AllocaInst *Slot = cast<AllocaInst>(Arg);
4951 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
4952 "can only escape static allocas");
4953 int FI = FuncInfo.StaticAllocaMap[Slot];
4954 MCSymbol *FrameAllocSym =
4955 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
4956 GlobalValue::getRealLinkageName(MF.getName()), Idx);
4957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
4958 TII->get(TargetOpcode::LOCAL_ESCAPE))
4959 .addSym(FrameAllocSym)
4966 case Intrinsic::localrecover: {
4967 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
4968 MachineFunction &MF = DAG.getMachineFunction();
4969 MVT PtrVT = TLI.getPointerTy(0);
4971 // Get the symbol that defines the frame offset.
4972 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
4973 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
4974 unsigned IdxVal = unsigned(Idx->getLimitedValue(INT_MAX));
4975 MCSymbol *FrameAllocSym =
4976 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
4977 GlobalValue::getRealLinkageName(Fn->getName()), IdxVal);
4979 // Create a MCSymbol for the label to avoid any target lowering
4980 // that would make this PC relative.
4981 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
4983 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
4985 // Add the offset to the FP.
4986 Value *FP = I.getArgOperand(1);
4987 SDValue FPVal = getValue(FP);
4988 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
4993 case Intrinsic::eh_begincatch:
4994 case Intrinsic::eh_endcatch:
4995 llvm_unreachable("begin/end catch intrinsics not lowered in codegen");
4996 case Intrinsic::eh_exceptioncode: {
4997 unsigned Reg = TLI.getExceptionPointerRegister();
4998 assert(Reg && "cannot get exception code on this platform");
4999 MVT PtrVT = TLI.getPointerTy();
5000 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
5001 assert(FuncInfo.MBB->isLandingPad() && "eh.exceptioncode in non-lpad");
5002 unsigned VReg = FuncInfo.MBB->addLiveIn(Reg, PtrRC);
5004 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
5005 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
5012 std::pair<SDValue, SDValue>
5013 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
5014 MachineBasicBlock *LandingPad) {
5015 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5016 MCSymbol *BeginLabel = nullptr;
5019 // Insert a label before the invoke call to mark the try range. This can be
5020 // used to detect deletion of the invoke via the MachineModuleInfo.
5021 BeginLabel = MMI.getContext().createTempSymbol();
5023 // For SjLj, keep track of which landing pads go with which invokes
5024 // so as to maintain the ordering of pads in the LSDA.
5025 unsigned CallSiteIndex = MMI.getCurrentCallSite();
5026 if (CallSiteIndex) {
5027 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
5028 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
5030 // Now that the call site is handled, stop tracking it.
5031 MMI.setCurrentCallSite(0);
5034 // Both PendingLoads and PendingExports must be flushed here;
5035 // this call might not return.
5037 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
5039 CLI.setChain(getRoot());
5041 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5042 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
5044 assert((CLI.IsTailCall || Result.second.getNode()) &&
5045 "Non-null chain expected with non-tail call!");
5046 assert((Result.second.getNode() || !Result.first.getNode()) &&
5047 "Null value expected with tail call!");
5049 if (!Result.second.getNode()) {
5050 // As a special case, a null chain means that a tail call has been emitted
5051 // and the DAG root is already updated.
5054 // Since there's no actual continuation from this block, nothing can be
5055 // relying on us setting vregs for them.
5056 PendingExports.clear();
5058 DAG.setRoot(Result.second);
5062 // Insert a label at the end of the invoke call to mark the try range. This
5063 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5064 MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
5065 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
5067 // Inform MachineModuleInfo of range.
5068 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5074 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
5076 MachineBasicBlock *LandingPad) {
5077 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5078 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5079 Type *RetTy = FTy->getReturnType();
5081 TargetLowering::ArgListTy Args;
5082 TargetLowering::ArgListEntry Entry;
5083 Args.reserve(CS.arg_size());
5085 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
5087 const Value *V = *i;
5090 if (V->getType()->isEmptyTy())
5093 SDValue ArgNode = getValue(V);
5094 Entry.Node = ArgNode; Entry.Ty = V->getType();
5096 // Skip the first return-type Attribute to get to params.
5097 Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
5098 Args.push_back(Entry);
5100 // If we have an explicit sret argument that is an Instruction, (i.e., it
5101 // might point to function-local memory), we can't meaningfully tail-call.
5102 if (Entry.isSRet && isa<Instruction>(V))
5106 // Check if target-independent constraints permit a tail call here.
5107 // Target-dependent constraints are checked within TLI->LowerCallTo.
5108 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
5111 TargetLowering::CallLoweringInfo CLI(DAG);
5112 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
5113 .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
5114 .setTailCall(isTailCall);
5115 std::pair<SDValue,SDValue> Result = lowerInvokable(CLI, LandingPad);
5117 if (Result.first.getNode())
5118 setValue(CS.getInstruction(), Result.first);
5121 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5122 /// value is equal or not-equal to zero.
5123 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5124 for (const User *U : V->users()) {
5125 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
5126 if (IC->isEquality())
5127 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5128 if (C->isNullValue())
5130 // Unknown instruction.
5136 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5138 SelectionDAGBuilder &Builder) {
5140 // Check to see if this load can be trivially constant folded, e.g. if the
5141 // input is from a string literal.
5142 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5143 // Cast pointer to the type we really want to load.
5144 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5145 PointerType::getUnqual(LoadTy));
5147 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
5148 const_cast<Constant *>(LoadInput), *Builder.DL))
5149 return Builder.getValue(LoadCst);
5152 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5153 // still constant memory, the input chain can be the entry node.
5155 bool ConstantMemory = false;
5157 // Do not serialize (non-volatile) loads of constant memory with anything.
5158 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5159 Root = Builder.DAG.getEntryNode();
5160 ConstantMemory = true;
5162 // Do not serialize non-volatile loads against each other.
5163 Root = Builder.DAG.getRoot();
5166 SDValue Ptr = Builder.getValue(PtrVal);
5167 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
5168 Ptr, MachinePointerInfo(PtrVal),
5170 false /*nontemporal*/,
5171 false /*isinvariant*/, 1 /* align=1 */);
5173 if (!ConstantMemory)
5174 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5178 /// processIntegerCallValue - Record the value for an instruction that
5179 /// produces an integer result, converting the type where necessary.
5180 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
5183 EVT VT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
5185 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
5187 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
5188 setValue(&I, Value);
5191 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5192 /// If so, return true and lower it, otherwise return false and it will be
5193 /// lowered like a normal call.
5194 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5195 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5196 if (I.getNumArgOperands() != 3)
5199 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5200 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5201 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5202 !I.getType()->isIntegerTy())
5205 const Value *Size = I.getArgOperand(2);
5206 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
5207 if (CSize && CSize->getZExtValue() == 0) {
5208 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(I.getType(), true);
5209 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
5213 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5214 std::pair<SDValue, SDValue> Res =
5215 TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5216 getValue(LHS), getValue(RHS), getValue(Size),
5217 MachinePointerInfo(LHS),
5218 MachinePointerInfo(RHS));
5219 if (Res.first.getNode()) {
5220 processIntegerCallValue(I, Res.first, true);
5221 PendingLoads.push_back(Res.second);
5225 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5226 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5227 if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
5228 bool ActuallyDoIt = true;
5231 switch (CSize->getZExtValue()) {
5233 LoadVT = MVT::Other;
5235 ActuallyDoIt = false;
5239 LoadTy = Type::getInt16Ty(CSize->getContext());
5243 LoadTy = Type::getInt32Ty(CSize->getContext());
5247 LoadTy = Type::getInt64Ty(CSize->getContext());
5251 LoadVT = MVT::v4i32;
5252 LoadTy = Type::getInt32Ty(CSize->getContext());
5253 LoadTy = VectorType::get(LoadTy, 4);
5258 // This turns into unaligned loads. We only do this if the target natively
5259 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5260 // we'll only produce a small number of byte loads.
5262 // Require that we can find a legal MVT, and only do this if the target
5263 // supports unaligned loads of that type. Expanding into byte loads would
5265 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5266 if (ActuallyDoIt && CSize->getZExtValue() > 4) {
5267 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
5268 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
5269 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5270 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5271 // TODO: Check alignment of src and dest ptrs.
5272 if (!TLI.isTypeLegal(LoadVT) ||
5273 !TLI.allowsMisalignedMemoryAccesses(LoadVT, SrcAS) ||
5274 !TLI.allowsMisalignedMemoryAccesses(LoadVT, DstAS))
5275 ActuallyDoIt = false;
5279 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5280 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5282 SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
5284 processIntegerCallValue(I, Res, false);
5293 /// visitMemChrCall -- See if we can lower a memchr call into an optimized
5294 /// form. If so, return true and lower it, otherwise return false and it
5295 /// will be lowered like a normal call.
5296 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
5297 // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
5298 if (I.getNumArgOperands() != 3)
5301 const Value *Src = I.getArgOperand(0);
5302 const Value *Char = I.getArgOperand(1);
5303 const Value *Length = I.getArgOperand(2);
5304 if (!Src->getType()->isPointerTy() ||
5305 !Char->getType()->isIntegerTy() ||
5306 !Length->getType()->isIntegerTy() ||
5307 !I.getType()->isPointerTy())
5310 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5311 std::pair<SDValue, SDValue> Res =
5312 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
5313 getValue(Src), getValue(Char), getValue(Length),
5314 MachinePointerInfo(Src));
5315 if (Res.first.getNode()) {
5316 setValue(&I, Res.first);
5317 PendingLoads.push_back(Res.second);
5324 /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
5325 /// optimized form. If so, return true and lower it, otherwise return false
5326 /// and it will be lowered like a normal call.
5327 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
5328 // Verify that the prototype makes sense. char *strcpy(char *, char *)
5329 if (I.getNumArgOperands() != 2)
5332 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5333 if (!Arg0->getType()->isPointerTy() ||
5334 !Arg1->getType()->isPointerTy() ||
5335 !I.getType()->isPointerTy())
5338 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5339 std::pair<SDValue, SDValue> Res =
5340 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
5341 getValue(Arg0), getValue(Arg1),
5342 MachinePointerInfo(Arg0),
5343 MachinePointerInfo(Arg1), isStpcpy);
5344 if (Res.first.getNode()) {
5345 setValue(&I, Res.first);
5346 DAG.setRoot(Res.second);
5353 /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
5354 /// If so, return true and lower it, otherwise return false and it will be
5355 /// lowered like a normal call.
5356 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
5357 // Verify that the prototype makes sense. int strcmp(void*,void*)
5358 if (I.getNumArgOperands() != 2)
5361 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5362 if (!Arg0->getType()->isPointerTy() ||
5363 !Arg1->getType()->isPointerTy() ||
5364 !I.getType()->isIntegerTy())
5367 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5368 std::pair<SDValue, SDValue> Res =
5369 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
5370 getValue(Arg0), getValue(Arg1),
5371 MachinePointerInfo(Arg0),
5372 MachinePointerInfo(Arg1));
5373 if (Res.first.getNode()) {
5374 processIntegerCallValue(I, Res.first, true);
5375 PendingLoads.push_back(Res.second);
5382 /// visitStrLenCall -- See if we can lower a strlen call into an optimized
5383 /// form. If so, return true and lower it, otherwise return false and it
5384 /// will be lowered like a normal call.
5385 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
5386 // Verify that the prototype makes sense. size_t strlen(char *)
5387 if (I.getNumArgOperands() != 1)
5390 const Value *Arg0 = I.getArgOperand(0);
5391 if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
5394 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5395 std::pair<SDValue, SDValue> Res =
5396 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
5397 getValue(Arg0), MachinePointerInfo(Arg0));
5398 if (Res.first.getNode()) {
5399 processIntegerCallValue(I, Res.first, false);
5400 PendingLoads.push_back(Res.second);
5407 /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
5408 /// form. If so, return true and lower it, otherwise return false and it
5409 /// will be lowered like a normal call.
5410 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
5411 // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
5412 if (I.getNumArgOperands() != 2)
5415 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
5416 if (!Arg0->getType()->isPointerTy() ||
5417 !Arg1->getType()->isIntegerTy() ||
5418 !I.getType()->isIntegerTy())
5421 const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
5422 std::pair<SDValue, SDValue> Res =
5423 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
5424 getValue(Arg0), getValue(Arg1),
5425 MachinePointerInfo(Arg0));
5426 if (Res.first.getNode()) {
5427 processIntegerCallValue(I, Res.first, false);
5428 PendingLoads.push_back(Res.second);
5435 /// visitUnaryFloatCall - If a call instruction is a unary floating-point
5436 /// operation (as expected), translate it to an SDNode with the specified opcode
5437 /// and return true.
5438 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5440 // Sanity check that it really is a unary floating-point call.
5441 if (I.getNumArgOperands() != 1 ||
5442 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5443 I.getType() != I.getArgOperand(0)->getType() ||
5444 !I.onlyReadsMemory())
5447 SDValue Tmp = getValue(I.getArgOperand(0));
5448 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
5452 /// visitBinaryFloatCall - If a call instruction is a binary floating-point
5453 /// operation (as expected), translate it to an SDNode with the specified opcode
5454 /// and return true.
5455 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
5457 // Sanity check that it really is a binary floating-point call.
5458 if (I.getNumArgOperands() != 2 ||
5459 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5460 I.getType() != I.getArgOperand(0)->getType() ||
5461 I.getType() != I.getArgOperand(1)->getType() ||
5462 !I.onlyReadsMemory())
5465 SDValue Tmp0 = getValue(I.getArgOperand(0));
5466 SDValue Tmp1 = getValue(I.getArgOperand(1));
5467 EVT VT = Tmp0.getValueType();
5468 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
5472 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5473 // Handle inline assembly differently.
5474 if (isa<InlineAsm>(I.getCalledValue())) {
5479 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5480 ComputeUsesVAFloatArgument(I, &MMI);
5482 const char *RenameFn = nullptr;
5483 if (Function *F = I.getCalledFunction()) {
5484 if (F->isDeclaration()) {
5485 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5486 if (unsigned IID = II->getIntrinsicID(F)) {
5487 RenameFn = visitIntrinsicCall(I, IID);
5492 if (Intrinsic::ID IID = F->getIntrinsicID()) {
5493 RenameFn = visitIntrinsicCall(I, IID);
5499 // Check for well-known libc/libm calls. If the function is internal, it
5500 // can't be a library call.
5502 if (!F->hasLocalLinkage() && F->hasName() &&
5503 LibInfo->getLibFunc(F->getName(), Func) &&
5504 LibInfo->hasOptimizedCodeGen(Func)) {
5507 case LibFunc::copysign:
5508 case LibFunc::copysignf:
5509 case LibFunc::copysignl:
5510 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5511 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5512 I.getType() == I.getArgOperand(0)->getType() &&
5513 I.getType() == I.getArgOperand(1)->getType() &&
5514 I.onlyReadsMemory()) {
5515 SDValue LHS = getValue(I.getArgOperand(0));
5516 SDValue RHS = getValue(I.getArgOperand(1));
5517 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
5518 LHS.getValueType(), LHS, RHS));
5523 case LibFunc::fabsf:
5524 case LibFunc::fabsl:
5525 if (visitUnaryFloatCall(I, ISD::FABS))
5529 case LibFunc::fminf:
5530 case LibFunc::fminl:
5531 if (visitBinaryFloatCall(I, ISD::FMINNUM))
5535 case LibFunc::fmaxf:
5536 case LibFunc::fmaxl:
5537 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
5543 if (visitUnaryFloatCall(I, ISD::FSIN))
5549 if (visitUnaryFloatCall(I, ISD::FCOS))
5553 case LibFunc::sqrtf:
5554 case LibFunc::sqrtl:
5555 case LibFunc::sqrt_finite:
5556 case LibFunc::sqrtf_finite:
5557 case LibFunc::sqrtl_finite:
5558 if (visitUnaryFloatCall(I, ISD::FSQRT))
5561 case LibFunc::floor:
5562 case LibFunc::floorf:
5563 case LibFunc::floorl:
5564 if (visitUnaryFloatCall(I, ISD::FFLOOR))
5567 case LibFunc::nearbyint:
5568 case LibFunc::nearbyintf:
5569 case LibFunc::nearbyintl:
5570 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
5574 case LibFunc::ceilf:
5575 case LibFunc::ceill:
5576 if (visitUnaryFloatCall(I, ISD::FCEIL))
5580 case LibFunc::rintf:
5581 case LibFunc::rintl:
5582 if (visitUnaryFloatCall(I, ISD::FRINT))
5585 case LibFunc::round:
5586 case LibFunc::roundf:
5587 case LibFunc::roundl:
5588 if (visitUnaryFloatCall(I, ISD::FROUND))
5591 case LibFunc::trunc:
5592 case LibFunc::truncf:
5593 case LibFunc::truncl:
5594 if (visitUnaryFloatCall(I, ISD::FTRUNC))
5598 case LibFunc::log2f:
5599 case LibFunc::log2l:
5600 if (visitUnaryFloatCall(I, ISD::FLOG2))
5604 case LibFunc::exp2f:
5605 case LibFunc::exp2l:
5606 if (visitUnaryFloatCall(I, ISD::FEXP2))
5609 case LibFunc::memcmp:
5610 if (visitMemCmpCall(I))
5613 case LibFunc::memchr:
5614 if (visitMemChrCall(I))
5617 case LibFunc::strcpy:
5618 if (visitStrCpyCall(I, false))
5621 case LibFunc::stpcpy:
5622 if (visitStrCpyCall(I, true))
5625 case LibFunc::strcmp:
5626 if (visitStrCmpCall(I))
5629 case LibFunc::strlen:
5630 if (visitStrLenCall(I))
5633 case LibFunc::strnlen:
5634 if (visitStrNLenCall(I))
5643 Callee = getValue(I.getCalledValue());
5645 Callee = DAG.getExternalSymbol(RenameFn,
5646 DAG.getTargetLoweringInfo().getPointerTy());
5648 // Check if we can potentially perform a tail call. More detailed checking is
5649 // be done within LowerCallTo, after more information about the call is known.
5650 LowerCallTo(&I, Callee, I.isTailCall());
5655 /// AsmOperandInfo - This contains information for each constraint that we are
5657 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
5659 /// CallOperand - If this is the result output operand or a clobber
5660 /// this is null, otherwise it is the incoming operand to the CallInst.
5661 /// This gets modified as the asm is processed.
5662 SDValue CallOperand;
5664 /// AssignedRegs - If this is a register or register class operand, this
5665 /// contains the set of register corresponding to the operand.
5666 RegsForValue AssignedRegs;
5668 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
5669 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr,0) {
5672 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5673 /// corresponds to. If there is no Value* for this operand, it returns
5675 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
5676 const DataLayout &DL) const {
5677 if (!CallOperandVal) return MVT::Other;
5679 if (isa<BasicBlock>(CallOperandVal))
5680 return TLI.getPointerTy();
5682 llvm::Type *OpTy = CallOperandVal->getType();
5684 // FIXME: code duplicated from TargetLowering::ParseConstraints().
5685 // If this is an indirect operand, the operand is a pointer to the
5688 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5690 report_fatal_error("Indirect operand for inline asm not a pointer!");
5691 OpTy = PtrTy->getElementType();
5694 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5695 if (StructType *STy = dyn_cast<StructType>(OpTy))
5696 if (STy->getNumElements() == 1)
5697 OpTy = STy->getElementType(0);
5699 // If OpTy is not a single value, it may be a struct/union that we
5700 // can tile with integers.
5701 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5702 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
5711 OpTy = IntegerType::get(Context, BitSize);
5716 return TLI.getValueType(OpTy, true);
5720 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5722 } // end anonymous namespace
5724 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5725 /// specified operand. We prefer to assign virtual registers, to allow the
5726 /// register allocator to handle the assignment process. However, if the asm
5727 /// uses features that we can't model on machineinstrs, we have SDISel do the
5728 /// allocation. This produces generally horrible, but correct, code.
5730 /// OpInfo describes the operand.
5732 static void GetRegistersForValue(SelectionDAG &DAG,
5733 const TargetLowering &TLI,
5735 SDISelAsmOperandInfo &OpInfo) {
5736 LLVMContext &Context = *DAG.getContext();
5738 MachineFunction &MF = DAG.getMachineFunction();
5739 SmallVector<unsigned, 4> Regs;
5741 // If this is a constraint for a single physreg, or a constraint for a
5742 // register class, find it.
5743 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
5744 TLI.getRegForInlineAsmConstraint(MF.getSubtarget().getRegisterInfo(),
5745 OpInfo.ConstraintCode,
5746 OpInfo.ConstraintVT);
5748 unsigned NumRegs = 1;
5749 if (OpInfo.ConstraintVT != MVT::Other) {
5750 // If this is a FP input in an integer register (or visa versa) insert a bit
5751 // cast of the input value. More generally, handle any case where the input
5752 // value disagrees with the register class we plan to stick this in.
5753 if (OpInfo.Type == InlineAsm::isInput &&
5754 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5755 // Try to convert to the first EVT that the reg class contains. If the
5756 // types are identical size, use a bitcast to convert (e.g. two differing
5758 MVT RegVT = *PhysReg.second->vt_begin();
5759 if (RegVT.getSizeInBits() == OpInfo.CallOperand.getValueSizeInBits()) {
5760 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5761 RegVT, OpInfo.CallOperand);
5762 OpInfo.ConstraintVT = RegVT;
5763 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5764 // If the input is a FP value and we want it in FP registers, do a
5765 // bitcast to the corresponding integer type. This turns an f64 value
5766 // into i64, which can be passed with two i32 values on a 32-bit
5768 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
5769 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5770 RegVT, OpInfo.CallOperand);
5771 OpInfo.ConstraintVT = RegVT;
5775 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5779 EVT ValueVT = OpInfo.ConstraintVT;
5781 // If this is a constraint for a specific physical register, like {r17},
5783 if (unsigned AssignedReg = PhysReg.first) {
5784 const TargetRegisterClass *RC = PhysReg.second;
5785 if (OpInfo.ConstraintVT == MVT::Other)
5786 ValueVT = *RC->vt_begin();
5788 // Get the actual register value type. This is important, because the user
5789 // may have asked for (e.g.) the AX register in i32 type. We need to
5790 // remember that AX is actually i16 to get the right extension.
5791 RegVT = *RC->vt_begin();
5793 // This is a explicit reference to a physical register.
5794 Regs.push_back(AssignedReg);
5796 // If this is an expanded reference, add the rest of the regs to Regs.
5798 TargetRegisterClass::iterator I = RC->begin();
5799 for (; *I != AssignedReg; ++I)
5800 assert(I != RC->end() && "Didn't find reg!");
5802 // Already added the first reg.
5804 for (; NumRegs; --NumRegs, ++I) {
5805 assert(I != RC->end() && "Ran out of registers to allocate!");
5810 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5814 // Otherwise, if this was a reference to an LLVM register class, create vregs
5815 // for this reference.
5816 if (const TargetRegisterClass *RC = PhysReg.second) {
5817 RegVT = *RC->vt_begin();
5818 if (OpInfo.ConstraintVT == MVT::Other)
5821 // Create the appropriate number of virtual registers.
5822 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5823 for (; NumRegs; --NumRegs)
5824 Regs.push_back(RegInfo.createVirtualRegister(RC));
5826 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5830 // Otherwise, we couldn't allocate enough registers for this.
5833 /// visitInlineAsm - Handle a call to an InlineAsm object.
5835 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5836 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5838 /// ConstraintOperands - Information about all of the constraints.
5839 SDISelAsmOperandInfoVector ConstraintOperands;
5841 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5842 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
5843 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
5845 bool hasMemory = false;
5847 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5848 unsigned ResNo = 0; // ResNo - The result number of the next output.
5849 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5850 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
5851 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5853 MVT OpVT = MVT::Other;
5855 // Compute the value type for each operand.
5856 switch (OpInfo.Type) {
5857 case InlineAsm::isOutput:
5858 // Indirect outputs just consume an argument.
5859 if (OpInfo.isIndirect) {
5860 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5864 // The return value of the call is this value. As such, there is no
5865 // corresponding argument.
5866 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5867 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
5868 OpVT = TLI.getSimpleValueType(STy->getElementType(ResNo));
5870 assert(ResNo == 0 && "Asm only has one result!");
5871 OpVT = TLI.getSimpleValueType(CS.getType());
5875 case InlineAsm::isInput:
5876 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5878 case InlineAsm::isClobber:
5883 // If this is an input or an indirect output, process the call argument.
5884 // BasicBlocks are labels, currently appearing only in asm's.
5885 if (OpInfo.CallOperandVal) {
5886 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5887 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5889 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5892 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
5893 DAG.getDataLayout()).getSimpleVT();
5896 OpInfo.ConstraintVT = OpVT;
5898 // Indirect operand accesses access memory.
5899 if (OpInfo.isIndirect)
5902 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
5903 TargetLowering::ConstraintType
5904 CType = TLI.getConstraintType(OpInfo.Codes[j]);
5905 if (CType == TargetLowering::C_Memory) {
5913 SDValue Chain, Flag;
5915 // We won't need to flush pending loads if this asm doesn't touch
5916 // memory and is nonvolatile.
5917 if (hasMemory || IA->hasSideEffects())
5920 Chain = DAG.getRoot();
5922 // Second pass over the constraints: compute which constraint option to use
5923 // and assign registers to constraints that want a specific physreg.
5924 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5925 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5927 // If this is an output operand with a matching input operand, look up the
5928 // matching input. If their types mismatch, e.g. one is an integer, the
5929 // other is floating point, or their sizes are different, flag it as an
5931 if (OpInfo.hasMatchingInput()) {
5932 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5934 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5935 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
5936 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
5937 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
5938 OpInfo.ConstraintVT);
5939 std::pair<unsigned, const TargetRegisterClass *> InputRC =
5940 TLI.getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
5941 Input.ConstraintVT);
5942 if ((OpInfo.ConstraintVT.isInteger() !=
5943 Input.ConstraintVT.isInteger()) ||
5944 (MatchRC.second != InputRC.second)) {
5945 report_fatal_error("Unsupported asm: input constraint"
5946 " with a matching output constraint of"
5947 " incompatible type!");
5949 Input.ConstraintVT = OpInfo.ConstraintVT;
5953 // Compute the constraint code and ConstraintType to use.
5954 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
5956 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5957 OpInfo.Type == InlineAsm::isClobber)
5960 // If this is a memory input, and if the operand is not indirect, do what we
5961 // need to to provide an address for the memory input.
5962 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5963 !OpInfo.isIndirect) {
5964 assert((OpInfo.isMultipleAlternative ||
5965 (OpInfo.Type == InlineAsm::isInput)) &&
5966 "Can only indirectify direct input operands!");
5968 // Memory operands really want the address of the value. If we don't have
5969 // an indirect input, put it in the constpool if we can, otherwise spill
5970 // it to a stack slot.
5971 // TODO: This isn't quite right. We need to handle these according to
5972 // the addressing mode that the constraint wants. Also, this may take
5973 // an additional register for the computation and we don't want that
5976 // If the operand is a float, integer, or vector constant, spill to a
5977 // constant pool entry to get its address.
5978 const Value *OpVal = OpInfo.CallOperandVal;
5979 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5980 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
5981 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5982 TLI.getPointerTy());
5984 // Otherwise, create a stack slot and emit a store to it before the
5986 Type *Ty = OpVal->getType();
5987 auto &DL = DAG.getDataLayout();
5988 uint64_t TySize = DL.getTypeAllocSize(Ty);
5989 unsigned Align = DL.getPrefTypeAlignment(Ty);
5990 MachineFunction &MF = DAG.getMachineFunction();
5991 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5992 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5993 Chain = DAG.getStore(Chain, getCurSDLoc(),
5994 OpInfo.CallOperand, StackSlot,
5995 MachinePointerInfo::getFixedStack(SSFI),
5997 OpInfo.CallOperand = StackSlot;
6000 // There is no longer a Value* corresponding to this operand.
6001 OpInfo.CallOperandVal = nullptr;
6003 // It is now an indirect operand.
6004 OpInfo.isIndirect = true;
6007 // If this constraint is for a specific register, allocate it before
6009 if (OpInfo.ConstraintType == TargetLowering::C_Register)
6010 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6013 // Second pass - Loop over all of the operands, assigning virtual or physregs
6014 // to register class operands.
6015 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6016 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6018 // C_Register operands have already been allocated, Other/Memory don't need
6020 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
6021 GetRegistersForValue(DAG, TLI, getCurSDLoc(), OpInfo);
6024 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6025 std::vector<SDValue> AsmNodeOperands;
6026 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6027 AsmNodeOperands.push_back(
6028 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6029 TLI.getPointerTy()));
6031 // If we have a !srcloc metadata node associated with it, we want to attach
6032 // this to the ultimately generated inline asm machineinstr. To do this, we
6033 // pass in the third operand as this (potentially null) inline asm MDNode.
6034 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6035 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
6037 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6038 // bits as operand 3.
6039 unsigned ExtraInfo = 0;
6040 if (IA->hasSideEffects())
6041 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6042 if (IA->isAlignStack())
6043 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
6044 // Set the asm dialect.
6045 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
6047 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6048 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6049 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6051 // Compute the constraint code and ConstraintType to use.
6052 TLI.ComputeConstraintToUse(OpInfo, SDValue());
6054 // Ideally, we would only check against memory constraints. However, the
6055 // meaning of an other constraint can be target-specific and we can't easily
6056 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6057 // for other constriants as well.
6058 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6059 OpInfo.ConstraintType == TargetLowering::C_Other) {
6060 if (OpInfo.Type == InlineAsm::isInput)
6061 ExtraInfo |= InlineAsm::Extra_MayLoad;
6062 else if (OpInfo.Type == InlineAsm::isOutput)
6063 ExtraInfo |= InlineAsm::Extra_MayStore;
6064 else if (OpInfo.Type == InlineAsm::isClobber)
6065 ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
6069 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo, getCurSDLoc(),
6070 TLI.getPointerTy()));
6072 // Loop over all of the inputs, copying the operand values into the
6073 // appropriate registers and processing the output regs.
6074 RegsForValue RetValRegs;
6076 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6077 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
6079 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6080 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6082 switch (OpInfo.Type) {
6083 case InlineAsm::isOutput: {
6084 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6085 OpInfo.ConstraintType != TargetLowering::C_Register) {
6086 // Memory output, or 'other' output (e.g. 'X' constraint).
6087 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6089 unsigned ConstraintID =
6090 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6091 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6092 "Failed to convert memory constraint code to constraint id.");
6094 // Add information to the INLINEASM node to know about this output.
6095 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6096 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
6097 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
6099 AsmNodeOperands.push_back(OpInfo.CallOperand);
6103 // Otherwise, this is a register or register class output.
6105 // Copy the output from the appropriate register. Find a register that
6107 if (OpInfo.AssignedRegs.Regs.empty()) {
6108 LLVMContext &Ctx = *DAG.getContext();
6109 Ctx.emitError(CS.getInstruction(),
6110 "couldn't allocate output register for constraint '" +
6111 Twine(OpInfo.ConstraintCode) + "'");
6115 // If this is an indirect operand, store through the pointer after the
6117 if (OpInfo.isIndirect) {
6118 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6119 OpInfo.CallOperandVal));
6121 // This is the result value of the call.
6122 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
6123 // Concatenate this output onto the outputs list.
6124 RetValRegs.append(OpInfo.AssignedRegs);
6127 // Add information to the INLINEASM node to know that this register is
6130 .AddInlineAsmOperands(OpInfo.isEarlyClobber
6131 ? InlineAsm::Kind_RegDefEarlyClobber
6132 : InlineAsm::Kind_RegDef,
6133 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
6136 case InlineAsm::isInput: {
6137 SDValue InOperandVal = OpInfo.CallOperand;
6139 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
6140 // If this is required to match an output register we have already set,
6141 // just use its register.
6142 unsigned OperandNo = OpInfo.getMatchedOperand();
6144 // Scan until we find the definition we already emitted of this operand.
6145 // When we find it, create a RegsForValue operand.
6146 unsigned CurOp = InlineAsm::Op_FirstOperand;
6147 for (; OperandNo; --OperandNo) {
6148 // Advance to the next operand.
6150 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6151 assert((InlineAsm::isRegDefKind(OpFlag) ||
6152 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6153 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
6154 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
6158 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
6159 if (InlineAsm::isRegDefKind(OpFlag) ||
6160 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
6161 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
6162 if (OpInfo.isIndirect) {
6163 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
6164 LLVMContext &Ctx = *DAG.getContext();
6165 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6166 " don't know how to handle tied "
6167 "indirect register inputs");
6171 RegsForValue MatchedRegs;
6172 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
6173 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
6174 MatchedRegs.RegVTs.push_back(RegVT);
6175 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
6176 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
6178 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT))
6179 MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
6181 LLVMContext &Ctx = *DAG.getContext();
6182 Ctx.emitError(CS.getInstruction(),
6183 "inline asm error: This value"
6184 " type register class is not natively supported!");
6188 SDLoc dl = getCurSDLoc();
6189 // Use the produced MatchedRegs object to
6190 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6191 Chain, &Flag, CS.getInstruction());
6192 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
6193 true, OpInfo.getMatchedOperand(), dl,
6194 DAG, AsmNodeOperands);
6198 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6199 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6200 "Unexpected number of operands");
6201 // Add information to the INLINEASM node to know about this input.
6202 // See InlineAsm.h isUseOperandTiedToDef.
6203 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
6204 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6205 OpInfo.getMatchedOperand());
6206 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag, getCurSDLoc(),
6207 TLI.getPointerTy()));
6208 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6212 // Treat indirect 'X' constraint as memory.
6213 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6215 OpInfo.ConstraintType = TargetLowering::C_Memory;
6217 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
6218 std::vector<SDValue> Ops;
6219 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
6222 LLVMContext &Ctx = *DAG.getContext();
6223 Ctx.emitError(CS.getInstruction(),
6224 "invalid operand for inline asm constraint '" +
6225 Twine(OpInfo.ConstraintCode) + "'");
6229 // Add information to the INLINEASM node to know about this input.
6230 unsigned ResOpType =
6231 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
6232 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6234 TLI.getPointerTy()));
6235 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6239 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
6240 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6241 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6242 "Memory operands expect pointer values");
6244 unsigned ConstraintID =
6245 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
6246 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
6247 "Failed to convert memory constraint code to constraint id.");
6249 // Add information to the INLINEASM node to know about this input.
6250 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6251 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
6252 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6255 AsmNodeOperands.push_back(InOperandVal);
6259 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6260 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6261 "Unknown constraint type!");
6263 // TODO: Support this.
6264 if (OpInfo.isIndirect) {
6265 LLVMContext &Ctx = *DAG.getContext();
6266 Ctx.emitError(CS.getInstruction(),
6267 "Don't know how to handle indirect register inputs yet "
6268 "for constraint '" +
6269 Twine(OpInfo.ConstraintCode) + "'");
6273 // Copy the input into the appropriate registers.
6274 if (OpInfo.AssignedRegs.Regs.empty()) {
6275 LLVMContext &Ctx = *DAG.getContext();
6276 Ctx.emitError(CS.getInstruction(),
6277 "couldn't allocate input reg for constraint '" +
6278 Twine(OpInfo.ConstraintCode) + "'");
6282 SDLoc dl = getCurSDLoc();
6284 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
6285 Chain, &Flag, CS.getInstruction());
6287 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6288 dl, DAG, AsmNodeOperands);
6291 case InlineAsm::isClobber: {
6292 // Add the clobbered value to the operand list, so that the register
6293 // allocator is aware that the physreg got clobbered.
6294 if (!OpInfo.AssignedRegs.Regs.empty())
6295 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
6296 false, 0, getCurSDLoc(), DAG,
6303 // Finish up input operands. Set the input chain and add the flag last.
6304 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6305 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6307 Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
6308 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
6309 Flag = Chain.getValue(1);
6311 // If this asm returns a register value, copy the result from that register
6312 // and set it as the value of the call.
6313 if (!RetValRegs.Regs.empty()) {
6314 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6315 Chain, &Flag, CS.getInstruction());
6317 // FIXME: Why don't we do this for inline asms with MRVs?
6318 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6319 EVT ResultType = TLI.getValueType(CS.getType());
6321 // If any of the results of the inline asm is a vector, it may have the
6322 // wrong width/num elts. This can happen for register classes that can
6323 // contain multiple different value types. The preg or vreg allocated may
6324 // not have the same VT as was expected. Convert it to the right type
6325 // with bit_convert.
6326 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6327 Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
6330 } else if (ResultType != Val.getValueType() &&
6331 ResultType.isInteger() && Val.getValueType().isInteger()) {
6332 // If a result value was tied to an input value, the computed result may
6333 // have a wider width than the expected result. Extract the relevant
6335 Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
6338 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6341 setValue(CS.getInstruction(), Val);
6342 // Don't need to use this as a chain in this case.
6343 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6347 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6349 // Process indirect outputs, first output all of the flagged copies out of
6351 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6352 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6353 const Value *Ptr = IndirectStoresToEmit[i].second;
6354 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
6356 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6359 // Emit the non-flagged stores from the physregs.
6360 SmallVector<SDValue, 8> OutChains;
6361 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6362 SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
6363 StoresToEmit[i].first,
6364 getValue(StoresToEmit[i].second),
6365 MachinePointerInfo(StoresToEmit[i].second),
6367 OutChains.push_back(Val);
6370 if (!OutChains.empty())
6371 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
6376 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6377 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
6378 MVT::Other, getRoot(),
6379 getValue(I.getArgOperand(0)),
6380 DAG.getSrcValue(I.getArgOperand(0))));
6383 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6384 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6385 const DataLayout &DL = DAG.getDataLayout();
6386 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurSDLoc(),
6387 getRoot(), getValue(I.getOperand(0)),
6388 DAG.getSrcValue(I.getOperand(0)),
6389 DL.getABITypeAlignment(I.getType()));
6391 DAG.setRoot(V.getValue(1));
6394 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6395 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
6396 MVT::Other, getRoot(),
6397 getValue(I.getArgOperand(0)),
6398 DAG.getSrcValue(I.getArgOperand(0))));
6401 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6402 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
6403 MVT::Other, getRoot(),
6404 getValue(I.getArgOperand(0)),
6405 getValue(I.getArgOperand(1)),
6406 DAG.getSrcValue(I.getArgOperand(0)),
6407 DAG.getSrcValue(I.getArgOperand(1))));
6410 /// \brief Lower an argument list according to the target calling convention.
6412 /// \return A tuple of <return-value, token-chain>
6414 /// This is a helper for lowering intrinsics that follow a target calling
6415 /// convention or require stack pointer adjustment. Only a subset of the
6416 /// intrinsic's operands need to participate in the calling convention.
6417 std::pair<SDValue, SDValue>
6418 SelectionDAGBuilder::lowerCallOperands(ImmutableCallSite CS, unsigned ArgIdx,
6419 unsigned NumArgs, SDValue Callee,
6421 MachineBasicBlock *LandingPad,
6422 bool IsPatchPoint) {
6423 TargetLowering::ArgListTy Args;
6424 Args.reserve(NumArgs);
6426 // Populate the argument list.
6427 // Attributes for args start at offset 1, after the return attribute.
6428 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
6429 ArgI != ArgE; ++ArgI) {
6430 const Value *V = CS->getOperand(ArgI);
6432 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
6434 TargetLowering::ArgListEntry Entry;
6435 Entry.Node = getValue(V);
6436 Entry.Ty = V->getType();
6437 Entry.setAttributes(&CS, AttrI);
6438 Args.push_back(Entry);
6441 TargetLowering::CallLoweringInfo CLI(DAG);
6442 CLI.setDebugLoc(getCurSDLoc()).setChain(getRoot())
6443 .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args), NumArgs)
6444 .setDiscardResult(CS->use_empty()).setIsPatchPoint(IsPatchPoint);
6446 return lowerInvokable(CLI, LandingPad);
6449 /// \brief Add a stack map intrinsic call's live variable operands to a stackmap
6450 /// or patchpoint target node's operand list.
6452 /// Constants are converted to TargetConstants purely as an optimization to
6453 /// avoid constant materialization and register allocation.
6455 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
6456 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
6457 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
6458 /// address materialization and register allocation, but may also be required
6459 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
6460 /// alloca in the entry block, then the runtime may assume that the alloca's
6461 /// StackMap location can be read immediately after compilation and that the
6462 /// location is valid at any point during execution (this is similar to the
6463 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
6464 /// only available in a register, then the runtime would need to trap when
6465 /// execution reaches the StackMap in order to read the alloca's location.
6466 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
6467 SDLoc DL, SmallVectorImpl<SDValue> &Ops,
6468 SelectionDAGBuilder &Builder) {
6469 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
6470 SDValue OpVal = Builder.getValue(CS.getArgument(i));
6471 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
6473 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
6475 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
6476 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
6477 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
6479 Builder.DAG.getTargetFrameIndex(FI->getIndex(), TLI.getPointerTy()));
6481 Ops.push_back(OpVal);
6485 /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
6486 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
6487 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
6488 // [live variables...])
6490 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
6492 SDValue Chain, InFlag, Callee, NullPtr;
6493 SmallVector<SDValue, 32> Ops;
6495 SDLoc DL = getCurSDLoc();
6496 Callee = getValue(CI.getCalledValue());
6497 NullPtr = DAG.getIntPtrConstant(0, DL, true);
6499 // The stackmap intrinsic only records the live variables (the arguemnts
6500 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
6501 // intrinsic, this won't be lowered to a function call. This means we don't
6502 // have to worry about calling conventions and target specific lowering code.
6503 // Instead we perform the call lowering right here.
6505 // chain, flag = CALLSEQ_START(chain, 0)
6506 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
6507 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
6509 Chain = DAG.getCALLSEQ_START(getRoot(), NullPtr, DL);
6510 InFlag = Chain.getValue(1);
6512 // Add the <id> and <numBytes> constants.
6513 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
6514 Ops.push_back(DAG.getTargetConstant(
6515 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
6516 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
6517 Ops.push_back(DAG.getTargetConstant(
6518 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
6521 // Push live variables for the stack map.
6522 addStackMapLiveVars(&CI, 2, DL, Ops, *this);
6524 // We are not pushing any register mask info here on the operands list,
6525 // because the stackmap doesn't clobber anything.
6527 // Push the chain and the glue flag.
6528 Ops.push_back(Chain);
6529 Ops.push_back(InFlag);
6531 // Create the STACKMAP node.
6532 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6533 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
6534 Chain = SDValue(SM, 0);
6535 InFlag = Chain.getValue(1);
6537 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
6539 // Stackmaps don't generate values, so nothing goes into the NodeMap.
6541 // Set the root to the target-lowered call chain.
6544 // Inform the Frame Information that we have a stackmap in this function.
6545 FuncInfo.MF->getFrameInfo()->setHasStackMap();
6548 /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
6549 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
6550 MachineBasicBlock *LandingPad) {
6551 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
6556 // [live variables...])
6558 CallingConv::ID CC = CS.getCallingConv();
6559 bool IsAnyRegCC = CC == CallingConv::AnyReg;
6560 bool HasDef = !CS->getType()->isVoidTy();
6561 SDLoc dl = getCurSDLoc();
6562 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
6564 // Handle immediate and symbolic callees.
6565 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
6566 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
6568 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
6569 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
6570 SDLoc(SymbolicCallee),
6571 SymbolicCallee->getValueType(0));
6573 // Get the real number of arguments participating in the call <numArgs>
6574 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
6575 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
6577 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
6578 // Intrinsics include all meta-operands up to but not including CC.
6579 unsigned NumMetaOpers = PatchPointOpers::CCPos;
6580 assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
6581 "Not enough arguments provided to the patchpoint intrinsic");
6583 // For AnyRegCC the arguments are lowered later on manually.
6584 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
6586 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
6587 std::pair<SDValue, SDValue> Result =
6588 lowerCallOperands(CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
6591 SDNode *CallEnd = Result.second.getNode();
6592 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
6593 CallEnd = CallEnd->getOperand(0).getNode();
6595 /// Get a call instruction from the call sequence chain.
6596 /// Tail calls are not allowed.
6597 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
6598 "Expected a callseq node.");
6599 SDNode *Call = CallEnd->getOperand(0).getNode();
6600 bool HasGlue = Call->getGluedNode();
6602 // Replace the target specific call node with the patchable intrinsic.
6603 SmallVector<SDValue, 8> Ops;
6605 // Add the <id> and <numBytes> constants.
6606 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
6607 Ops.push_back(DAG.getTargetConstant(
6608 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
6609 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
6610 Ops.push_back(DAG.getTargetConstant(
6611 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
6615 Ops.push_back(Callee);
6617 // Adjust <numArgs> to account for any arguments that have been passed on the
6619 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
6620 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
6621 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
6622 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
6624 // Add the calling convention
6625 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
6627 // Add the arguments we omitted previously. The register allocator should
6628 // place these in any free register.
6630 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
6631 Ops.push_back(getValue(CS.getArgument(i)));
6633 // Push the arguments from the call instruction up to the register mask.
6634 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
6635 Ops.append(Call->op_begin() + 2, e);
6637 // Push live variables for the stack map.
6638 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
6640 // Push the register mask info.
6642 Ops.push_back(*(Call->op_end()-2));
6644 Ops.push_back(*(Call->op_end()-1));
6646 // Push the chain (this is originally the first operand of the call, but
6647 // becomes now the last or second to last operand).
6648 Ops.push_back(*(Call->op_begin()));
6650 // Push the glue flag (last operand).
6652 Ops.push_back(*(Call->op_end()-1));
6655 if (IsAnyRegCC && HasDef) {
6656 // Create the return types based on the intrinsic definition
6657 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6658 SmallVector<EVT, 3> ValueVTs;
6659 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
6660 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
6662 // There is always a chain and a glue type at the end
6663 ValueVTs.push_back(MVT::Other);
6664 ValueVTs.push_back(MVT::Glue);
6665 NodeTys = DAG.getVTList(ValueVTs);
6667 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6669 // Replace the target specific call node with a PATCHPOINT node.
6670 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
6673 // Update the NodeMap.
6676 setValue(CS.getInstruction(), SDValue(MN, 0));
6678 setValue(CS.getInstruction(), Result.first);
6681 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
6682 // call sequence. Furthermore the location of the chain and glue can change
6683 // when the AnyReg calling convention is used and the intrinsic returns a
6685 if (IsAnyRegCC && HasDef) {
6686 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
6687 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
6688 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
6690 DAG.ReplaceAllUsesWith(Call, MN);
6691 DAG.DeleteNode(Call);
6693 // Inform the Frame Information that we have a patchpoint in this function.
6694 FuncInfo.MF->getFrameInfo()->setHasPatchPoint();
6697 /// Returns an AttributeSet representing the attributes applied to the return
6698 /// value of the given call.
6699 static AttributeSet getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
6700 SmallVector<Attribute::AttrKind, 2> Attrs;
6702 Attrs.push_back(Attribute::SExt);
6704 Attrs.push_back(Attribute::ZExt);
6706 Attrs.push_back(Attribute::InReg);
6708 return AttributeSet::get(CLI.RetTy->getContext(), AttributeSet::ReturnIndex,
6712 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6713 /// implementation, which just calls LowerCall.
6714 /// FIXME: When all targets are
6715 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6716 std::pair<SDValue, SDValue>
6717 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
6718 // Handle the incoming return values from the call.
6720 Type *OrigRetTy = CLI.RetTy;
6721 SmallVector<EVT, 4> RetTys;
6722 SmallVector<uint64_t, 4> Offsets;
6723 auto &DL = CLI.DAG.getDataLayout();
6724 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
6726 SmallVector<ISD::OutputArg, 4> Outs;
6727 GetReturnInfo(CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
6729 bool CanLowerReturn =
6730 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
6731 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
6733 SDValue DemoteStackSlot;
6734 int DemoteStackIdx = -100;
6735 if (!CanLowerReturn) {
6736 // FIXME: equivalent assert?
6737 // assert(!CS.hasInAllocaArgument() &&
6738 // "sret demotion is incompatible with inalloca");
6739 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
6740 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
6741 MachineFunction &MF = CLI.DAG.getMachineFunction();
6742 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
6743 Type *StackSlotPtrType = PointerType::getUnqual(CLI.RetTy);
6745 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getPointerTy());
6747 Entry.Node = DemoteStackSlot;
6748 Entry.Ty = StackSlotPtrType;
6749 Entry.isSExt = false;
6750 Entry.isZExt = false;
6751 Entry.isInReg = false;
6752 Entry.isSRet = true;
6753 Entry.isNest = false;
6754 Entry.isByVal = false;
6755 Entry.isReturned = false;
6756 Entry.Alignment = Align;
6757 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
6758 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
6760 // sret demotion isn't compatible with tail-calls, since the sret argument
6761 // points into the callers stack frame.
6762 CLI.IsTailCall = false;
6764 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6766 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6767 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
6768 for (unsigned i = 0; i != NumRegs; ++i) {
6769 ISD::InputArg MyFlags;
6770 MyFlags.VT = RegisterVT;
6772 MyFlags.Used = CLI.IsReturnValueUsed;
6774 MyFlags.Flags.setSExt();
6776 MyFlags.Flags.setZExt();
6778 MyFlags.Flags.setInReg();
6779 CLI.Ins.push_back(MyFlags);
6784 // Handle all of the outgoing arguments.
6786 CLI.OutVals.clear();
6787 ArgListTy &Args = CLI.getArgs();
6788 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6789 SmallVector<EVT, 4> ValueVTs;
6790 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
6791 Type *FinalType = Args[i].Ty;
6792 if (Args[i].isByVal)
6793 FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
6794 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
6795 FinalType, CLI.CallConv, CLI.IsVarArg);
6796 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
6798 EVT VT = ValueVTs[Value];
6799 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
6800 SDValue Op = SDValue(Args[i].Node.getNode(),
6801 Args[i].Node.getResNo() + Value);
6802 ISD::ArgFlagsTy Flags;
6803 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
6809 if (Args[i].isInReg)
6813 if (Args[i].isByVal)
6815 if (Args[i].isInAlloca) {
6816 Flags.setInAlloca();
6817 // Set the byval flag for CCAssignFn callbacks that don't know about
6818 // inalloca. This way we can know how many bytes we should've allocated
6819 // and how many bytes a callee cleanup function will pop. If we port
6820 // inalloca to more targets, we'll have to add custom inalloca handling
6821 // in the various CC lowering callbacks.
6824 if (Args[i].isByVal || Args[i].isInAlloca) {
6825 PointerType *Ty = cast<PointerType>(Args[i].Ty);
6826 Type *ElementTy = Ty->getElementType();
6827 Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
6828 // For ByVal, alignment should come from FE. BE will guess if this
6829 // info is not there but there are cases it cannot get right.
6830 unsigned FrameAlign;
6831 if (Args[i].Alignment)
6832 FrameAlign = Args[i].Alignment;
6834 FrameAlign = getByValTypeAlignment(ElementTy);
6835 Flags.setByValAlign(FrameAlign);
6840 Flags.setInConsecutiveRegs();
6841 Flags.setOrigAlign(OriginalAlignment);
6843 MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
6844 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
6845 SmallVector<SDValue, 4> Parts(NumParts);
6846 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6849 ExtendKind = ISD::SIGN_EXTEND;
6850 else if (Args[i].isZExt)
6851 ExtendKind = ISD::ZERO_EXTEND;
6853 // Conservatively only handle 'returned' on non-vectors for now
6854 if (Args[i].isReturned && !Op.getValueType().isVector()) {
6855 assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
6856 "unexpected use of 'returned'");
6857 // Before passing 'returned' to the target lowering code, ensure that
6858 // either the register MVT and the actual EVT are the same size or that
6859 // the return value and argument are extended in the same way; in these
6860 // cases it's safe to pass the argument register value unchanged as the
6861 // return register value (although it's at the target's option whether
6863 // TODO: allow code generation to take advantage of partially preserved
6864 // registers rather than clobbering the entire register when the
6865 // parameter extension method is not compatible with the return
6867 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
6868 (ExtendKind != ISD::ANY_EXTEND &&
6869 CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
6870 Flags.setReturned();
6873 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
6874 CLI.CS ? CLI.CS->getInstruction() : nullptr, ExtendKind);
6876 for (unsigned j = 0; j != NumParts; ++j) {
6877 // if it isn't first piece, alignment must be 1
6878 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
6879 i < CLI.NumFixedArgs,
6880 i, j*Parts[j].getValueType().getStoreSize());
6881 if (NumParts > 1 && j == 0)
6882 MyFlags.Flags.setSplit();
6884 MyFlags.Flags.setOrigAlign(1);
6886 CLI.Outs.push_back(MyFlags);
6887 CLI.OutVals.push_back(Parts[j]);
6890 if (NeedsRegBlock && Value == NumValues - 1)
6891 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
6895 SmallVector<SDValue, 4> InVals;
6896 CLI.Chain = LowerCall(CLI, InVals);
6898 // Verify that the target's LowerCall behaved as expected.
6899 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
6900 "LowerCall didn't return a valid chain!");
6901 assert((!CLI.IsTailCall || InVals.empty()) &&
6902 "LowerCall emitted a return value for a tail call!");
6903 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
6904 "LowerCall didn't emit the correct number of values!");
6906 // For a tail call, the return value is merely live-out and there aren't
6907 // any nodes in the DAG representing it. Return a special value to
6908 // indicate that a tail call has been emitted and no more Instructions
6909 // should be processed in the current block.
6910 if (CLI.IsTailCall) {
6911 CLI.DAG.setRoot(CLI.Chain);
6912 return std::make_pair(SDValue(), SDValue());
6915 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
6916 assert(InVals[i].getNode() &&
6917 "LowerCall emitted a null value!");
6918 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
6919 "LowerCall emitted a value with the wrong type!");
6922 SmallVector<SDValue, 4> ReturnValues;
6923 if (!CanLowerReturn) {
6924 // The instruction result is the result of loading from the
6925 // hidden sret parameter.
6926 SmallVector<EVT, 1> PVTs;
6927 Type *PtrRetTy = PointerType::getUnqual(OrigRetTy);
6929 ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
6930 assert(PVTs.size() == 1 && "Pointers should fit in one register");
6931 EVT PtrVT = PVTs[0];
6933 unsigned NumValues = RetTys.size();
6934 ReturnValues.resize(NumValues);
6935 SmallVector<SDValue, 4> Chains(NumValues);
6937 for (unsigned i = 0; i < NumValues; ++i) {
6938 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
6939 CLI.DAG.getConstant(Offsets[i], CLI.DL,
6941 SDValue L = CLI.DAG.getLoad(
6942 RetTys[i], CLI.DL, CLI.Chain, Add,
6943 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]), false,
6945 ReturnValues[i] = L;
6946 Chains[i] = L.getValue(1);
6949 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
6951 // Collect the legal value parts into potentially illegal values
6952 // that correspond to the original function's return values.
6953 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6955 AssertOp = ISD::AssertSext;
6956 else if (CLI.RetZExt)
6957 AssertOp = ISD::AssertZext;
6958 unsigned CurReg = 0;
6959 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6961 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6962 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
6964 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
6965 NumRegs, RegisterVT, VT, nullptr,
6970 // For a function returning void, there is no return value. We can't create
6971 // such a node, so we just return a null return value in that case. In
6972 // that case, nothing will actually look at the value.
6973 if (ReturnValues.empty())
6974 return std::make_pair(SDValue(), CLI.Chain);
6977 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
6978 CLI.DAG.getVTList(RetTys), ReturnValues);
6979 return std::make_pair(Res, CLI.Chain);
6982 void TargetLowering::LowerOperationWrapper(SDNode *N,
6983 SmallVectorImpl<SDValue> &Results,
6984 SelectionDAG &DAG) const {
6985 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6987 Results.push_back(Res);
6990 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6991 llvm_unreachable("LowerOperation not implemented for this target!");
6995 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
6996 SDValue Op = getNonRegisterValue(V);
6997 assert((Op.getOpcode() != ISD::CopyFromReg ||
6998 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6999 "Copy from a reg to the same reg!");
7000 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
7002 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7003 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
7005 SDValue Chain = DAG.getEntryNode();
7007 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
7008 FuncInfo.PreferredExtendType.end())
7010 : FuncInfo.PreferredExtendType[V];
7011 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
7012 PendingExports.push_back(Chain);
7015 #include "llvm/CodeGen/SelectionDAGISel.h"
7017 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
7018 /// entry block, return true. This includes arguments used by switches, since
7019 /// the switch may expand into multiple basic blocks.
7020 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
7021 // With FastISel active, we may be splitting blocks, so force creation
7022 // of virtual registers for all non-dead arguments.
7024 return A->use_empty();
7026 const BasicBlock *Entry = A->getParent()->begin();
7027 for (const User *U : A->users())
7028 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
7029 return false; // Use not in entry block.
7034 void SelectionDAGISel::LowerArguments(const Function &F) {
7035 SelectionDAG &DAG = SDB->DAG;
7036 SDLoc dl = SDB->getCurSDLoc();
7037 const DataLayout &DL = DAG.getDataLayout();
7038 SmallVector<ISD::InputArg, 16> Ins;
7040 if (!FuncInfo->CanLowerReturn) {
7041 // Put in an sret pointer parameter before all the other parameters.
7042 SmallVector<EVT, 1> ValueVTs;
7043 ComputeValueVTs(*TLI, DAG.getDataLayout(),
7044 PointerType::getUnqual(F.getReturnType()), ValueVTs);
7046 // NOTE: Assuming that a pointer will never break down to more than one VT
7048 ISD::ArgFlagsTy Flags;
7050 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
7051 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
7052 ISD::InputArg::NoArgIndex, 0);
7053 Ins.push_back(RetArg);
7056 // Set up the incoming argument description vector.
7058 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
7059 I != E; ++I, ++Idx) {
7060 SmallVector<EVT, 4> ValueVTs;
7061 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7062 bool isArgValueUsed = !I->use_empty();
7063 unsigned PartBase = 0;
7064 Type *FinalType = I->getType();
7065 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7066 FinalType = cast<PointerType>(FinalType)->getElementType();
7067 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
7068 FinalType, F.getCallingConv(), F.isVarArg());
7069 for (unsigned Value = 0, NumValues = ValueVTs.size();
7070 Value != NumValues; ++Value) {
7071 EVT VT = ValueVTs[Value];
7072 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
7073 ISD::ArgFlagsTy Flags;
7074 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
7076 if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7078 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7080 if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
7082 if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
7084 if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal))
7086 if (F.getAttributes().hasAttribute(Idx, Attribute::InAlloca)) {
7087 Flags.setInAlloca();
7088 // Set the byval flag for CCAssignFn callbacks that don't know about
7089 // inalloca. This way we can know how many bytes we should've allocated
7090 // and how many bytes a callee cleanup function will pop. If we port
7091 // inalloca to more targets, we'll have to add custom inalloca handling
7092 // in the various CC lowering callbacks.
7095 if (Flags.isByVal() || Flags.isInAlloca()) {
7096 PointerType *Ty = cast<PointerType>(I->getType());
7097 Type *ElementTy = Ty->getElementType();
7098 Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
7099 // For ByVal, alignment should be passed from FE. BE will guess if
7100 // this info is not there but there are cases it cannot get right.
7101 unsigned FrameAlign;
7102 if (F.getParamAlignment(Idx))
7103 FrameAlign = F.getParamAlignment(Idx);
7105 FrameAlign = TLI->getByValTypeAlignment(ElementTy);
7106 Flags.setByValAlign(FrameAlign);
7108 if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
7111 Flags.setInConsecutiveRegs();
7112 Flags.setOrigAlign(OriginalAlignment);
7114 MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7115 unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7116 for (unsigned i = 0; i != NumRegs; ++i) {
7117 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
7118 Idx-1, PartBase+i*RegisterVT.getStoreSize());
7119 if (NumRegs > 1 && i == 0)
7120 MyFlags.Flags.setSplit();
7121 // if it isn't first piece, alignment must be 1
7123 MyFlags.Flags.setOrigAlign(1);
7124 Ins.push_back(MyFlags);
7126 if (NeedsRegBlock && Value == NumValues - 1)
7127 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
7128 PartBase += VT.getStoreSize();
7132 // Call the target to set up the argument values.
7133 SmallVector<SDValue, 8> InVals;
7134 SDValue NewRoot = TLI->LowerFormalArguments(
7135 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
7137 // Verify that the target's LowerFormalArguments behaved as expected.
7138 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
7139 "LowerFormalArguments didn't return a valid chain!");
7140 assert(InVals.size() == Ins.size() &&
7141 "LowerFormalArguments didn't emit the correct number of values!");
7143 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
7144 assert(InVals[i].getNode() &&
7145 "LowerFormalArguments emitted a null value!");
7146 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
7147 "LowerFormalArguments emitted a value with the wrong type!");
7151 // Update the DAG with the new chain value resulting from argument lowering.
7152 DAG.setRoot(NewRoot);
7154 // Set up the argument values.
7157 if (!FuncInfo->CanLowerReturn) {
7158 // Create a virtual register for the sret pointer, and put in a copy
7159 // from the sret argument into it.
7160 SmallVector<EVT, 1> ValueVTs;
7161 ComputeValueVTs(*TLI, DAG.getDataLayout(),
7162 PointerType::getUnqual(F.getReturnType()), ValueVTs);
7163 MVT VT = ValueVTs[0].getSimpleVT();
7164 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7165 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7166 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
7167 RegVT, VT, nullptr, AssertOp);
7169 MachineFunction& MF = SDB->DAG.getMachineFunction();
7170 MachineRegisterInfo& RegInfo = MF.getRegInfo();
7171 unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
7172 FuncInfo->DemoteRegister = SRetReg;
7174 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
7175 DAG.setRoot(NewRoot);
7177 // i indexes lowered arguments. Bump it past the hidden sret argument.
7178 // Idx indexes LLVM arguments. Don't touch it.
7182 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
7184 SmallVector<SDValue, 4> ArgValues;
7185 SmallVector<EVT, 4> ValueVTs;
7186 ComputeValueVTs(*TLI, DAG.getDataLayout(), I->getType(), ValueVTs);
7187 unsigned NumValues = ValueVTs.size();
7189 // If this argument is unused then remember its value. It is used to generate
7190 // debugging information.
7191 if (I->use_empty() && NumValues) {
7192 SDB->setUnusedArgValue(I, InVals[i]);
7194 // Also remember any frame index for use in FastISel.
7195 if (FrameIndexSDNode *FI =
7196 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
7197 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7200 for (unsigned Val = 0; Val != NumValues; ++Val) {
7201 EVT VT = ValueVTs[Val];
7202 MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
7203 unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
7205 if (!I->use_empty()) {
7206 ISD::NodeType AssertOp = ISD::DELETED_NODE;
7207 if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
7208 AssertOp = ISD::AssertSext;
7209 else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
7210 AssertOp = ISD::AssertZext;
7212 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
7213 NumParts, PartVT, VT,
7214 nullptr, AssertOp));
7220 // We don't need to do anything else for unused arguments.
7221 if (ArgValues.empty())
7224 // Note down frame index.
7225 if (FrameIndexSDNode *FI =
7226 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
7227 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7229 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
7230 SDB->getCurSDLoc());
7232 SDB->setValue(I, Res);
7233 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
7234 if (LoadSDNode *LNode =
7235 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
7236 if (FrameIndexSDNode *FI =
7237 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
7238 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
7241 // If this argument is live outside of the entry block, insert a copy from
7242 // wherever we got it to the vreg that other BB's will reference it as.
7243 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
7244 // If we can, though, try to skip creating an unnecessary vreg.
7245 // FIXME: This isn't very clean... it would be nice to make this more
7246 // general. It's also subtly incompatible with the hacks FastISel
7248 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
7249 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
7250 FuncInfo->ValueMap[I] = Reg;
7254 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
7255 FuncInfo->InitializeRegForValue(I);
7256 SDB->CopyToExportRegsIfNeeded(I);
7260 assert(i == InVals.size() && "Argument register count mismatch!");
7262 // Finally, if the target has anything special to do, allow it to do so.
7263 EmitFunctionEntryCode();
7266 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
7267 /// ensure constants are generated when needed. Remember the virtual registers
7268 /// that need to be added to the Machine PHI nodes as input. We cannot just
7269 /// directly add them, because expansion might result in multiple MBB's for one
7270 /// BB. As such, the start of the BB might correspond to a different MBB than
7274 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
7275 const TerminatorInst *TI = LLVMBB->getTerminator();
7277 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
7279 // Check PHI nodes in successors that expect a value to be available from this
7281 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
7282 const BasicBlock *SuccBB = TI->getSuccessor(succ);
7283 if (!isa<PHINode>(SuccBB->begin())) continue;
7284 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
7286 // If this terminator has multiple identical successors (common for
7287 // switches), only handle each succ once.
7288 if (!SuccsHandled.insert(SuccMBB).second)
7291 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
7293 // At this point we know that there is a 1-1 correspondence between LLVM PHI
7294 // nodes and Machine PHI nodes, but the incoming operands have not been
7296 for (BasicBlock::const_iterator I = SuccBB->begin();
7297 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
7298 // Ignore dead phi's.
7299 if (PN->use_empty()) continue;
7302 if (PN->getType()->isEmptyTy())
7306 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
7308 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
7309 unsigned &RegOut = ConstantsOut[C];
7311 RegOut = FuncInfo.CreateRegs(C->getType());
7312 CopyValueToVirtualRegister(C, RegOut);
7316 DenseMap<const Value *, unsigned>::iterator I =
7317 FuncInfo.ValueMap.find(PHIOp);
7318 if (I != FuncInfo.ValueMap.end())
7321 assert(isa<AllocaInst>(PHIOp) &&
7322 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
7323 "Didn't codegen value into a register!??");
7324 Reg = FuncInfo.CreateRegs(PHIOp->getType());
7325 CopyValueToVirtualRegister(PHIOp, Reg);
7329 // Remember that this register needs to added to the machine PHI node as
7330 // the input for this MBB.
7331 SmallVector<EVT, 4> ValueVTs;
7332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7333 ComputeValueVTs(TLI, DAG.getDataLayout(), PN->getType(), ValueVTs);
7334 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
7335 EVT VT = ValueVTs[vti];
7336 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
7337 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
7338 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
7339 Reg += NumRegisters;
7344 ConstantsOut.clear();
7347 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
7350 SelectionDAGBuilder::StackProtectorDescriptor::
7351 AddSuccessorMBB(const BasicBlock *BB,
7352 MachineBasicBlock *ParentMBB,
7354 MachineBasicBlock *SuccMBB) {
7355 // If SuccBB has not been created yet, create it.
7357 MachineFunction *MF = ParentMBB->getParent();
7358 MachineFunction::iterator BBI = ParentMBB;
7359 SuccMBB = MF->CreateMachineBasicBlock(BB);
7360 MF->insert(++BBI, SuccMBB);
7362 // Add it as a successor of ParentMBB.
7363 ParentMBB->addSuccessor(
7364 SuccMBB, BranchProbabilityInfo::getBranchWeightStackProtector(IsLikely));
7368 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
7369 MachineFunction::iterator I = MBB;
7370 if (++I == FuncInfo.MF->end())
7375 /// During lowering new call nodes can be created (such as memset, etc.).
7376 /// Those will become new roots of the current DAG, but complications arise
7377 /// when they are tail calls. In such cases, the call lowering will update
7378 /// the root, but the builder still needs to know that a tail call has been
7379 /// lowered in order to avoid generating an additional return.
7380 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
7381 // If the node is null, we do have a tail call.
7382 if (MaybeTC.getNode() != nullptr)
7383 DAG.setRoot(MaybeTC);
7388 bool SelectionDAGBuilder::isDense(const CaseClusterVector &Clusters,
7389 unsigned *TotalCases, unsigned First,
7391 assert(Last >= First);
7392 assert(TotalCases[Last] >= TotalCases[First]);
7394 APInt LowCase = Clusters[First].Low->getValue();
7395 APInt HighCase = Clusters[Last].High->getValue();
7396 assert(LowCase.getBitWidth() == HighCase.getBitWidth());
7398 // FIXME: A range of consecutive cases has 100% density, but only requires one
7399 // comparison to lower. We should discriminate against such consecutive ranges
7402 uint64_t Diff = (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100);
7403 uint64_t Range = Diff + 1;
7406 TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
7408 assert(NumCases < UINT64_MAX / 100);
7409 assert(Range >= NumCases);
7411 return NumCases * 100 >= Range * MinJumpTableDensity;
7414 static inline bool areJTsAllowed(const TargetLowering &TLI) {
7415 return TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
7416 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
7419 bool SelectionDAGBuilder::buildJumpTable(CaseClusterVector &Clusters,
7420 unsigned First, unsigned Last,
7421 const SwitchInst *SI,
7422 MachineBasicBlock *DefaultMBB,
7423 CaseCluster &JTCluster) {
7424 assert(First <= Last);
7426 uint32_t Weight = 0;
7427 unsigned NumCmps = 0;
7428 std::vector<MachineBasicBlock*> Table;
7429 DenseMap<MachineBasicBlock*, uint32_t> JTWeights;
7430 for (unsigned I = First; I <= Last; ++I) {
7431 assert(Clusters[I].Kind == CC_Range);
7432 Weight += Clusters[I].Weight;
7433 assert(Weight >= Clusters[I].Weight && "Weight overflow!");
7434 APInt Low = Clusters[I].Low->getValue();
7435 APInt High = Clusters[I].High->getValue();
7436 NumCmps += (Low == High) ? 1 : 2;
7438 // Fill the gap between this and the previous cluster.
7439 APInt PreviousHigh = Clusters[I - 1].High->getValue();
7440 assert(PreviousHigh.slt(Low));
7441 uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
7442 for (uint64_t J = 0; J < Gap; J++)
7443 Table.push_back(DefaultMBB);
7445 uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
7446 for (uint64_t J = 0; J < ClusterSize; ++J)
7447 Table.push_back(Clusters[I].MBB);
7448 JTWeights[Clusters[I].MBB] += Clusters[I].Weight;
7451 unsigned NumDests = JTWeights.size();
7452 if (isSuitableForBitTests(NumDests, NumCmps,
7453 Clusters[First].Low->getValue(),
7454 Clusters[Last].High->getValue())) {
7455 // Clusters[First..Last] should be lowered as bit tests instead.
7459 // Create the MBB that will load from and jump through the table.
7460 // Note: We create it here, but it's not inserted into the function yet.
7461 MachineFunction *CurMF = FuncInfo.MF;
7462 MachineBasicBlock *JumpTableMBB =
7463 CurMF->CreateMachineBasicBlock(SI->getParent());
7465 // Add successors. Note: use table order for determinism.
7466 SmallPtrSet<MachineBasicBlock *, 8> Done;
7467 for (MachineBasicBlock *Succ : Table) {
7468 if (Done.count(Succ))
7470 addSuccessorWithWeight(JumpTableMBB, Succ, JTWeights[Succ]);
7474 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7475 unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
7476 ->createJumpTableIndex(Table);
7478 // Set up the jump table info.
7479 JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
7480 JumpTableHeader JTH(Clusters[First].Low->getValue(),
7481 Clusters[Last].High->getValue(), SI->getCondition(),
7483 JTCases.emplace_back(std::move(JTH), std::move(JT));
7485 JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
7486 JTCases.size() - 1, Weight);
7490 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
7491 const SwitchInst *SI,
7492 MachineBasicBlock *DefaultMBB) {
7494 // Clusters must be non-empty, sorted, and only contain Range clusters.
7495 assert(!Clusters.empty());
7496 for (CaseCluster &C : Clusters)
7497 assert(C.Kind == CC_Range);
7498 for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
7499 assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
7502 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7503 if (!areJTsAllowed(TLI))
7506 const int64_t N = Clusters.size();
7507 const unsigned MinJumpTableSize = TLI.getMinimumJumpTableEntries();
7509 // TotalCases[i]: Total nbr of cases in Clusters[0..i].
7510 SmallVector<unsigned, 8> TotalCases(N);
7512 for (unsigned i = 0; i < N; ++i) {
7513 APInt Hi = Clusters[i].High->getValue();
7514 APInt Lo = Clusters[i].Low->getValue();
7515 TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
7517 TotalCases[i] += TotalCases[i - 1];
7520 if (N >= MinJumpTableSize && isDense(Clusters, &TotalCases[0], 0, N - 1)) {
7521 // Cheap case: the whole range might be suitable for jump table.
7522 CaseCluster JTCluster;
7523 if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
7524 Clusters[0] = JTCluster;
7530 // The algorithm below is not suitable for -O0.
7531 if (TM.getOptLevel() == CodeGenOpt::None)
7534 // Split Clusters into minimum number of dense partitions. The algorithm uses
7535 // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
7536 // for the Case Statement'" (1994), but builds the MinPartitions array in
7537 // reverse order to make it easier to reconstruct the partitions in ascending
7538 // order. In the choice between two optimal partitionings, it picks the one
7539 // which yields more jump tables.
7541 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
7542 SmallVector<unsigned, 8> MinPartitions(N);
7543 // LastElement[i] is the last element of the partition starting at i.
7544 SmallVector<unsigned, 8> LastElement(N);
7545 // NumTables[i]: nbr of >= MinJumpTableSize partitions from Clusters[i..N-1].
7546 SmallVector<unsigned, 8> NumTables(N);
7548 // Base case: There is only one way to partition Clusters[N-1].
7549 MinPartitions[N - 1] = 1;
7550 LastElement[N - 1] = N - 1;
7551 assert(MinJumpTableSize > 1);
7552 NumTables[N - 1] = 0;
7554 // Note: loop indexes are signed to avoid underflow.
7555 for (int64_t i = N - 2; i >= 0; i--) {
7556 // Find optimal partitioning of Clusters[i..N-1].
7557 // Baseline: Put Clusters[i] into a partition on its own.
7558 MinPartitions[i] = MinPartitions[i + 1] + 1;
7560 NumTables[i] = NumTables[i + 1];
7562 // Search for a solution that results in fewer partitions.
7563 for (int64_t j = N - 1; j > i; j--) {
7564 // Try building a partition from Clusters[i..j].
7565 if (isDense(Clusters, &TotalCases[0], i, j)) {
7566 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
7567 bool IsTable = j - i + 1 >= MinJumpTableSize;
7568 unsigned Tables = IsTable + (j == N - 1 ? 0 : NumTables[j + 1]);
7570 // If this j leads to fewer partitions, or same number of partitions
7571 // with more lookup tables, it is a better partitioning.
7572 if (NumPartitions < MinPartitions[i] ||
7573 (NumPartitions == MinPartitions[i] && Tables > NumTables[i])) {
7574 MinPartitions[i] = NumPartitions;
7576 NumTables[i] = Tables;
7582 // Iterate over the partitions, replacing some with jump tables in-place.
7583 unsigned DstIndex = 0;
7584 for (unsigned First = 0, Last; First < N; First = Last + 1) {
7585 Last = LastElement[First];
7586 assert(Last >= First);
7587 assert(DstIndex <= First);
7588 unsigned NumClusters = Last - First + 1;
7590 CaseCluster JTCluster;
7591 if (NumClusters >= MinJumpTableSize &&
7592 buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
7593 Clusters[DstIndex++] = JTCluster;
7595 for (unsigned I = First; I <= Last; ++I)
7596 std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
7599 Clusters.resize(DstIndex);
7602 bool SelectionDAGBuilder::rangeFitsInWord(const APInt &Low, const APInt &High) {
7603 // FIXME: Using the pointer type doesn't seem ideal.
7604 uint64_t BW = DAG.getDataLayout().getPointerSizeInBits();
7605 uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
7609 bool SelectionDAGBuilder::isSuitableForBitTests(unsigned NumDests,
7612 const APInt &High) {
7613 // FIXME: I don't think NumCmps is the correct metric: a single case and a
7614 // range of cases both require only one branch to lower. Just looking at the
7615 // number of clusters and destinations should be enough to decide whether to
7618 // To lower a range with bit tests, the range must fit the bitwidth of a
7620 if (!rangeFitsInWord(Low, High))
7623 // Decide whether it's profitable to lower this range with bit tests. Each
7624 // destination requires a bit test and branch, and there is an overall range
7625 // check branch. For a small number of clusters, separate comparisons might be
7626 // cheaper, and for many destinations, splitting the range might be better.
7627 return (NumDests == 1 && NumCmps >= 3) ||
7628 (NumDests == 2 && NumCmps >= 5) ||
7629 (NumDests == 3 && NumCmps >= 6);
7632 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
7633 unsigned First, unsigned Last,
7634 const SwitchInst *SI,
7635 CaseCluster &BTCluster) {
7636 assert(First <= Last);
7640 BitVector Dests(FuncInfo.MF->getNumBlockIDs());
7641 unsigned NumCmps = 0;
7642 for (int64_t I = First; I <= Last; ++I) {
7643 assert(Clusters[I].Kind == CC_Range);
7644 Dests.set(Clusters[I].MBB->getNumber());
7645 NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
7647 unsigned NumDests = Dests.count();
7649 APInt Low = Clusters[First].Low->getValue();
7650 APInt High = Clusters[Last].High->getValue();
7651 assert(Low.slt(High));
7653 if (!isSuitableForBitTests(NumDests, NumCmps, Low, High))
7659 const int BitWidth =
7660 DAG.getTargetLoweringInfo().getPointerTy().getSizeInBits();
7661 assert(rangeFitsInWord(Low, High) && "Case range must fit in bit mask!");
7663 if (Low.isNonNegative() && High.slt(BitWidth)) {
7664 // Optimize the case where all the case values fit in a
7665 // word without having to subtract minValue. In this case,
7666 // we can optimize away the subtraction.
7667 LowBound = APInt::getNullValue(Low.getBitWidth());
7671 CmpRange = High - Low;
7675 uint32_t TotalWeight = 0;
7676 for (unsigned i = First; i <= Last; ++i) {
7677 // Find the CaseBits for this destination.
7679 for (j = 0; j < CBV.size(); ++j)
7680 if (CBV[j].BB == Clusters[i].MBB)
7682 if (j == CBV.size())
7683 CBV.push_back(CaseBits(0, Clusters[i].MBB, 0, 0));
7684 CaseBits *CB = &CBV[j];
7686 // Update Mask, Bits and ExtraWeight.
7687 uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
7688 uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
7689 assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
7690 CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
7691 CB->Bits += Hi - Lo + 1;
7692 CB->ExtraWeight += Clusters[i].Weight;
7693 TotalWeight += Clusters[i].Weight;
7694 assert(TotalWeight >= Clusters[i].Weight && "Weight overflow!");
7698 std::sort(CBV.begin(), CBV.end(), [](const CaseBits &a, const CaseBits &b) {
7699 // Sort by weight first, number of bits second.
7700 if (a.ExtraWeight != b.ExtraWeight)
7701 return a.ExtraWeight > b.ExtraWeight;
7702 return a.Bits > b.Bits;
7705 for (auto &CB : CBV) {
7706 MachineBasicBlock *BitTestBB =
7707 FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
7708 BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraWeight));
7710 BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
7711 SI->getCondition(), -1U, MVT::Other, false, nullptr,
7712 nullptr, std::move(BTI));
7714 BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
7715 BitTestCases.size() - 1, TotalWeight);
7719 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
7720 const SwitchInst *SI) {
7721 // Partition Clusters into as few subsets as possible, where each subset has a
7722 // range that fits in a machine word and has <= 3 unique destinations.
7725 // Clusters must be sorted and contain Range or JumpTable clusters.
7726 assert(!Clusters.empty());
7727 assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
7728 for (const CaseCluster &C : Clusters)
7729 assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
7730 for (unsigned i = 1; i < Clusters.size(); ++i)
7731 assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
7734 // The algorithm below is not suitable for -O0.
7735 if (TM.getOptLevel() == CodeGenOpt::None)
7738 // If target does not have legal shift left, do not emit bit tests at all.
7739 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7740 EVT PTy = TLI.getPointerTy();
7741 if (!TLI.isOperationLegal(ISD::SHL, PTy))
7744 int BitWidth = PTy.getSizeInBits();
7745 const int64_t N = Clusters.size();
7747 // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
7748 SmallVector<unsigned, 8> MinPartitions(N);
7749 // LastElement[i] is the last element of the partition starting at i.
7750 SmallVector<unsigned, 8> LastElement(N);
7752 // FIXME: This might not be the best algorithm for finding bit test clusters.
7754 // Base case: There is only one way to partition Clusters[N-1].
7755 MinPartitions[N - 1] = 1;
7756 LastElement[N - 1] = N - 1;
7758 // Note: loop indexes are signed to avoid underflow.
7759 for (int64_t i = N - 2; i >= 0; --i) {
7760 // Find optimal partitioning of Clusters[i..N-1].
7761 // Baseline: Put Clusters[i] into a partition on its own.
7762 MinPartitions[i] = MinPartitions[i + 1] + 1;
7765 // Search for a solution that results in fewer partitions.
7766 // Note: the search is limited by BitWidth, reducing time complexity.
7767 for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
7768 // Try building a partition from Clusters[i..j].
7771 if (!rangeFitsInWord(Clusters[i].Low->getValue(),
7772 Clusters[j].High->getValue()))
7775 // Check nbr of destinations and cluster types.
7776 // FIXME: This works, but doesn't seem very efficient.
7777 bool RangesOnly = true;
7778 BitVector Dests(FuncInfo.MF->getNumBlockIDs());
7779 for (int64_t k = i; k <= j; k++) {
7780 if (Clusters[k].Kind != CC_Range) {
7784 Dests.set(Clusters[k].MBB->getNumber());
7786 if (!RangesOnly || Dests.count() > 3)
7789 // Check if it's a better partition.
7790 unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
7791 if (NumPartitions < MinPartitions[i]) {
7792 // Found a better partition.
7793 MinPartitions[i] = NumPartitions;
7799 // Iterate over the partitions, replacing with bit-test clusters in-place.
7800 unsigned DstIndex = 0;
7801 for (unsigned First = 0, Last; First < N; First = Last + 1) {
7802 Last = LastElement[First];
7803 assert(First <= Last);
7804 assert(DstIndex <= First);
7806 CaseCluster BitTestCluster;
7807 if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
7808 Clusters[DstIndex++] = BitTestCluster;
7810 size_t NumClusters = Last - First + 1;
7811 std::memmove(&Clusters[DstIndex], &Clusters[First],
7812 sizeof(Clusters[0]) * NumClusters);
7813 DstIndex += NumClusters;
7816 Clusters.resize(DstIndex);
7819 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
7820 MachineBasicBlock *SwitchMBB,
7821 MachineBasicBlock *DefaultMBB) {
7822 MachineFunction *CurMF = FuncInfo.MF;
7823 MachineBasicBlock *NextMBB = nullptr;
7824 MachineFunction::iterator BBI = W.MBB;
7825 if (++BBI != FuncInfo.MF->end())
7828 unsigned Size = W.LastCluster - W.FirstCluster + 1;
7830 BranchProbabilityInfo *BPI = FuncInfo.BPI;
7832 if (Size == 2 && W.MBB == SwitchMBB) {
7833 // If any two of the cases has the same destination, and if one value
7834 // is the same as the other, but has one bit unset that the other has set,
7835 // use bit manipulation to do two compares at once. For example:
7836 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
7837 // TODO: This could be extended to merge any 2 cases in switches with 3
7839 // TODO: Handle cases where W.CaseBB != SwitchBB.
7840 CaseCluster &Small = *W.FirstCluster;
7841 CaseCluster &Big = *W.LastCluster;
7843 if (Small.Low == Small.High && Big.Low == Big.High &&
7844 Small.MBB == Big.MBB) {
7845 const APInt &SmallValue = Small.Low->getValue();
7846 const APInt &BigValue = Big.Low->getValue();
7848 // Check that there is only one bit different.
7849 APInt CommonBit = BigValue ^ SmallValue;
7850 if (CommonBit.isPowerOf2()) {
7851 SDValue CondLHS = getValue(Cond);
7852 EVT VT = CondLHS.getValueType();
7853 SDLoc DL = getCurSDLoc();
7855 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
7856 DAG.getConstant(CommonBit, DL, VT));
7857 SDValue Cond = DAG.getSetCC(
7858 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
7861 // Update successor info.
7862 // Both Small and Big will jump to Small.BB, so we sum up the weights.
7863 addSuccessorWithWeight(SwitchMBB, Small.MBB, Small.Weight + Big.Weight);
7864 addSuccessorWithWeight(
7865 SwitchMBB, DefaultMBB,
7866 // The default destination is the first successor in IR.
7867 BPI ? BPI->getEdgeWeight(SwitchMBB->getBasicBlock(), (unsigned)0)
7870 // Insert the true branch.
7872 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
7873 DAG.getBasicBlock(Small.MBB));
7874 // Insert the false branch.
7875 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
7876 DAG.getBasicBlock(DefaultMBB));
7878 DAG.setRoot(BrCond);
7884 if (TM.getOptLevel() != CodeGenOpt::None) {
7885 // Order cases by weight so the most likely case will be checked first.
7886 std::sort(W.FirstCluster, W.LastCluster + 1,
7887 [](const CaseCluster &a, const CaseCluster &b) {
7888 return a.Weight > b.Weight;
7891 // Rearrange the case blocks so that the last one falls through if possible
7892 // without without changing the order of weights.
7893 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
7895 if (I->Weight > W.LastCluster->Weight)
7897 if (I->Kind == CC_Range && I->MBB == NextMBB) {
7898 std::swap(*I, *W.LastCluster);
7904 // Compute total weight.
7905 uint32_t UnhandledWeights = 0;
7906 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) {
7907 UnhandledWeights += I->Weight;
7908 assert(UnhandledWeights >= I->Weight && "Weight overflow!");
7911 MachineBasicBlock *CurMBB = W.MBB;
7912 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
7913 MachineBasicBlock *Fallthrough;
7914 if (I == W.LastCluster) {
7915 // For the last cluster, fall through to the default destination.
7916 Fallthrough = DefaultMBB;
7918 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
7919 CurMF->insert(BBI, Fallthrough);
7920 // Put Cond in a virtual register to make it available from the new blocks.
7921 ExportFromCurrentBlock(Cond);
7925 case CC_JumpTable: {
7926 // FIXME: Optimize away range check based on pivot comparisons.
7927 JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
7928 JumpTable *JT = &JTCases[I->JTCasesIndex].second;
7930 // The jump block hasn't been inserted yet; insert it here.
7931 MachineBasicBlock *JumpMBB = JT->MBB;
7932 CurMF->insert(BBI, JumpMBB);
7933 addSuccessorWithWeight(CurMBB, Fallthrough);
7934 addSuccessorWithWeight(CurMBB, JumpMBB);
7936 // The jump table header will be inserted in our current block, do the
7937 // range check, and fall through to our fallthrough block.
7938 JTH->HeaderBB = CurMBB;
7939 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
7941 // If we're in the right place, emit the jump table header right now.
7942 if (CurMBB == SwitchMBB) {
7943 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
7944 JTH->Emitted = true;
7949 // FIXME: Optimize away range check based on pivot comparisons.
7950 BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
7952 // The bit test blocks haven't been inserted yet; insert them here.
7953 for (BitTestCase &BTC : BTB->Cases)
7954 CurMF->insert(BBI, BTC.ThisBB);
7956 // Fill in fields of the BitTestBlock.
7957 BTB->Parent = CurMBB;
7958 BTB->Default = Fallthrough;
7960 // If we're in the right place, emit the bit test header header right now.
7961 if (CurMBB ==SwitchMBB) {
7962 visitBitTestHeader(*BTB, SwitchMBB);
7963 BTB->Emitted = true;
7968 const Value *RHS, *LHS, *MHS;
7970 if (I->Low == I->High) {
7971 // Check Cond == I->Low.
7977 // Check I->Low <= Cond <= I->High.
7984 // The false weight is the sum of all unhandled cases.
7985 UnhandledWeights -= I->Weight;
7986 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB, I->Weight,
7989 if (CurMBB == SwitchMBB)
7990 visitSwitchCase(CB, SwitchMBB);
7992 SwitchCases.push_back(CB);
7997 CurMBB = Fallthrough;
8001 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
8002 CaseClusterIt First,
8003 CaseClusterIt Last) {
8004 return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
8005 if (X.Weight != CC.Weight)
8006 return X.Weight > CC.Weight;
8008 // Ties are broken by comparing the case value.
8009 return X.Low->getValue().slt(CC.Low->getValue());
8013 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
8014 const SwitchWorkListItem &W,
8016 MachineBasicBlock *SwitchMBB) {
8017 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
8018 "Clusters not sorted?");
8020 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
8022 // Balance the tree based on branch weights to create a near-optimal (in terms
8023 // of search time given key frequency) binary search tree. See e.g. Kurt
8024 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
8025 CaseClusterIt LastLeft = W.FirstCluster;
8026 CaseClusterIt FirstRight = W.LastCluster;
8027 uint32_t LeftWeight = LastLeft->Weight;
8028 uint32_t RightWeight = FirstRight->Weight;
8030 // Move LastLeft and FirstRight towards each other from opposite directions to
8031 // find a partitioning of the clusters which balances the weight on both
8032 // sides. If LeftWeight and RightWeight are equal, alternate which side is
8033 // taken to ensure 0-weight nodes are distributed evenly.
8035 while (LastLeft + 1 < FirstRight) {
8036 if (LeftWeight < RightWeight || (LeftWeight == RightWeight && (I & 1)))
8037 LeftWeight += (++LastLeft)->Weight;
8039 RightWeight += (--FirstRight)->Weight;
8044 // Our binary search tree differs from a typical BST in that ours can have up
8045 // to three values in each leaf. The pivot selection above doesn't take that
8046 // into account, which means the tree might require more nodes and be less
8047 // efficient. We compensate for this here.
8049 unsigned NumLeft = LastLeft - W.FirstCluster + 1;
8050 unsigned NumRight = W.LastCluster - FirstRight + 1;
8052 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
8053 // If one side has less than 3 clusters, and the other has more than 3,
8054 // consider taking a cluster from the other side.
8056 if (NumLeft < NumRight) {
8057 // Consider moving the first cluster on the right to the left side.
8058 CaseCluster &CC = *FirstRight;
8059 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8060 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8061 if (LeftSideRank <= RightSideRank) {
8062 // Moving the cluster to the left does not demote it.
8068 assert(NumRight < NumLeft);
8069 // Consider moving the last element on the left to the right side.
8070 CaseCluster &CC = *LastLeft;
8071 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
8072 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
8073 if (RightSideRank <= LeftSideRank) {
8074 // Moving the cluster to the right does not demot it.
8084 assert(LastLeft + 1 == FirstRight);
8085 assert(LastLeft >= W.FirstCluster);
8086 assert(FirstRight <= W.LastCluster);
8088 // Use the first element on the right as pivot since we will make less-than
8089 // comparisons against it.
8090 CaseClusterIt PivotCluster = FirstRight;
8091 assert(PivotCluster > W.FirstCluster);
8092 assert(PivotCluster <= W.LastCluster);
8094 CaseClusterIt FirstLeft = W.FirstCluster;
8095 CaseClusterIt LastRight = W.LastCluster;
8097 const ConstantInt *Pivot = PivotCluster->Low;
8099 // New blocks will be inserted immediately after the current one.
8100 MachineFunction::iterator BBI = W.MBB;
8103 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
8104 // we can branch to its destination directly if it's squeezed exactly in
8105 // between the known lower bound and Pivot - 1.
8106 MachineBasicBlock *LeftMBB;
8107 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
8108 FirstLeft->Low == W.GE &&
8109 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
8110 LeftMBB = FirstLeft->MBB;
8112 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8113 FuncInfo.MF->insert(BBI, LeftMBB);
8114 WorkList.push_back({LeftMBB, FirstLeft, LastLeft, W.GE, Pivot});
8115 // Put Cond in a virtual register to make it available from the new blocks.
8116 ExportFromCurrentBlock(Cond);
8119 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
8120 // single cluster, RHS.Low == Pivot, and we can branch to its destination
8121 // directly if RHS.High equals the current upper bound.
8122 MachineBasicBlock *RightMBB;
8123 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
8124 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
8125 RightMBB = FirstRight->MBB;
8127 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
8128 FuncInfo.MF->insert(BBI, RightMBB);
8129 WorkList.push_back({RightMBB, FirstRight, LastRight, Pivot, W.LT});
8130 // Put Cond in a virtual register to make it available from the new blocks.
8131 ExportFromCurrentBlock(Cond);
8134 // Create the CaseBlock record that will be used to lower the branch.
8135 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
8136 LeftWeight, RightWeight);
8138 if (W.MBB == SwitchMBB)
8139 visitSwitchCase(CB, SwitchMBB);
8141 SwitchCases.push_back(CB);
8144 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
8145 // Extract cases from the switch.
8146 BranchProbabilityInfo *BPI = FuncInfo.BPI;
8147 CaseClusterVector Clusters;
8148 Clusters.reserve(SI.getNumCases());
8149 for (auto I : SI.cases()) {
8150 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
8151 const ConstantInt *CaseVal = I.getCaseValue();
8153 BPI ? BPI->getEdgeWeight(SI.getParent(), I.getSuccessorIndex()) : 0;
8154 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Weight));
8157 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
8159 // Cluster adjacent cases with the same destination. We do this at all
8160 // optimization levels because it's cheap to do and will make codegen faster
8161 // if there are many clusters.
8162 sortAndRangeify(Clusters);
8164 if (TM.getOptLevel() != CodeGenOpt::None) {
8165 // Replace an unreachable default with the most popular destination.
8166 // FIXME: Exploit unreachable default more aggressively.
8167 bool UnreachableDefault =
8168 isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
8169 if (UnreachableDefault && !Clusters.empty()) {
8170 DenseMap<const BasicBlock *, unsigned> Popularity;
8171 unsigned MaxPop = 0;
8172 const BasicBlock *MaxBB = nullptr;
8173 for (auto I : SI.cases()) {
8174 const BasicBlock *BB = I.getCaseSuccessor();
8175 if (++Popularity[BB] > MaxPop) {
8176 MaxPop = Popularity[BB];
8181 assert(MaxPop > 0 && MaxBB);
8182 DefaultMBB = FuncInfo.MBBMap[MaxBB];
8184 // Remove cases that were pointing to the destination that is now the
8186 CaseClusterVector New;
8187 New.reserve(Clusters.size());
8188 for (CaseCluster &CC : Clusters) {
8189 if (CC.MBB != DefaultMBB)
8192 Clusters = std::move(New);
8196 // If there is only the default destination, jump there directly.
8197 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
8198 if (Clusters.empty()) {
8199 SwitchMBB->addSuccessor(DefaultMBB);
8200 if (DefaultMBB != NextBlock(SwitchMBB)) {
8201 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
8202 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
8207 findJumpTables(Clusters, &SI, DefaultMBB);
8208 findBitTestClusters(Clusters, &SI);
8211 dbgs() << "Case clusters: ";
8212 for (const CaseCluster &C : Clusters) {
8213 if (C.Kind == CC_JumpTable) dbgs() << "JT:";
8214 if (C.Kind == CC_BitTests) dbgs() << "BT:";
8216 C.Low->getValue().print(dbgs(), true);
8217 if (C.Low != C.High) {
8219 C.High->getValue().print(dbgs(), true);
8226 assert(!Clusters.empty());
8227 SwitchWorkList WorkList;
8228 CaseClusterIt First = Clusters.begin();
8229 CaseClusterIt Last = Clusters.end() - 1;
8230 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr});
8232 while (!WorkList.empty()) {
8233 SwitchWorkListItem W = WorkList.back();
8234 WorkList.pop_back();
8235 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
8237 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None) {
8238 // For optimized builds, lower large range as a balanced binary tree.
8239 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
8243 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);