[x86] fix assert with horizontal math + broadcast of vector (PR43402)
[llvm-core.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuilder.cpp
blob7f9266bc7b43a9d6f805cfad6cff2a9ec2b8914e
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //===----------------------------------------------------------------------===//
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BranchProbabilityInfo.h"
31 #include "llvm/Analysis/ConstantFolding.h"
32 #include "llvm/Analysis/EHPersonalities.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/MemoryLocation.h"
35 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Analysis/VectorUtils.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/FunctionLoweringInfo.h"
40 #include "llvm/CodeGen/GCMetadata.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineJumpTableInfo.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/RuntimeLibcalls.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
56 #include "llvm/CodeGen/StackMaps.h"
57 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
58 #include "llvm/CodeGen/TargetFrameLowering.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/CodeGen/WinEHFuncInfo.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/BasicBlock.h"
69 #include "llvm/IR/CFG.h"
70 #include "llvm/IR/CallSite.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfoMetadata.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/Intrinsics.h"
87 #include "llvm/IR/LLVMContext.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/Operator.h"
91 #include "llvm/IR/PatternMatch.h"
92 #include "llvm/IR/Statepoint.h"
93 #include "llvm/IR/Type.h"
94 #include "llvm/IR/User.h"
95 #include "llvm/IR/Value.h"
96 #include "llvm/MC/MCContext.h"
97 #include "llvm/MC/MCSymbol.h"
98 #include "llvm/Support/AtomicOrdering.h"
99 #include "llvm/Support/BranchProbability.h"
100 #include "llvm/Support/Casting.h"
101 #include "llvm/Support/CodeGen.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Compiler.h"
104 #include "llvm/Support/Debug.h"
105 #include "llvm/Support/ErrorHandling.h"
106 #include "llvm/Support/MachineValueType.h"
107 #include "llvm/Support/MathExtras.h"
108 #include "llvm/Support/raw_ostream.h"
109 #include "llvm/Target/TargetIntrinsicInfo.h"
110 #include "llvm/Target/TargetMachine.h"
111 #include "llvm/Target/TargetOptions.h"
112 #include "llvm/Transforms/Utils/Local.h"
113 #include <algorithm>
114 #include <cassert>
115 #include <cstddef>
116 #include <cstdint>
117 #include <cstring>
118 #include <iterator>
119 #include <limits>
120 #include <numeric>
121 #include <tuple>
122 #include <utility>
123 #include <vector>
125 using namespace llvm;
126 using namespace PatternMatch;
127 using namespace SwitchCG;
129 #define DEBUG_TYPE "isel"
131 /// LimitFloatPrecision - Generate low-precision inline sequences for
132 /// some float libcalls (6, 8 or 12 bits).
133 static unsigned LimitFloatPrecision;
135 static cl::opt<unsigned, true>
136 LimitFPPrecision("limit-float-precision",
137 cl::desc("Generate low-precision inline sequences "
138 "for some float libcalls"),
139 cl::location(LimitFloatPrecision), cl::Hidden,
140 cl::init(0));
142 static cl::opt<unsigned> SwitchPeelThreshold(
143 "switch-peel-threshold", cl::Hidden, cl::init(66),
144 cl::desc("Set the case probability threshold for peeling the case from a "
145 "switch statement. A value greater than 100 will void this "
146 "optimization"));
148 // Limit the width of DAG chains. This is important in general to prevent
149 // DAG-based analysis from blowing up. For example, alias analysis and
150 // load clustering may not complete in reasonable time. It is difficult to
151 // recognize and avoid this situation within each individual analysis, and
152 // future analyses are likely to have the same behavior. Limiting DAG width is
153 // the safe approach and will be especially important with global DAGs.
155 // MaxParallelChains default is arbitrarily high to avoid affecting
156 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
157 // sequence over this should have been converted to llvm.memcpy by the
158 // frontend. It is easy to induce this behavior with .ll code such as:
159 // %buffer = alloca [4096 x i8]
160 // %data = load [4096 x i8]* %argPtr
161 // store [4096 x i8] %data, [4096 x i8]* %buffer
162 static const unsigned MaxParallelChains = 64;
164 // Return the calling convention if the Value passed requires ABI mangling as it
165 // is a parameter to a function or a return value from a function which is not
166 // an intrinsic.
167 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
168 if (auto *R = dyn_cast<ReturnInst>(V))
169 return R->getParent()->getParent()->getCallingConv();
171 if (auto *CI = dyn_cast<CallInst>(V)) {
172 const bool IsInlineAsm = CI->isInlineAsm();
173 const bool IsIndirectFunctionCall =
174 !IsInlineAsm && !CI->getCalledFunction();
176 // It is possible that the call instruction is an inline asm statement or an
177 // indirect function call in which case the return value of
178 // getCalledFunction() would be nullptr.
179 const bool IsInstrinsicCall =
180 !IsInlineAsm && !IsIndirectFunctionCall &&
181 CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
183 if (!IsInlineAsm && !IsInstrinsicCall)
184 return CI->getCallingConv();
187 return None;
190 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
191 const SDValue *Parts, unsigned NumParts,
192 MVT PartVT, EVT ValueVT, const Value *V,
193 Optional<CallingConv::ID> CC);
195 /// getCopyFromParts - Create a value that contains the specified legal parts
196 /// combined into the value they represent. If the parts combine to a type
197 /// larger than ValueVT then AssertOp can be used to specify whether the extra
198 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
199 /// (ISD::AssertSext).
200 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
201 const SDValue *Parts, unsigned NumParts,
202 MVT PartVT, EVT ValueVT, const Value *V,
203 Optional<CallingConv::ID> CC = None,
204 Optional<ISD::NodeType> AssertOp = None) {
205 if (ValueVT.isVector())
206 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
207 CC);
209 assert(NumParts > 0 && "No parts to assemble!");
210 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
211 SDValue Val = Parts[0];
213 if (NumParts > 1) {
214 // Assemble the value from multiple parts.
215 if (ValueVT.isInteger()) {
216 unsigned PartBits = PartVT.getSizeInBits();
217 unsigned ValueBits = ValueVT.getSizeInBits();
219 // Assemble the power of 2 part.
220 unsigned RoundParts =
221 (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
222 unsigned RoundBits = PartBits * RoundParts;
223 EVT RoundVT = RoundBits == ValueBits ?
224 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
225 SDValue Lo, Hi;
227 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
229 if (RoundParts > 2) {
230 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
231 PartVT, HalfVT, V);
232 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
233 RoundParts / 2, PartVT, HalfVT, V);
234 } else {
235 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
236 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
239 if (DAG.getDataLayout().isBigEndian())
240 std::swap(Lo, Hi);
242 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
244 if (RoundParts < NumParts) {
245 // Assemble the trailing non-power-of-2 part.
246 unsigned OddParts = NumParts - RoundParts;
247 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
248 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
249 OddVT, V, CC);
251 // Combine the round and odd parts.
252 Lo = Val;
253 if (DAG.getDataLayout().isBigEndian())
254 std::swap(Lo, Hi);
255 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
256 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
257 Hi =
258 DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
259 DAG.getConstant(Lo.getValueSizeInBits(), DL,
260 TLI.getPointerTy(DAG.getDataLayout())));
261 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
262 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
264 } else if (PartVT.isFloatingPoint()) {
265 // FP split into multiple FP parts (for ppcf128)
266 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
267 "Unexpected split");
268 SDValue Lo, Hi;
269 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
270 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
271 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
272 std::swap(Lo, Hi);
273 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
274 } else {
275 // FP split into integer parts (soft fp)
276 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
277 !PartVT.isVector() && "Unexpected split");
278 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
279 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
283 // There is now one part, held in Val. Correct it to match ValueVT.
284 // PartEVT is the type of the register class that holds the value.
285 // ValueVT is the type of the inline asm operation.
286 EVT PartEVT = Val.getValueType();
288 if (PartEVT == ValueVT)
289 return Val;
291 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
292 ValueVT.bitsLT(PartEVT)) {
293 // For an FP value in an integer part, we need to truncate to the right
294 // width first.
295 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
296 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
299 // Handle types that have the same size.
300 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
301 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
303 // Handle types with different sizes.
304 if (PartEVT.isInteger() && ValueVT.isInteger()) {
305 if (ValueVT.bitsLT(PartEVT)) {
306 // For a truncate, see if we have any information to
307 // indicate whether the truncated bits will always be
308 // zero or sign-extension.
309 if (AssertOp.hasValue())
310 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
311 DAG.getValueType(ValueVT));
312 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
314 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
317 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
318 // FP_ROUND's are always exact here.
319 if (ValueVT.bitsLT(Val.getValueType()))
320 return DAG.getNode(
321 ISD::FP_ROUND, DL, ValueVT, Val,
322 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
324 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
327 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
328 // then truncating.
329 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
330 ValueVT.bitsLT(PartEVT)) {
331 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
332 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
335 report_fatal_error("Unknown mismatch in getCopyFromParts!");
338 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
339 const Twine &ErrMsg) {
340 const Instruction *I = dyn_cast_or_null<Instruction>(V);
341 if (!V)
342 return Ctx.emitError(ErrMsg);
344 const char *AsmError = ", possible invalid constraint for vector type";
345 if (const CallInst *CI = dyn_cast<CallInst>(I))
346 if (isa<InlineAsm>(CI->getCalledValue()))
347 return Ctx.emitError(I, ErrMsg + AsmError);
349 return Ctx.emitError(I, ErrMsg);
352 /// getCopyFromPartsVector - Create a value that contains the specified legal
353 /// parts combined into the value they represent. If the parts combine to a
354 /// type larger than ValueVT then AssertOp can be used to specify whether the
355 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
356 /// ValueVT (ISD::AssertSext).
357 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
358 const SDValue *Parts, unsigned NumParts,
359 MVT PartVT, EVT ValueVT, const Value *V,
360 Optional<CallingConv::ID> CallConv) {
361 assert(ValueVT.isVector() && "Not a vector value");
362 assert(NumParts > 0 && "No parts to assemble!");
363 const bool IsABIRegCopy = CallConv.hasValue();
365 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
366 SDValue Val = Parts[0];
368 // Handle a multi-element vector.
369 if (NumParts > 1) {
370 EVT IntermediateVT;
371 MVT RegisterVT;
372 unsigned NumIntermediates;
373 unsigned NumRegs;
375 if (IsABIRegCopy) {
376 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
377 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
378 NumIntermediates, RegisterVT);
379 } else {
380 NumRegs =
381 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
382 NumIntermediates, RegisterVT);
385 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
386 NumParts = NumRegs; // Silence a compiler warning.
387 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
388 assert(RegisterVT.getSizeInBits() ==
389 Parts[0].getSimpleValueType().getSizeInBits() &&
390 "Part type sizes don't match!");
392 // Assemble the parts into intermediate operands.
393 SmallVector<SDValue, 8> Ops(NumIntermediates);
394 if (NumIntermediates == NumParts) {
395 // If the register was not expanded, truncate or copy the value,
396 // as appropriate.
397 for (unsigned i = 0; i != NumParts; ++i)
398 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
399 PartVT, IntermediateVT, V);
400 } else if (NumParts > 0) {
401 // If the intermediate type was expanded, build the intermediate
402 // operands from the parts.
403 assert(NumParts % NumIntermediates == 0 &&
404 "Must expand into a divisible number of parts!");
405 unsigned Factor = NumParts / NumIntermediates;
406 for (unsigned i = 0; i != NumIntermediates; ++i)
407 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
408 PartVT, IntermediateVT, V);
411 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
412 // intermediate operands.
413 EVT BuiltVectorTy =
414 EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
415 (IntermediateVT.isVector()
416 ? IntermediateVT.getVectorNumElements() * NumParts
417 : NumIntermediates));
418 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
419 : ISD::BUILD_VECTOR,
420 DL, BuiltVectorTy, Ops);
423 // There is now one part, held in Val. Correct it to match ValueVT.
424 EVT PartEVT = Val.getValueType();
426 if (PartEVT == ValueVT)
427 return Val;
429 if (PartEVT.isVector()) {
430 // If the element type of the source/dest vectors are the same, but the
431 // parts vector has more elements than the value vector, then we have a
432 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
433 // elements we want.
434 if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
435 assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
436 "Cannot narrow, it would be a lossy transformation");
437 return DAG.getNode(
438 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
439 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
442 // Vector/Vector bitcast.
443 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
444 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
446 assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
447 "Cannot handle this kind of promotion");
448 // Promoted vector extract
449 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
453 // Trivial bitcast if the types are the same size and the destination
454 // vector type is legal.
455 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
456 TLI.isTypeLegal(ValueVT))
457 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
459 if (ValueVT.getVectorNumElements() != 1) {
460 // Certain ABIs require that vectors are passed as integers. For vectors
461 // are the same size, this is an obvious bitcast.
462 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
463 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
464 } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
465 // Bitcast Val back the original type and extract the corresponding
466 // vector we want.
467 unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
468 EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
469 ValueVT.getVectorElementType(), Elts);
470 Val = DAG.getBitcast(WiderVecType, Val);
471 return DAG.getNode(
472 ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
473 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
476 diagnosePossiblyInvalidConstraint(
477 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
478 return DAG.getUNDEF(ValueVT);
481 // Handle cases such as i8 -> <1 x i1>
482 EVT ValueSVT = ValueVT.getVectorElementType();
483 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
484 Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
485 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
487 return DAG.getBuildVector(ValueVT, DL, Val);
490 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
491 SDValue Val, SDValue *Parts, unsigned NumParts,
492 MVT PartVT, const Value *V,
493 Optional<CallingConv::ID> CallConv);
495 /// getCopyToParts - Create a series of nodes that contain the specified value
496 /// split into legal parts. If the parts contain more bits than Val, then, for
497 /// integers, ExtendKind can be used to specify how to generate the extra bits.
498 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
499 SDValue *Parts, unsigned NumParts, MVT PartVT,
500 const Value *V,
501 Optional<CallingConv::ID> CallConv = None,
502 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
503 EVT ValueVT = Val.getValueType();
505 // Handle the vector case separately.
506 if (ValueVT.isVector())
507 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
508 CallConv);
510 unsigned PartBits = PartVT.getSizeInBits();
511 unsigned OrigNumParts = NumParts;
512 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
513 "Copying to an illegal type!");
515 if (NumParts == 0)
516 return;
518 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
519 EVT PartEVT = PartVT;
520 if (PartEVT == ValueVT) {
521 assert(NumParts == 1 && "No-op copy with multiple parts!");
522 Parts[0] = Val;
523 return;
526 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
527 // If the parts cover more bits than the value has, promote the value.
528 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
529 assert(NumParts == 1 && "Do not know what to promote to!");
530 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
531 } else {
532 if (ValueVT.isFloatingPoint()) {
533 // FP values need to be bitcast, then extended if they are being put
534 // into a larger container.
535 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
536 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
538 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
539 ValueVT.isInteger() &&
540 "Unknown mismatch!");
541 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
542 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
543 if (PartVT == MVT::x86mmx)
544 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
546 } else if (PartBits == ValueVT.getSizeInBits()) {
547 // Different types of the same size.
548 assert(NumParts == 1 && PartEVT != ValueVT);
549 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
550 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
551 // If the parts cover less bits than value has, truncate the value.
552 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
553 ValueVT.isInteger() &&
554 "Unknown mismatch!");
555 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
556 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
557 if (PartVT == MVT::x86mmx)
558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561 // The value may have changed - recompute ValueVT.
562 ValueVT = Val.getValueType();
563 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
564 "Failed to tile the value with PartVT!");
566 if (NumParts == 1) {
567 if (PartEVT != ValueVT) {
568 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
569 "scalar-to-vector conversion failed");
570 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
573 Parts[0] = Val;
574 return;
577 // Expand the value into multiple parts.
578 if (NumParts & (NumParts - 1)) {
579 // The number of parts is not a power of 2. Split off and copy the tail.
580 assert(PartVT.isInteger() && ValueVT.isInteger() &&
581 "Do not know what to expand to!");
582 unsigned RoundParts = 1 << Log2_32(NumParts);
583 unsigned RoundBits = RoundParts * PartBits;
584 unsigned OddParts = NumParts - RoundParts;
585 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
586 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
588 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
589 CallConv);
591 if (DAG.getDataLayout().isBigEndian())
592 // The odd parts were reversed by getCopyToParts - unreverse them.
593 std::reverse(Parts + RoundParts, Parts + NumParts);
595 NumParts = RoundParts;
596 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
597 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
600 // The number of parts is a power of 2. Repeatedly bisect the value using
601 // EXTRACT_ELEMENT.
602 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
603 EVT::getIntegerVT(*DAG.getContext(),
604 ValueVT.getSizeInBits()),
605 Val);
607 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
608 for (unsigned i = 0; i < NumParts; i += StepSize) {
609 unsigned ThisBits = StepSize * PartBits / 2;
610 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
611 SDValue &Part0 = Parts[i];
612 SDValue &Part1 = Parts[i+StepSize/2];
614 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
615 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
616 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
617 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
619 if (ThisBits == PartBits && ThisVT != PartVT) {
620 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
621 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
626 if (DAG.getDataLayout().isBigEndian())
627 std::reverse(Parts, Parts + OrigNumParts);
630 static SDValue widenVectorToPartType(SelectionDAG &DAG,
631 SDValue Val, const SDLoc &DL, EVT PartVT) {
632 if (!PartVT.isVector())
633 return SDValue();
635 EVT ValueVT = Val.getValueType();
636 unsigned PartNumElts = PartVT.getVectorNumElements();
637 unsigned ValueNumElts = ValueVT.getVectorNumElements();
638 if (PartNumElts > ValueNumElts &&
639 PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
640 EVT ElementVT = PartVT.getVectorElementType();
641 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
642 // undef elements.
643 SmallVector<SDValue, 16> Ops;
644 DAG.ExtractVectorElements(Val, Ops);
645 SDValue EltUndef = DAG.getUNDEF(ElementVT);
646 for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
647 Ops.push_back(EltUndef);
649 // FIXME: Use CONCAT for 2x -> 4x.
650 return DAG.getBuildVector(PartVT, DL, Ops);
653 return SDValue();
656 /// getCopyToPartsVector - Create a series of nodes that contain the specified
657 /// value split into legal parts.
658 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
659 SDValue Val, SDValue *Parts, unsigned NumParts,
660 MVT PartVT, const Value *V,
661 Optional<CallingConv::ID> CallConv) {
662 EVT ValueVT = Val.getValueType();
663 assert(ValueVT.isVector() && "Not a vector");
664 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
665 const bool IsABIRegCopy = CallConv.hasValue();
667 if (NumParts == 1) {
668 EVT PartEVT = PartVT;
669 if (PartEVT == ValueVT) {
670 // Nothing to do.
671 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
672 // Bitconvert vector->vector case.
673 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
674 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
675 Val = Widened;
676 } else if (PartVT.isVector() &&
677 PartEVT.getVectorElementType().bitsGE(
678 ValueVT.getVectorElementType()) &&
679 PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
681 // Promoted vector extract
682 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
683 } else {
684 if (ValueVT.getVectorNumElements() == 1) {
685 Val = DAG.getNode(
686 ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
687 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
688 } else {
689 assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
690 "lossy conversion of vector to scalar type");
691 EVT IntermediateType =
692 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
693 Val = DAG.getBitcast(IntermediateType, Val);
694 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
698 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
699 Parts[0] = Val;
700 return;
703 // Handle a multi-element vector.
704 EVT IntermediateVT;
705 MVT RegisterVT;
706 unsigned NumIntermediates;
707 unsigned NumRegs;
708 if (IsABIRegCopy) {
709 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
710 *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
711 NumIntermediates, RegisterVT);
712 } else {
713 NumRegs =
714 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
715 NumIntermediates, RegisterVT);
718 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
719 NumParts = NumRegs; // Silence a compiler warning.
720 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
722 unsigned IntermediateNumElts = IntermediateVT.isVector() ?
723 IntermediateVT.getVectorNumElements() : 1;
725 // Convert the vector to the appropiate type if necessary.
726 unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
728 EVT BuiltVectorTy = EVT::getVectorVT(
729 *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
730 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
731 if (ValueVT != BuiltVectorTy) {
732 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
733 Val = Widened;
735 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
738 // Split the vector into intermediate operands.
739 SmallVector<SDValue, 8> Ops(NumIntermediates);
740 for (unsigned i = 0; i != NumIntermediates; ++i) {
741 if (IntermediateVT.isVector()) {
742 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
743 DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
744 } else {
745 Ops[i] = DAG.getNode(
746 ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
747 DAG.getConstant(i, DL, IdxVT));
751 // Split the intermediate operands into legal parts.
752 if (NumParts == NumIntermediates) {
753 // If the register was not expanded, promote or copy the value,
754 // as appropriate.
755 for (unsigned i = 0; i != NumParts; ++i)
756 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
757 } else if (NumParts > 0) {
758 // If the intermediate type was expanded, split each the value into
759 // legal parts.
760 assert(NumIntermediates != 0 && "division by zero");
761 assert(NumParts % NumIntermediates == 0 &&
762 "Must expand into a divisible number of parts!");
763 unsigned Factor = NumParts / NumIntermediates;
764 for (unsigned i = 0; i != NumIntermediates; ++i)
765 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
766 CallConv);
770 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
771 EVT valuevt, Optional<CallingConv::ID> CC)
772 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
773 RegCount(1, regs.size()), CallConv(CC) {}
775 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
776 const DataLayout &DL, unsigned Reg, Type *Ty,
777 Optional<CallingConv::ID> CC) {
778 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
780 CallConv = CC;
782 for (EVT ValueVT : ValueVTs) {
783 unsigned NumRegs =
784 isABIMangled()
785 ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
786 : TLI.getNumRegisters(Context, ValueVT);
787 MVT RegisterVT =
788 isABIMangled()
789 ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
790 : TLI.getRegisterType(Context, ValueVT);
791 for (unsigned i = 0; i != NumRegs; ++i)
792 Regs.push_back(Reg + i);
793 RegVTs.push_back(RegisterVT);
794 RegCount.push_back(NumRegs);
795 Reg += NumRegs;
799 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
800 FunctionLoweringInfo &FuncInfo,
801 const SDLoc &dl, SDValue &Chain,
802 SDValue *Flag, const Value *V) const {
803 // A Value with type {} or [0 x %t] needs no registers.
804 if (ValueVTs.empty())
805 return SDValue();
807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
809 // Assemble the legal parts into the final values.
810 SmallVector<SDValue, 4> Values(ValueVTs.size());
811 SmallVector<SDValue, 8> Parts;
812 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
813 // Copy the legal parts from the registers.
814 EVT ValueVT = ValueVTs[Value];
815 unsigned NumRegs = RegCount[Value];
816 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
817 *DAG.getContext(),
818 CallConv.getValue(), RegVTs[Value])
819 : RegVTs[Value];
821 Parts.resize(NumRegs);
822 for (unsigned i = 0; i != NumRegs; ++i) {
823 SDValue P;
824 if (!Flag) {
825 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
826 } else {
827 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
828 *Flag = P.getValue(2);
831 Chain = P.getValue(1);
832 Parts[i] = P;
834 // If the source register was virtual and if we know something about it,
835 // add an assert node.
836 if (!Register::isVirtualRegister(Regs[Part + i]) ||
837 !RegisterVT.isInteger())
838 continue;
840 const FunctionLoweringInfo::LiveOutInfo *LOI =
841 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
842 if (!LOI)
843 continue;
845 unsigned RegSize = RegisterVT.getScalarSizeInBits();
846 unsigned NumSignBits = LOI->NumSignBits;
847 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
849 if (NumZeroBits == RegSize) {
850 // The current value is a zero.
851 // Explicitly express that as it would be easier for
852 // optimizations to kick in.
853 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
854 continue;
857 // FIXME: We capture more information than the dag can represent. For
858 // now, just use the tightest assertzext/assertsext possible.
859 bool isSExt;
860 EVT FromVT(MVT::Other);
861 if (NumZeroBits) {
862 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
863 isSExt = false;
864 } else if (NumSignBits > 1) {
865 FromVT =
866 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
867 isSExt = true;
868 } else {
869 continue;
871 // Add an assertion node.
872 assert(FromVT != MVT::Other);
873 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
874 RegisterVT, P, DAG.getValueType(FromVT));
877 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
878 RegisterVT, ValueVT, V, CallConv);
879 Part += NumRegs;
880 Parts.clear();
883 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
886 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
887 const SDLoc &dl, SDValue &Chain, SDValue *Flag,
888 const Value *V,
889 ISD::NodeType PreferredExtendType) const {
890 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
891 ISD::NodeType ExtendKind = PreferredExtendType;
893 // Get the list of the values's legal parts.
894 unsigned NumRegs = Regs.size();
895 SmallVector<SDValue, 8> Parts(NumRegs);
896 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
897 unsigned NumParts = RegCount[Value];
899 MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
900 *DAG.getContext(),
901 CallConv.getValue(), RegVTs[Value])
902 : RegVTs[Value];
904 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
905 ExtendKind = ISD::ZERO_EXTEND;
907 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
908 NumParts, RegisterVT, V, CallConv, ExtendKind);
909 Part += NumParts;
912 // Copy the parts into the registers.
913 SmallVector<SDValue, 8> Chains(NumRegs);
914 for (unsigned i = 0; i != NumRegs; ++i) {
915 SDValue Part;
916 if (!Flag) {
917 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
918 } else {
919 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
920 *Flag = Part.getValue(1);
923 Chains[i] = Part.getValue(0);
926 if (NumRegs == 1 || Flag)
927 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
928 // flagged to it. That is the CopyToReg nodes and the user are considered
929 // a single scheduling unit. If we create a TokenFactor and return it as
930 // chain, then the TokenFactor is both a predecessor (operand) of the
931 // user as well as a successor (the TF operands are flagged to the user).
932 // c1, f1 = CopyToReg
933 // c2, f2 = CopyToReg
934 // c3 = TokenFactor c1, c2
935 // ...
936 // = op c3, ..., f2
937 Chain = Chains[NumRegs-1];
938 else
939 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
942 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
943 unsigned MatchingIdx, const SDLoc &dl,
944 SelectionDAG &DAG,
945 std::vector<SDValue> &Ops) const {
946 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
948 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
949 if (HasMatching)
950 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
951 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
952 // Put the register class of the virtual registers in the flag word. That
953 // way, later passes can recompute register class constraints for inline
954 // assembly as well as normal instructions.
955 // Don't do this for tied operands that can use the regclass information
956 // from the def.
957 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
958 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
959 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
962 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
963 Ops.push_back(Res);
965 if (Code == InlineAsm::Kind_Clobber) {
966 // Clobbers should always have a 1:1 mapping with registers, and may
967 // reference registers that have illegal (e.g. vector) types. Hence, we
968 // shouldn't try to apply any sort of splitting logic to them.
969 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
970 "No 1:1 mapping from clobbers to regs?");
971 unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
972 (void)SP;
973 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
974 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
975 assert(
976 (Regs[I] != SP ||
977 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
978 "If we clobbered the stack pointer, MFI should know about it.");
980 return;
983 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
984 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
985 MVT RegisterVT = RegVTs[Value];
986 for (unsigned i = 0; i != NumRegs; ++i) {
987 assert(Reg < Regs.size() && "Mismatch in # registers expected");
988 unsigned TheReg = Regs[Reg++];
989 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
994 SmallVector<std::pair<unsigned, unsigned>, 4>
995 RegsForValue::getRegsAndSizes() const {
996 SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
997 unsigned I = 0;
998 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
999 unsigned RegCount = std::get<0>(CountAndVT);
1000 MVT RegisterVT = std::get<1>(CountAndVT);
1001 unsigned RegisterSize = RegisterVT.getSizeInBits();
1002 for (unsigned E = I + RegCount; I != E; ++I)
1003 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1005 return OutVec;
1008 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1009 const TargetLibraryInfo *li) {
1010 AA = aa;
1011 GFI = gfi;
1012 LibInfo = li;
1013 DL = &DAG.getDataLayout();
1014 Context = DAG.getContext();
1015 LPadToCallSiteMap.clear();
1016 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1019 void SelectionDAGBuilder::clear() {
1020 NodeMap.clear();
1021 UnusedArgNodeMap.clear();
1022 PendingLoads.clear();
1023 PendingExports.clear();
1024 CurInst = nullptr;
1025 HasTailCall = false;
1026 SDNodeOrder = LowestSDNodeOrder;
1027 StatepointLowering.clear();
1030 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1031 DanglingDebugInfoMap.clear();
1034 SDValue SelectionDAGBuilder::getRoot() {
1035 if (PendingLoads.empty())
1036 return DAG.getRoot();
1038 if (PendingLoads.size() == 1) {
1039 SDValue Root = PendingLoads[0];
1040 DAG.setRoot(Root);
1041 PendingLoads.clear();
1042 return Root;
1045 // Otherwise, we have to make a token factor node.
1046 SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1047 PendingLoads.clear();
1048 DAG.setRoot(Root);
1049 return Root;
1052 SDValue SelectionDAGBuilder::getControlRoot() {
1053 SDValue Root = DAG.getRoot();
1055 if (PendingExports.empty())
1056 return Root;
1058 // Turn all of the CopyToReg chains into one factored node.
1059 if (Root.getOpcode() != ISD::EntryToken) {
1060 unsigned i = 0, e = PendingExports.size();
1061 for (; i != e; ++i) {
1062 assert(PendingExports[i].getNode()->getNumOperands() > 1);
1063 if (PendingExports[i].getNode()->getOperand(0) == Root)
1064 break; // Don't add the root if we already indirectly depend on it.
1067 if (i == e)
1068 PendingExports.push_back(Root);
1071 Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1072 PendingExports);
1073 PendingExports.clear();
1074 DAG.setRoot(Root);
1075 return Root;
1078 void SelectionDAGBuilder::visit(const Instruction &I) {
1079 // Set up outgoing PHI node register values before emitting the terminator.
1080 if (I.isTerminator()) {
1081 HandlePHINodesInSuccessorBlocks(I.getParent());
1084 // Increase the SDNodeOrder if dealing with a non-debug instruction.
1085 if (!isa<DbgInfoIntrinsic>(I))
1086 ++SDNodeOrder;
1088 CurInst = &I;
1090 visit(I.getOpcode(), I);
1092 if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1093 // Propagate the fast-math-flags of this IR instruction to the DAG node that
1094 // maps to this instruction.
1095 // TODO: We could handle all flags (nsw, etc) here.
1096 // TODO: If an IR instruction maps to >1 node, only the final node will have
1097 // flags set.
1098 if (SDNode *Node = getNodeForIRValue(&I)) {
1099 SDNodeFlags IncomingFlags;
1100 IncomingFlags.copyFMF(*FPMO);
1101 if (!Node->getFlags().isDefined())
1102 Node->setFlags(IncomingFlags);
1103 else
1104 Node->intersectFlagsWith(IncomingFlags);
1108 if (!I.isTerminator() && !HasTailCall &&
1109 !isStatepoint(&I)) // statepoints handle their exports internally
1110 CopyToExportRegsIfNeeded(&I);
1112 CurInst = nullptr;
1115 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1116 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1119 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1120 // Note: this doesn't use InstVisitor, because it has to work with
1121 // ConstantExpr's in addition to instructions.
1122 switch (Opcode) {
1123 default: llvm_unreachable("Unknown instruction type encountered!");
1124 // Build the switch statement using the Instruction.def file.
1125 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1126 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1127 #include "llvm/IR/Instruction.def"
1131 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1132 const DIExpression *Expr) {
1133 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1134 const DbgValueInst *DI = DDI.getDI();
1135 DIVariable *DanglingVariable = DI->getVariable();
1136 DIExpression *DanglingExpr = DI->getExpression();
1137 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1138 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1139 return true;
1141 return false;
1144 for (auto &DDIMI : DanglingDebugInfoMap) {
1145 DanglingDebugInfoVector &DDIV = DDIMI.second;
1147 // If debug info is to be dropped, run it through final checks to see
1148 // whether it can be salvaged.
1149 for (auto &DDI : DDIV)
1150 if (isMatchingDbgValue(DDI))
1151 salvageUnresolvedDbgValue(DDI);
1153 DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1157 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1158 // generate the debug data structures now that we've seen its definition.
1159 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1160 SDValue Val) {
1161 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1162 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1163 return;
1165 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1166 for (auto &DDI : DDIV) {
1167 const DbgValueInst *DI = DDI.getDI();
1168 assert(DI && "Ill-formed DanglingDebugInfo");
1169 DebugLoc dl = DDI.getdl();
1170 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1171 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1172 DILocalVariable *Variable = DI->getVariable();
1173 DIExpression *Expr = DI->getExpression();
1174 assert(Variable->isValidLocationForIntrinsic(dl) &&
1175 "Expected inlined-at fields to agree");
1176 SDDbgValue *SDV;
1177 if (Val.getNode()) {
1178 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1179 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1180 // we couldn't resolve it directly when examining the DbgValue intrinsic
1181 // in the first place we should not be more successful here). Unless we
1182 // have some test case that prove this to be correct we should avoid
1183 // calling EmitFuncArgumentDbgValue here.
1184 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1185 LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1186 << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
1187 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1188 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1189 // inserted after the definition of Val when emitting the instructions
1190 // after ISel. An alternative could be to teach
1191 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1192 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1193 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1194 << ValSDNodeOrder << "\n");
1195 SDV = getDbgValue(Val, Variable, Expr, dl,
1196 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1197 DAG.AddDbgValue(SDV, Val.getNode(), false);
1198 } else
1199 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1200 << "in EmitFuncArgumentDbgValue\n");
1201 } else {
1202 LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1203 auto Undef =
1204 UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1205 auto SDV =
1206 DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1207 DAG.AddDbgValue(SDV, nullptr, false);
1210 DDIV.clear();
1213 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1214 Value *V = DDI.getDI()->getValue();
1215 DILocalVariable *Var = DDI.getDI()->getVariable();
1216 DIExpression *Expr = DDI.getDI()->getExpression();
1217 DebugLoc DL = DDI.getdl();
1218 DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1219 unsigned SDOrder = DDI.getSDNodeOrder();
1221 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1222 // that DW_OP_stack_value is desired.
1223 assert(isa<DbgValueInst>(DDI.getDI()));
1224 bool StackValue = true;
1226 // Can this Value can be encoded without any further work?
1227 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1228 return;
1230 // Attempt to salvage back through as many instructions as possible. Bail if
1231 // a non-instruction is seen, such as a constant expression or global
1232 // variable. FIXME: Further work could recover those too.
1233 while (isa<Instruction>(V)) {
1234 Instruction &VAsInst = *cast<Instruction>(V);
1235 DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1237 // If we cannot salvage any further, and haven't yet found a suitable debug
1238 // expression, bail out.
1239 if (!NewExpr)
1240 break;
1242 // New value and expr now represent this debuginfo.
1243 V = VAsInst.getOperand(0);
1244 Expr = NewExpr;
1246 // Some kind of simplification occurred: check whether the operand of the
1247 // salvaged debug expression can be encoded in this DAG.
1248 if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1249 LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
1250 << DDI.getDI() << "\nBy stripping back to:\n " << V);
1251 return;
1255 // This was the final opportunity to salvage this debug information, and it
1256 // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1257 // any earlier variable location.
1258 auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1259 auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1260 DAG.AddDbgValue(SDV, nullptr, false);
1262 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
1263 << "\n");
1264 LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
1265 << "\n");
1268 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1269 DIExpression *Expr, DebugLoc dl,
1270 DebugLoc InstDL, unsigned Order) {
1271 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1272 SDDbgValue *SDV;
1273 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1274 isa<ConstantPointerNull>(V)) {
1275 SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1276 DAG.AddDbgValue(SDV, nullptr, false);
1277 return true;
1280 // If the Value is a frame index, we can create a FrameIndex debug value
1281 // without relying on the DAG at all.
1282 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1283 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1284 if (SI != FuncInfo.StaticAllocaMap.end()) {
1285 auto SDV =
1286 DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1287 /*IsIndirect*/ false, dl, SDNodeOrder);
1288 // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1289 // is still available even if the SDNode gets optimized out.
1290 DAG.AddDbgValue(SDV, nullptr, false);
1291 return true;
1295 // Do not use getValue() in here; we don't want to generate code at
1296 // this point if it hasn't been done yet.
1297 SDValue N = NodeMap[V];
1298 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1299 N = UnusedArgNodeMap[V];
1300 if (N.getNode()) {
1301 if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1302 return true;
1303 SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1304 DAG.AddDbgValue(SDV, N.getNode(), false);
1305 return true;
1308 // Special rules apply for the first dbg.values of parameter variables in a
1309 // function. Identify them by the fact they reference Argument Values, that
1310 // they're parameters, and they are parameters of the current function. We
1311 // need to let them dangle until they get an SDNode.
1312 bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1313 !InstDL.getInlinedAt();
1314 if (!IsParamOfFunc) {
1315 // The value is not used in this block yet (or it would have an SDNode).
1316 // We still want the value to appear for the user if possible -- if it has
1317 // an associated VReg, we can refer to that instead.
1318 auto VMI = FuncInfo.ValueMap.find(V);
1319 if (VMI != FuncInfo.ValueMap.end()) {
1320 unsigned Reg = VMI->second;
1321 // If this is a PHI node, it may be split up into several MI PHI nodes
1322 // (in FunctionLoweringInfo::set).
1323 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1324 V->getType(), None);
1325 if (RFV.occupiesMultipleRegs()) {
1326 unsigned Offset = 0;
1327 unsigned BitsToDescribe = 0;
1328 if (auto VarSize = Var->getSizeInBits())
1329 BitsToDescribe = *VarSize;
1330 if (auto Fragment = Expr->getFragmentInfo())
1331 BitsToDescribe = Fragment->SizeInBits;
1332 for (auto RegAndSize : RFV.getRegsAndSizes()) {
1333 unsigned RegisterSize = RegAndSize.second;
1334 // Bail out if all bits are described already.
1335 if (Offset >= BitsToDescribe)
1336 break;
1337 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1338 ? BitsToDescribe - Offset
1339 : RegisterSize;
1340 auto FragmentExpr = DIExpression::createFragmentExpression(
1341 Expr, Offset, FragmentSize);
1342 if (!FragmentExpr)
1343 continue;
1344 SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1345 false, dl, SDNodeOrder);
1346 DAG.AddDbgValue(SDV, nullptr, false);
1347 Offset += RegisterSize;
1349 } else {
1350 SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1351 DAG.AddDbgValue(SDV, nullptr, false);
1353 return true;
1357 return false;
1360 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1361 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1362 for (auto &Pair : DanglingDebugInfoMap)
1363 for (auto &DDI : Pair.second)
1364 salvageUnresolvedDbgValue(DDI);
1365 clearDanglingDebugInfo();
1368 /// getCopyFromRegs - If there was virtual register allocated for the value V
1369 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1370 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1371 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1372 SDValue Result;
1374 if (It != FuncInfo.ValueMap.end()) {
1375 unsigned InReg = It->second;
1377 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1378 DAG.getDataLayout(), InReg, Ty,
1379 None); // This is not an ABI copy.
1380 SDValue Chain = DAG.getEntryNode();
1381 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1383 resolveDanglingDebugInfo(V, Result);
1386 return Result;
1389 /// getValue - Return an SDValue for the given Value.
1390 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1391 // If we already have an SDValue for this value, use it. It's important
1392 // to do this first, so that we don't create a CopyFromReg if we already
1393 // have a regular SDValue.
1394 SDValue &N = NodeMap[V];
1395 if (N.getNode()) return N;
1397 // If there's a virtual register allocated and initialized for this
1398 // value, use it.
1399 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1400 return copyFromReg;
1402 // Otherwise create a new SDValue and remember it.
1403 SDValue Val = getValueImpl(V);
1404 NodeMap[V] = Val;
1405 resolveDanglingDebugInfo(V, Val);
1406 return Val;
1409 // Return true if SDValue exists for the given Value
1410 bool SelectionDAGBuilder::findValue(const Value *V) const {
1411 return (NodeMap.find(V) != NodeMap.end()) ||
1412 (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1415 /// getNonRegisterValue - Return an SDValue for the given Value, but
1416 /// don't look in FuncInfo.ValueMap for a virtual register.
1417 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1418 // If we already have an SDValue for this value, use it.
1419 SDValue &N = NodeMap[V];
1420 if (N.getNode()) {
1421 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1422 // Remove the debug location from the node as the node is about to be used
1423 // in a location which may differ from the original debug location. This
1424 // is relevant to Constant and ConstantFP nodes because they can appear
1425 // as constant expressions inside PHI nodes.
1426 N->setDebugLoc(DebugLoc());
1428 return N;
1431 // Otherwise create a new SDValue and remember it.
1432 SDValue Val = getValueImpl(V);
1433 NodeMap[V] = Val;
1434 resolveDanglingDebugInfo(V, Val);
1435 return Val;
1438 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1439 /// Create an SDValue for the given value.
1440 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1441 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1443 if (const Constant *C = dyn_cast<Constant>(V)) {
1444 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1446 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1447 return DAG.getConstant(*CI, getCurSDLoc(), VT);
1449 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1450 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1452 if (isa<ConstantPointerNull>(C)) {
1453 unsigned AS = V->getType()->getPointerAddressSpace();
1454 return DAG.getConstant(0, getCurSDLoc(),
1455 TLI.getPointerTy(DAG.getDataLayout(), AS));
1458 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1459 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1461 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1462 return DAG.getUNDEF(VT);
1464 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1465 visit(CE->getOpcode(), *CE);
1466 SDValue N1 = NodeMap[V];
1467 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1468 return N1;
1471 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1472 SmallVector<SDValue, 4> Constants;
1473 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1474 OI != OE; ++OI) {
1475 SDNode *Val = getValue(*OI).getNode();
1476 // If the operand is an empty aggregate, there are no values.
1477 if (!Val) continue;
1478 // Add each leaf value from the operand to the Constants list
1479 // to form a flattened list of all the values.
1480 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1481 Constants.push_back(SDValue(Val, i));
1484 return DAG.getMergeValues(Constants, getCurSDLoc());
1487 if (const ConstantDataSequential *CDS =
1488 dyn_cast<ConstantDataSequential>(C)) {
1489 SmallVector<SDValue, 4> Ops;
1490 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1491 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1492 // Add each leaf value from the operand to the Constants list
1493 // to form a flattened list of all the values.
1494 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1495 Ops.push_back(SDValue(Val, i));
1498 if (isa<ArrayType>(CDS->getType()))
1499 return DAG.getMergeValues(Ops, getCurSDLoc());
1500 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1503 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1504 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1505 "Unknown struct or array constant!");
1507 SmallVector<EVT, 4> ValueVTs;
1508 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1509 unsigned NumElts = ValueVTs.size();
1510 if (NumElts == 0)
1511 return SDValue(); // empty struct
1512 SmallVector<SDValue, 4> Constants(NumElts);
1513 for (unsigned i = 0; i != NumElts; ++i) {
1514 EVT EltVT = ValueVTs[i];
1515 if (isa<UndefValue>(C))
1516 Constants[i] = DAG.getUNDEF(EltVT);
1517 else if (EltVT.isFloatingPoint())
1518 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1519 else
1520 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1523 return DAG.getMergeValues(Constants, getCurSDLoc());
1526 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1527 return DAG.getBlockAddress(BA, VT);
1529 VectorType *VecTy = cast<VectorType>(V->getType());
1530 unsigned NumElements = VecTy->getNumElements();
1532 // Now that we know the number and type of the elements, get that number of
1533 // elements into the Ops array based on what kind of constant it is.
1534 SmallVector<SDValue, 16> Ops;
1535 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1536 for (unsigned i = 0; i != NumElements; ++i)
1537 Ops.push_back(getValue(CV->getOperand(i)));
1538 } else {
1539 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1540 EVT EltVT =
1541 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1543 SDValue Op;
1544 if (EltVT.isFloatingPoint())
1545 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1546 else
1547 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1548 Ops.assign(NumElements, Op);
1551 // Create a BUILD_VECTOR node.
1552 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1555 // If this is a static alloca, generate it as the frameindex instead of
1556 // computation.
1557 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1558 DenseMap<const AllocaInst*, int>::iterator SI =
1559 FuncInfo.StaticAllocaMap.find(AI);
1560 if (SI != FuncInfo.StaticAllocaMap.end())
1561 return DAG.getFrameIndex(SI->second,
1562 TLI.getFrameIndexTy(DAG.getDataLayout()));
1565 // If this is an instruction which fast-isel has deferred, select it now.
1566 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1567 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1569 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1570 Inst->getType(), getABIRegCopyCC(V));
1571 SDValue Chain = DAG.getEntryNode();
1572 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1575 llvm_unreachable("Can't get register for value!");
1578 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1579 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1580 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1581 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1582 bool IsSEH = isAsynchronousEHPersonality(Pers);
1583 bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1584 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1585 if (!IsSEH)
1586 CatchPadMBB->setIsEHScopeEntry();
1587 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1588 if (IsMSVCCXX || IsCoreCLR)
1589 CatchPadMBB->setIsEHFuncletEntry();
1590 // Wasm does not need catchpads anymore
1591 if (!IsWasmCXX)
1592 DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1593 getControlRoot()));
1596 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1597 // Update machine-CFG edge.
1598 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1599 FuncInfo.MBB->addSuccessor(TargetMBB);
1601 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1602 bool IsSEH = isAsynchronousEHPersonality(Pers);
1603 if (IsSEH) {
1604 // If this is not a fall-through branch or optimizations are switched off,
1605 // emit the branch.
1606 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1607 TM.getOptLevel() == CodeGenOpt::None)
1608 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1609 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1610 return;
1613 // Figure out the funclet membership for the catchret's successor.
1614 // This will be used by the FuncletLayout pass to determine how to order the
1615 // BB's.
1616 // A 'catchret' returns to the outer scope's color.
1617 Value *ParentPad = I.getCatchSwitchParentPad();
1618 const BasicBlock *SuccessorColor;
1619 if (isa<ConstantTokenNone>(ParentPad))
1620 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1621 else
1622 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1623 assert(SuccessorColor && "No parent funclet for catchret!");
1624 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1625 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1627 // Create the terminator node.
1628 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1629 getControlRoot(), DAG.getBasicBlock(TargetMBB),
1630 DAG.getBasicBlock(SuccessorColorMBB));
1631 DAG.setRoot(Ret);
1634 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1635 // Don't emit any special code for the cleanuppad instruction. It just marks
1636 // the start of an EH scope/funclet.
1637 FuncInfo.MBB->setIsEHScopeEntry();
1638 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1639 if (Pers != EHPersonality::Wasm_CXX) {
1640 FuncInfo.MBB->setIsEHFuncletEntry();
1641 FuncInfo.MBB->setIsCleanupFuncletEntry();
1645 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1646 // the control flow always stops at the single catch pad, as it does for a
1647 // cleanup pad. In case the exception caught is not of the types the catch pad
1648 // catches, it will be rethrown by a rethrow.
1649 static void findWasmUnwindDestinations(
1650 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1651 BranchProbability Prob,
1652 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1653 &UnwindDests) {
1654 while (EHPadBB) {
1655 const Instruction *Pad = EHPadBB->getFirstNonPHI();
1656 if (isa<CleanupPadInst>(Pad)) {
1657 // Stop on cleanup pads.
1658 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1659 UnwindDests.back().first->setIsEHScopeEntry();
1660 break;
1661 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1662 // Add the catchpad handlers to the possible destinations. We don't
1663 // continue to the unwind destination of the catchswitch for wasm.
1664 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1665 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1666 UnwindDests.back().first->setIsEHScopeEntry();
1668 break;
1669 } else {
1670 continue;
1675 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1676 /// many places it could ultimately go. In the IR, we have a single unwind
1677 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1678 /// This function skips over imaginary basic blocks that hold catchswitch
1679 /// instructions, and finds all the "real" machine
1680 /// basic block destinations. As those destinations may not be successors of
1681 /// EHPadBB, here we also calculate the edge probability to those destinations.
1682 /// The passed-in Prob is the edge probability to EHPadBB.
1683 static void findUnwindDestinations(
1684 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1685 BranchProbability Prob,
1686 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1687 &UnwindDests) {
1688 EHPersonality Personality =
1689 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1690 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1691 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1692 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1693 bool IsSEH = isAsynchronousEHPersonality(Personality);
1695 if (IsWasmCXX) {
1696 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1697 assert(UnwindDests.size() <= 1 &&
1698 "There should be at most one unwind destination for wasm");
1699 return;
1702 while (EHPadBB) {
1703 const Instruction *Pad = EHPadBB->getFirstNonPHI();
1704 BasicBlock *NewEHPadBB = nullptr;
1705 if (isa<LandingPadInst>(Pad)) {
1706 // Stop on landingpads. They are not funclets.
1707 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1708 break;
1709 } else if (isa<CleanupPadInst>(Pad)) {
1710 // Stop on cleanup pads. Cleanups are always funclet entries for all known
1711 // personalities.
1712 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1713 UnwindDests.back().first->setIsEHScopeEntry();
1714 UnwindDests.back().first->setIsEHFuncletEntry();
1715 break;
1716 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1717 // Add the catchpad handlers to the possible destinations.
1718 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1719 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1720 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1721 if (IsMSVCCXX || IsCoreCLR)
1722 UnwindDests.back().first->setIsEHFuncletEntry();
1723 if (!IsSEH)
1724 UnwindDests.back().first->setIsEHScopeEntry();
1726 NewEHPadBB = CatchSwitch->getUnwindDest();
1727 } else {
1728 continue;
1731 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1732 if (BPI && NewEHPadBB)
1733 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1734 EHPadBB = NewEHPadBB;
1738 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1739 // Update successor info.
1740 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1741 auto UnwindDest = I.getUnwindDest();
1742 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1743 BranchProbability UnwindDestProb =
1744 (BPI && UnwindDest)
1745 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1746 : BranchProbability::getZero();
1747 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1748 for (auto &UnwindDest : UnwindDests) {
1749 UnwindDest.first->setIsEHPad();
1750 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1752 FuncInfo.MBB->normalizeSuccProbs();
1754 // Create the terminator node.
1755 SDValue Ret =
1756 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1757 DAG.setRoot(Ret);
1760 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1761 report_fatal_error("visitCatchSwitch not yet implemented!");
1764 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1765 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1766 auto &DL = DAG.getDataLayout();
1767 SDValue Chain = getControlRoot();
1768 SmallVector<ISD::OutputArg, 8> Outs;
1769 SmallVector<SDValue, 8> OutVals;
1771 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1772 // lower
1774 // %val = call <ty> @llvm.experimental.deoptimize()
1775 // ret <ty> %val
1777 // differently.
1778 if (I.getParent()->getTerminatingDeoptimizeCall()) {
1779 LowerDeoptimizingReturn();
1780 return;
1783 if (!FuncInfo.CanLowerReturn) {
1784 unsigned DemoteReg = FuncInfo.DemoteRegister;
1785 const Function *F = I.getParent()->getParent();
1787 // Emit a store of the return value through the virtual register.
1788 // Leave Outs empty so that LowerReturn won't try to load return
1789 // registers the usual way.
1790 SmallVector<EVT, 1> PtrValueVTs;
1791 ComputeValueVTs(TLI, DL,
1792 F->getReturnType()->getPointerTo(
1793 DAG.getDataLayout().getAllocaAddrSpace()),
1794 PtrValueVTs);
1796 SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1797 DemoteReg, PtrValueVTs[0]);
1798 SDValue RetOp = getValue(I.getOperand(0));
1800 SmallVector<EVT, 4> ValueVTs, MemVTs;
1801 SmallVector<uint64_t, 4> Offsets;
1802 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1803 &Offsets);
1804 unsigned NumValues = ValueVTs.size();
1806 SmallVector<SDValue, 4> Chains(NumValues);
1807 for (unsigned i = 0; i != NumValues; ++i) {
1808 // An aggregate return value cannot wrap around the address space, so
1809 // offsets to its parts don't wrap either.
1810 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1812 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1813 if (MemVTs[i] != ValueVTs[i])
1814 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1815 Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1816 // FIXME: better loc info would be nice.
1817 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1820 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1821 MVT::Other, Chains);
1822 } else if (I.getNumOperands() != 0) {
1823 SmallVector<EVT, 4> ValueVTs;
1824 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1825 unsigned NumValues = ValueVTs.size();
1826 if (NumValues) {
1827 SDValue RetOp = getValue(I.getOperand(0));
1829 const Function *F = I.getParent()->getParent();
1831 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1832 I.getOperand(0)->getType(), F->getCallingConv(),
1833 /*IsVarArg*/ false);
1835 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1836 if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1837 Attribute::SExt))
1838 ExtendKind = ISD::SIGN_EXTEND;
1839 else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1840 Attribute::ZExt))
1841 ExtendKind = ISD::ZERO_EXTEND;
1843 LLVMContext &Context = F->getContext();
1844 bool RetInReg = F->getAttributes().hasAttribute(
1845 AttributeList::ReturnIndex, Attribute::InReg);
1847 for (unsigned j = 0; j != NumValues; ++j) {
1848 EVT VT = ValueVTs[j];
1850 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1851 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1853 CallingConv::ID CC = F->getCallingConv();
1855 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1856 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1857 SmallVector<SDValue, 4> Parts(NumParts);
1858 getCopyToParts(DAG, getCurSDLoc(),
1859 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1860 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1862 // 'inreg' on function refers to return value
1863 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1864 if (RetInReg)
1865 Flags.setInReg();
1867 if (I.getOperand(0)->getType()->isPointerTy()) {
1868 Flags.setPointer();
1869 Flags.setPointerAddrSpace(
1870 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1873 if (NeedsRegBlock) {
1874 Flags.setInConsecutiveRegs();
1875 if (j == NumValues - 1)
1876 Flags.setInConsecutiveRegsLast();
1879 // Propagate extension type if any
1880 if (ExtendKind == ISD::SIGN_EXTEND)
1881 Flags.setSExt();
1882 else if (ExtendKind == ISD::ZERO_EXTEND)
1883 Flags.setZExt();
1885 for (unsigned i = 0; i < NumParts; ++i) {
1886 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1887 VT, /*isfixed=*/true, 0, 0));
1888 OutVals.push_back(Parts[i]);
1894 // Push in swifterror virtual register as the last element of Outs. This makes
1895 // sure swifterror virtual register will be returned in the swifterror
1896 // physical register.
1897 const Function *F = I.getParent()->getParent();
1898 if (TLI.supportSwiftError() &&
1899 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1900 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1901 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1902 Flags.setSwiftError();
1903 Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1904 EVT(TLI.getPointerTy(DL)) /*argvt*/,
1905 true /*isfixed*/, 1 /*origidx*/,
1906 0 /*partOffs*/));
1907 // Create SDNode for the swifterror virtual register.
1908 OutVals.push_back(
1909 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1910 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1911 EVT(TLI.getPointerTy(DL))));
1914 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1915 CallingConv::ID CallConv =
1916 DAG.getMachineFunction().getFunction().getCallingConv();
1917 Chain = DAG.getTargetLoweringInfo().LowerReturn(
1918 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1920 // Verify that the target's LowerReturn behaved as expected.
1921 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1922 "LowerReturn didn't return a valid chain!");
1924 // Update the DAG with the new chain value resulting from return lowering.
1925 DAG.setRoot(Chain);
1928 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1929 /// created for it, emit nodes to copy the value into the virtual
1930 /// registers.
1931 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1932 // Skip empty types
1933 if (V->getType()->isEmptyTy())
1934 return;
1936 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1937 if (VMI != FuncInfo.ValueMap.end()) {
1938 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1939 CopyValueToVirtualRegister(V, VMI->second);
1943 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1944 /// the current basic block, add it to ValueMap now so that we'll get a
1945 /// CopyTo/FromReg.
1946 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1947 // No need to export constants.
1948 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1950 // Already exported?
1951 if (FuncInfo.isExportedInst(V)) return;
1953 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1954 CopyValueToVirtualRegister(V, Reg);
1957 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1958 const BasicBlock *FromBB) {
1959 // The operands of the setcc have to be in this block. We don't know
1960 // how to export them from some other block.
1961 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1962 // Can export from current BB.
1963 if (VI->getParent() == FromBB)
1964 return true;
1966 // Is already exported, noop.
1967 return FuncInfo.isExportedInst(V);
1970 // If this is an argument, we can export it if the BB is the entry block or
1971 // if it is already exported.
1972 if (isa<Argument>(V)) {
1973 if (FromBB == &FromBB->getParent()->getEntryBlock())
1974 return true;
1976 // Otherwise, can only export this if it is already exported.
1977 return FuncInfo.isExportedInst(V);
1980 // Otherwise, constants can always be exported.
1981 return true;
1984 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1985 BranchProbability
1986 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1987 const MachineBasicBlock *Dst) const {
1988 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1989 const BasicBlock *SrcBB = Src->getBasicBlock();
1990 const BasicBlock *DstBB = Dst->getBasicBlock();
1991 if (!BPI) {
1992 // If BPI is not available, set the default probability as 1 / N, where N is
1993 // the number of successors.
1994 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1995 return BranchProbability(1, SuccSize);
1997 return BPI->getEdgeProbability(SrcBB, DstBB);
2000 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2001 MachineBasicBlock *Dst,
2002 BranchProbability Prob) {
2003 if (!FuncInfo.BPI)
2004 Src->addSuccessorWithoutProb(Dst);
2005 else {
2006 if (Prob.isUnknown())
2007 Prob = getEdgeProbability(Src, Dst);
2008 Src->addSuccessor(Dst, Prob);
2012 static bool InBlock(const Value *V, const BasicBlock *BB) {
2013 if (const Instruction *I = dyn_cast<Instruction>(V))
2014 return I->getParent() == BB;
2015 return true;
2018 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2019 /// This function emits a branch and is used at the leaves of an OR or an
2020 /// AND operator tree.
2021 void
2022 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2023 MachineBasicBlock *TBB,
2024 MachineBasicBlock *FBB,
2025 MachineBasicBlock *CurBB,
2026 MachineBasicBlock *SwitchBB,
2027 BranchProbability TProb,
2028 BranchProbability FProb,
2029 bool InvertCond) {
2030 const BasicBlock *BB = CurBB->getBasicBlock();
2032 // If the leaf of the tree is a comparison, merge the condition into
2033 // the caseblock.
2034 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2035 // The operands of the cmp have to be in this block. We don't know
2036 // how to export them from some other block. If this is the first block
2037 // of the sequence, no exporting is needed.
2038 if (CurBB == SwitchBB ||
2039 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2040 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2041 ISD::CondCode Condition;
2042 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2043 ICmpInst::Predicate Pred =
2044 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2045 Condition = getICmpCondCode(Pred);
2046 } else {
2047 const FCmpInst *FC = cast<FCmpInst>(Cond);
2048 FCmpInst::Predicate Pred =
2049 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2050 Condition = getFCmpCondCode(Pred);
2051 if (TM.Options.NoNaNsFPMath)
2052 Condition = getFCmpCodeWithoutNaN(Condition);
2055 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2056 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2057 SL->SwitchCases.push_back(CB);
2058 return;
2062 // Create a CaseBlock record representing this branch.
2063 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2064 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2065 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2066 SL->SwitchCases.push_back(CB);
2069 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2070 MachineBasicBlock *TBB,
2071 MachineBasicBlock *FBB,
2072 MachineBasicBlock *CurBB,
2073 MachineBasicBlock *SwitchBB,
2074 Instruction::BinaryOps Opc,
2075 BranchProbability TProb,
2076 BranchProbability FProb,
2077 bool InvertCond) {
2078 // Skip over not part of the tree and remember to invert op and operands at
2079 // next level.
2080 Value *NotCond;
2081 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2082 InBlock(NotCond, CurBB->getBasicBlock())) {
2083 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2084 !InvertCond);
2085 return;
2088 const Instruction *BOp = dyn_cast<Instruction>(Cond);
2089 // Compute the effective opcode for Cond, taking into account whether it needs
2090 // to be inverted, e.g.
2091 // and (not (or A, B)), C
2092 // gets lowered as
2093 // and (and (not A, not B), C)
2094 unsigned BOpc = 0;
2095 if (BOp) {
2096 BOpc = BOp->getOpcode();
2097 if (InvertCond) {
2098 if (BOpc == Instruction::And)
2099 BOpc = Instruction::Or;
2100 else if (BOpc == Instruction::Or)
2101 BOpc = Instruction::And;
2105 // If this node is not part of the or/and tree, emit it as a branch.
2106 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2107 BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2108 BOp->getParent() != CurBB->getBasicBlock() ||
2109 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2110 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2111 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2112 TProb, FProb, InvertCond);
2113 return;
2116 // Create TmpBB after CurBB.
2117 MachineFunction::iterator BBI(CurBB);
2118 MachineFunction &MF = DAG.getMachineFunction();
2119 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2120 CurBB->getParent()->insert(++BBI, TmpBB);
2122 if (Opc == Instruction::Or) {
2123 // Codegen X | Y as:
2124 // BB1:
2125 // jmp_if_X TBB
2126 // jmp TmpBB
2127 // TmpBB:
2128 // jmp_if_Y TBB
2129 // jmp FBB
2132 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2133 // The requirement is that
2134 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2135 // = TrueProb for original BB.
2136 // Assuming the original probabilities are A and B, one choice is to set
2137 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2138 // A/(1+B) and 2B/(1+B). This choice assumes that
2139 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2140 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2141 // TmpBB, but the math is more complicated.
2143 auto NewTrueProb = TProb / 2;
2144 auto NewFalseProb = TProb / 2 + FProb;
2145 // Emit the LHS condition.
2146 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2147 NewTrueProb, NewFalseProb, InvertCond);
2149 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2150 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2151 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2152 // Emit the RHS condition into TmpBB.
2153 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2154 Probs[0], Probs[1], InvertCond);
2155 } else {
2156 assert(Opc == Instruction::And && "Unknown merge op!");
2157 // Codegen X & Y as:
2158 // BB1:
2159 // jmp_if_X TmpBB
2160 // jmp FBB
2161 // TmpBB:
2162 // jmp_if_Y TBB
2163 // jmp FBB
2165 // This requires creation of TmpBB after CurBB.
2167 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2168 // The requirement is that
2169 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2170 // = FalseProb for original BB.
2171 // Assuming the original probabilities are A and B, one choice is to set
2172 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2173 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2174 // TrueProb for BB1 * FalseProb for TmpBB.
2176 auto NewTrueProb = TProb + FProb / 2;
2177 auto NewFalseProb = FProb / 2;
2178 // Emit the LHS condition.
2179 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2180 NewTrueProb, NewFalseProb, InvertCond);
2182 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2183 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2184 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2185 // Emit the RHS condition into TmpBB.
2186 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2187 Probs[0], Probs[1], InvertCond);
2191 /// If the set of cases should be emitted as a series of branches, return true.
2192 /// If we should emit this as a bunch of and/or'd together conditions, return
2193 /// false.
2194 bool
2195 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2196 if (Cases.size() != 2) return true;
2198 // If this is two comparisons of the same values or'd or and'd together, they
2199 // will get folded into a single comparison, so don't emit two blocks.
2200 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2201 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2202 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2203 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2204 return false;
2207 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2208 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2209 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2210 Cases[0].CC == Cases[1].CC &&
2211 isa<Constant>(Cases[0].CmpRHS) &&
2212 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2213 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2214 return false;
2215 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2216 return false;
2219 return true;
2222 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2223 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2225 // Update machine-CFG edges.
2226 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2228 if (I.isUnconditional()) {
2229 // Update machine-CFG edges.
2230 BrMBB->addSuccessor(Succ0MBB);
2232 // If this is not a fall-through branch or optimizations are switched off,
2233 // emit the branch.
2234 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2235 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2236 MVT::Other, getControlRoot(),
2237 DAG.getBasicBlock(Succ0MBB)));
2239 return;
2242 // If this condition is one of the special cases we handle, do special stuff
2243 // now.
2244 const Value *CondVal = I.getCondition();
2245 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2247 // If this is a series of conditions that are or'd or and'd together, emit
2248 // this as a sequence of branches instead of setcc's with and/or operations.
2249 // As long as jumps are not expensive, this should improve performance.
2250 // For example, instead of something like:
2251 // cmp A, B
2252 // C = seteq
2253 // cmp D, E
2254 // F = setle
2255 // or C, F
2256 // jnz foo
2257 // Emit:
2258 // cmp A, B
2259 // je foo
2260 // cmp D, E
2261 // jle foo
2262 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2263 Instruction::BinaryOps Opcode = BOp->getOpcode();
2264 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2265 !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2266 (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2267 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2268 Opcode,
2269 getEdgeProbability(BrMBB, Succ0MBB),
2270 getEdgeProbability(BrMBB, Succ1MBB),
2271 /*InvertCond=*/false);
2272 // If the compares in later blocks need to use values not currently
2273 // exported from this block, export them now. This block should always
2274 // be the first entry.
2275 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2277 // Allow some cases to be rejected.
2278 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2279 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2280 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2281 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2284 // Emit the branch for this block.
2285 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2286 SL->SwitchCases.erase(SL->SwitchCases.begin());
2287 return;
2290 // Okay, we decided not to do this, remove any inserted MBB's and clear
2291 // SwitchCases.
2292 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2293 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2295 SL->SwitchCases.clear();
2299 // Create a CaseBlock record representing this branch.
2300 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2301 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2303 // Use visitSwitchCase to actually insert the fast branch sequence for this
2304 // cond branch.
2305 visitSwitchCase(CB, BrMBB);
2308 /// visitSwitchCase - Emits the necessary code to represent a single node in
2309 /// the binary search tree resulting from lowering a switch instruction.
2310 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2311 MachineBasicBlock *SwitchBB) {
2312 SDValue Cond;
2313 SDValue CondLHS = getValue(CB.CmpLHS);
2314 SDLoc dl = CB.DL;
2316 if (CB.CC == ISD::SETTRUE) {
2317 // Branch or fall through to TrueBB.
2318 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2319 SwitchBB->normalizeSuccProbs();
2320 if (CB.TrueBB != NextBlock(SwitchBB)) {
2321 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2322 DAG.getBasicBlock(CB.TrueBB)));
2324 return;
2327 auto &TLI = DAG.getTargetLoweringInfo();
2328 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2330 // Build the setcc now.
2331 if (!CB.CmpMHS) {
2332 // Fold "(X == true)" to X and "(X == false)" to !X to
2333 // handle common cases produced by branch lowering.
2334 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2335 CB.CC == ISD::SETEQ)
2336 Cond = CondLHS;
2337 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2338 CB.CC == ISD::SETEQ) {
2339 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2340 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2341 } else {
2342 SDValue CondRHS = getValue(CB.CmpRHS);
2344 // If a pointer's DAG type is larger than its memory type then the DAG
2345 // values are zero-extended. This breaks signed comparisons so truncate
2346 // back to the underlying type before doing the compare.
2347 if (CondLHS.getValueType() != MemVT) {
2348 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2349 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2351 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2353 } else {
2354 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2356 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2357 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2359 SDValue CmpOp = getValue(CB.CmpMHS);
2360 EVT VT = CmpOp.getValueType();
2362 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2363 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2364 ISD::SETLE);
2365 } else {
2366 SDValue SUB = DAG.getNode(ISD::SUB, dl,
2367 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2368 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2369 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2373 // Update successor info
2374 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2375 // TrueBB and FalseBB are always different unless the incoming IR is
2376 // degenerate. This only happens when running llc on weird IR.
2377 if (CB.TrueBB != CB.FalseBB)
2378 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2379 SwitchBB->normalizeSuccProbs();
2381 // If the lhs block is the next block, invert the condition so that we can
2382 // fall through to the lhs instead of the rhs block.
2383 if (CB.TrueBB == NextBlock(SwitchBB)) {
2384 std::swap(CB.TrueBB, CB.FalseBB);
2385 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2386 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2389 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2390 MVT::Other, getControlRoot(), Cond,
2391 DAG.getBasicBlock(CB.TrueBB));
2393 // Insert the false branch. Do this even if it's a fall through branch,
2394 // this makes it easier to do DAG optimizations which require inverting
2395 // the branch condition.
2396 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2397 DAG.getBasicBlock(CB.FalseBB));
2399 DAG.setRoot(BrCond);
2402 /// visitJumpTable - Emit JumpTable node in the current MBB
2403 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2404 // Emit the code for the jump table
2405 assert(JT.Reg != -1U && "Should lower JT Header first!");
2406 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2407 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2408 JT.Reg, PTy);
2409 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2410 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2411 MVT::Other, Index.getValue(1),
2412 Table, Index);
2413 DAG.setRoot(BrJumpTable);
2416 /// visitJumpTableHeader - This function emits necessary code to produce index
2417 /// in the JumpTable from switch case.
2418 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2419 JumpTableHeader &JTH,
2420 MachineBasicBlock *SwitchBB) {
2421 SDLoc dl = getCurSDLoc();
2423 // Subtract the lowest switch case value from the value being switched on.
2424 SDValue SwitchOp = getValue(JTH.SValue);
2425 EVT VT = SwitchOp.getValueType();
2426 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2427 DAG.getConstant(JTH.First, dl, VT));
2429 // The SDNode we just created, which holds the value being switched on minus
2430 // the smallest case value, needs to be copied to a virtual register so it
2431 // can be used as an index into the jump table in a subsequent basic block.
2432 // This value may be smaller or larger than the target's pointer type, and
2433 // therefore require extension or truncating.
2434 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2435 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2437 unsigned JumpTableReg =
2438 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2439 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2440 JumpTableReg, SwitchOp);
2441 JT.Reg = JumpTableReg;
2443 if (!JTH.OmitRangeCheck) {
2444 // Emit the range check for the jump table, and branch to the default block
2445 // for the switch statement if the value being switched on exceeds the
2446 // largest case in the switch.
2447 SDValue CMP = DAG.getSetCC(
2448 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2449 Sub.getValueType()),
2450 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2452 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2453 MVT::Other, CopyTo, CMP,
2454 DAG.getBasicBlock(JT.Default));
2456 // Avoid emitting unnecessary branches to the next block.
2457 if (JT.MBB != NextBlock(SwitchBB))
2458 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2459 DAG.getBasicBlock(JT.MBB));
2461 DAG.setRoot(BrCond);
2462 } else {
2463 // Avoid emitting unnecessary branches to the next block.
2464 if (JT.MBB != NextBlock(SwitchBB))
2465 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2466 DAG.getBasicBlock(JT.MBB)));
2467 else
2468 DAG.setRoot(CopyTo);
2472 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2473 /// variable if there exists one.
2474 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2475 SDValue &Chain) {
2476 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2477 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2478 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2479 MachineFunction &MF = DAG.getMachineFunction();
2480 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2481 MachineSDNode *Node =
2482 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2483 if (Global) {
2484 MachinePointerInfo MPInfo(Global);
2485 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2486 MachineMemOperand::MODereferenceable;
2487 MachineMemOperand *MemRef = MF.getMachineMemOperand(
2488 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2489 DAG.setNodeMemRefs(Node, {MemRef});
2491 if (PtrTy != PtrMemTy)
2492 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2493 return SDValue(Node, 0);
2496 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2497 /// tail spliced into a stack protector check success bb.
2499 /// For a high level explanation of how this fits into the stack protector
2500 /// generation see the comment on the declaration of class
2501 /// StackProtectorDescriptor.
2502 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2503 MachineBasicBlock *ParentBB) {
2505 // First create the loads to the guard/stack slot for the comparison.
2506 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2507 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2508 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2510 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2511 int FI = MFI.getStackProtectorIndex();
2513 SDValue Guard;
2514 SDLoc dl = getCurSDLoc();
2515 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2516 const Module &M = *ParentBB->getParent()->getFunction().getParent();
2517 unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2519 // Generate code to load the content of the guard slot.
2520 SDValue GuardVal = DAG.getLoad(
2521 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2522 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2523 MachineMemOperand::MOVolatile);
2525 if (TLI.useStackGuardXorFP())
2526 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2528 // Retrieve guard check function, nullptr if instrumentation is inlined.
2529 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2530 // The target provides a guard check function to validate the guard value.
2531 // Generate a call to that function with the content of the guard slot as
2532 // argument.
2533 FunctionType *FnTy = GuardCheckFn->getFunctionType();
2534 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2536 TargetLowering::ArgListTy Args;
2537 TargetLowering::ArgListEntry Entry;
2538 Entry.Node = GuardVal;
2539 Entry.Ty = FnTy->getParamType(0);
2540 if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2541 Entry.IsInReg = true;
2542 Args.push_back(Entry);
2544 TargetLowering::CallLoweringInfo CLI(DAG);
2545 CLI.setDebugLoc(getCurSDLoc())
2546 .setChain(DAG.getEntryNode())
2547 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2548 getValue(GuardCheckFn), std::move(Args));
2550 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2551 DAG.setRoot(Result.second);
2552 return;
2555 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2556 // Otherwise, emit a volatile load to retrieve the stack guard value.
2557 SDValue Chain = DAG.getEntryNode();
2558 if (TLI.useLoadStackGuardNode()) {
2559 Guard = getLoadStackGuard(DAG, dl, Chain);
2560 } else {
2561 const Value *IRGuard = TLI.getSDagStackGuard(M);
2562 SDValue GuardPtr = getValue(IRGuard);
2564 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2565 MachinePointerInfo(IRGuard, 0), Align,
2566 MachineMemOperand::MOVolatile);
2569 // Perform the comparison via a subtract/getsetcc.
2570 EVT VT = Guard.getValueType();
2571 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2573 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2574 *DAG.getContext(),
2575 Sub.getValueType()),
2576 Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2578 // If the sub is not 0, then we know the guard/stackslot do not equal, so
2579 // branch to failure MBB.
2580 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2581 MVT::Other, GuardVal.getOperand(0),
2582 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2583 // Otherwise branch to success MBB.
2584 SDValue Br = DAG.getNode(ISD::BR, dl,
2585 MVT::Other, BrCond,
2586 DAG.getBasicBlock(SPD.getSuccessMBB()));
2588 DAG.setRoot(Br);
2591 /// Codegen the failure basic block for a stack protector check.
2593 /// A failure stack protector machine basic block consists simply of a call to
2594 /// __stack_chk_fail().
2596 /// For a high level explanation of how this fits into the stack protector
2597 /// generation see the comment on the declaration of class
2598 /// StackProtectorDescriptor.
2599 void
2600 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2601 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2602 TargetLowering::MakeLibCallOptions CallOptions;
2603 CallOptions.setDiscardResult(true);
2604 SDValue Chain =
2605 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2606 None, CallOptions, getCurSDLoc()).second;
2607 // On PS4, the "return address" must still be within the calling function,
2608 // even if it's at the very end, so emit an explicit TRAP here.
2609 // Passing 'true' for doesNotReturn above won't generate the trap for us.
2610 if (TM.getTargetTriple().isPS4CPU())
2611 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2613 DAG.setRoot(Chain);
2616 /// visitBitTestHeader - This function emits necessary code to produce value
2617 /// suitable for "bit tests"
2618 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2619 MachineBasicBlock *SwitchBB) {
2620 SDLoc dl = getCurSDLoc();
2622 // Subtract the minimum value
2623 SDValue SwitchOp = getValue(B.SValue);
2624 EVT VT = SwitchOp.getValueType();
2625 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2626 DAG.getConstant(B.First, dl, VT));
2628 // Check range
2629 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2630 SDValue RangeCmp = DAG.getSetCC(
2631 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2632 Sub.getValueType()),
2633 Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2635 // Determine the type of the test operands.
2636 bool UsePtrType = false;
2637 if (!TLI.isTypeLegal(VT))
2638 UsePtrType = true;
2639 else {
2640 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2641 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2642 // Switch table case range are encoded into series of masks.
2643 // Just use pointer type, it's guaranteed to fit.
2644 UsePtrType = true;
2645 break;
2648 if (UsePtrType) {
2649 VT = TLI.getPointerTy(DAG.getDataLayout());
2650 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2653 B.RegVT = VT.getSimpleVT();
2654 B.Reg = FuncInfo.CreateReg(B.RegVT);
2655 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2657 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2659 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2660 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2661 SwitchBB->normalizeSuccProbs();
2663 SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2664 MVT::Other, CopyTo, RangeCmp,
2665 DAG.getBasicBlock(B.Default));
2667 // Avoid emitting unnecessary branches to the next block.
2668 if (MBB != NextBlock(SwitchBB))
2669 BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2670 DAG.getBasicBlock(MBB));
2672 DAG.setRoot(BrRange);
2675 /// visitBitTestCase - this function produces one "bit test"
2676 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2677 MachineBasicBlock* NextMBB,
2678 BranchProbability BranchProbToNext,
2679 unsigned Reg,
2680 BitTestCase &B,
2681 MachineBasicBlock *SwitchBB) {
2682 SDLoc dl = getCurSDLoc();
2683 MVT VT = BB.RegVT;
2684 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2685 SDValue Cmp;
2686 unsigned PopCount = countPopulation(B.Mask);
2687 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2688 if (PopCount == 1) {
2689 // Testing for a single bit; just compare the shift count with what it
2690 // would need to be to shift a 1 bit in that position.
2691 Cmp = DAG.getSetCC(
2692 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2693 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2694 ISD::SETEQ);
2695 } else if (PopCount == BB.Range) {
2696 // There is only one zero bit in the range, test for it directly.
2697 Cmp = DAG.getSetCC(
2698 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2699 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2700 ISD::SETNE);
2701 } else {
2702 // Make desired shift
2703 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2704 DAG.getConstant(1, dl, VT), ShiftOp);
2706 // Emit bit tests and jumps
2707 SDValue AndOp = DAG.getNode(ISD::AND, dl,
2708 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2709 Cmp = DAG.getSetCC(
2710 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2711 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2714 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2715 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2716 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2717 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2718 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2719 // one as they are relative probabilities (and thus work more like weights),
2720 // and hence we need to normalize them to let the sum of them become one.
2721 SwitchBB->normalizeSuccProbs();
2723 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2724 MVT::Other, getControlRoot(),
2725 Cmp, DAG.getBasicBlock(B.TargetBB));
2727 // Avoid emitting unnecessary branches to the next block.
2728 if (NextMBB != NextBlock(SwitchBB))
2729 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2730 DAG.getBasicBlock(NextMBB));
2732 DAG.setRoot(BrAnd);
2735 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2736 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2738 // Retrieve successors. Look through artificial IR level blocks like
2739 // catchswitch for successors.
2740 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2741 const BasicBlock *EHPadBB = I.getSuccessor(1);
2743 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2744 // have to do anything here to lower funclet bundles.
2745 assert(!I.hasOperandBundlesOtherThan(
2746 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2747 "Cannot lower invokes with arbitrary operand bundles yet!");
2749 const Value *Callee(I.getCalledValue());
2750 const Function *Fn = dyn_cast<Function>(Callee);
2751 if (isa<InlineAsm>(Callee))
2752 visitInlineAsm(&I);
2753 else if (Fn && Fn->isIntrinsic()) {
2754 switch (Fn->getIntrinsicID()) {
2755 default:
2756 llvm_unreachable("Cannot invoke this intrinsic");
2757 case Intrinsic::donothing:
2758 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2759 break;
2760 case Intrinsic::experimental_patchpoint_void:
2761 case Intrinsic::experimental_patchpoint_i64:
2762 visitPatchpoint(&I, EHPadBB);
2763 break;
2764 case Intrinsic::experimental_gc_statepoint:
2765 LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2766 break;
2767 case Intrinsic::wasm_rethrow_in_catch: {
2768 // This is usually done in visitTargetIntrinsic, but this intrinsic is
2769 // special because it can be invoked, so we manually lower it to a DAG
2770 // node here.
2771 SmallVector<SDValue, 8> Ops;
2772 Ops.push_back(getRoot()); // inchain
2773 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2774 Ops.push_back(
2775 DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2776 TLI.getPointerTy(DAG.getDataLayout())));
2777 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2778 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2779 break;
2782 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2783 // Currently we do not lower any intrinsic calls with deopt operand bundles.
2784 // Eventually we will support lowering the @llvm.experimental.deoptimize
2785 // intrinsic, and right now there are no plans to support other intrinsics
2786 // with deopt state.
2787 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2788 } else {
2789 LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2792 // If the value of the invoke is used outside of its defining block, make it
2793 // available as a virtual register.
2794 // We already took care of the exported value for the statepoint instruction
2795 // during call to the LowerStatepoint.
2796 if (!isStatepoint(I)) {
2797 CopyToExportRegsIfNeeded(&I);
2800 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2801 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2802 BranchProbability EHPadBBProb =
2803 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2804 : BranchProbability::getZero();
2805 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2807 // Update successor info.
2808 addSuccessorWithProb(InvokeMBB, Return);
2809 for (auto &UnwindDest : UnwindDests) {
2810 UnwindDest.first->setIsEHPad();
2811 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2813 InvokeMBB->normalizeSuccProbs();
2815 // Drop into normal successor.
2816 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2817 DAG.getBasicBlock(Return)));
2820 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2821 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2823 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2824 // have to do anything here to lower funclet bundles.
2825 assert(!I.hasOperandBundlesOtherThan(
2826 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2827 "Cannot lower callbrs with arbitrary operand bundles yet!");
2829 assert(isa<InlineAsm>(I.getCalledValue()) &&
2830 "Only know how to handle inlineasm callbr");
2831 visitInlineAsm(&I);
2833 // Retrieve successors.
2834 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2836 // Update successor info.
2837 addSuccessorWithProb(CallBrMBB, Return);
2838 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2839 MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2840 addSuccessorWithProb(CallBrMBB, Target);
2842 CallBrMBB->normalizeSuccProbs();
2844 // Drop into default successor.
2845 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2846 MVT::Other, getControlRoot(),
2847 DAG.getBasicBlock(Return)));
2850 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2851 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2854 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2855 assert(FuncInfo.MBB->isEHPad() &&
2856 "Call to landingpad not in landing pad!");
2858 // If there aren't registers to copy the values into (e.g., during SjLj
2859 // exceptions), then don't bother to create these DAG nodes.
2860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2861 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2862 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2863 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2864 return;
2866 // If landingpad's return type is token type, we don't create DAG nodes
2867 // for its exception pointer and selector value. The extraction of exception
2868 // pointer or selector value from token type landingpads is not currently
2869 // supported.
2870 if (LP.getType()->isTokenTy())
2871 return;
2873 SmallVector<EVT, 2> ValueVTs;
2874 SDLoc dl = getCurSDLoc();
2875 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2876 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2878 // Get the two live-in registers as SDValues. The physregs have already been
2879 // copied into virtual registers.
2880 SDValue Ops[2];
2881 if (FuncInfo.ExceptionPointerVirtReg) {
2882 Ops[0] = DAG.getZExtOrTrunc(
2883 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2884 FuncInfo.ExceptionPointerVirtReg,
2885 TLI.getPointerTy(DAG.getDataLayout())),
2886 dl, ValueVTs[0]);
2887 } else {
2888 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2890 Ops[1] = DAG.getZExtOrTrunc(
2891 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2892 FuncInfo.ExceptionSelectorVirtReg,
2893 TLI.getPointerTy(DAG.getDataLayout())),
2894 dl, ValueVTs[1]);
2896 // Merge into one.
2897 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2898 DAG.getVTList(ValueVTs), Ops);
2899 setValue(&LP, Res);
2902 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2903 MachineBasicBlock *Last) {
2904 // Update JTCases.
2905 for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2906 if (SL->JTCases[i].first.HeaderBB == First)
2907 SL->JTCases[i].first.HeaderBB = Last;
2909 // Update BitTestCases.
2910 for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2911 if (SL->BitTestCases[i].Parent == First)
2912 SL->BitTestCases[i].Parent = Last;
2915 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2916 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2918 // Update machine-CFG edges with unique successors.
2919 SmallSet<BasicBlock*, 32> Done;
2920 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2921 BasicBlock *BB = I.getSuccessor(i);
2922 bool Inserted = Done.insert(BB).second;
2923 if (!Inserted)
2924 continue;
2926 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2927 addSuccessorWithProb(IndirectBrMBB, Succ);
2929 IndirectBrMBB->normalizeSuccProbs();
2931 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2932 MVT::Other, getControlRoot(),
2933 getValue(I.getAddress())));
2936 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2937 if (!DAG.getTarget().Options.TrapUnreachable)
2938 return;
2940 // We may be able to ignore unreachable behind a noreturn call.
2941 if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2942 const BasicBlock &BB = *I.getParent();
2943 if (&I != &BB.front()) {
2944 BasicBlock::const_iterator PredI =
2945 std::prev(BasicBlock::const_iterator(&I));
2946 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2947 if (Call->doesNotReturn())
2948 return;
2953 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2956 void SelectionDAGBuilder::visitFSub(const User &I) {
2957 // -0.0 - X --> fneg
2958 Type *Ty = I.getType();
2959 if (isa<Constant>(I.getOperand(0)) &&
2960 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2961 SDValue Op2 = getValue(I.getOperand(1));
2962 setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2963 Op2.getValueType(), Op2));
2964 return;
2967 visitBinary(I, ISD::FSUB);
2970 /// Checks if the given instruction performs a vector reduction, in which case
2971 /// we have the freedom to alter the elements in the result as long as the
2972 /// reduction of them stays unchanged.
2973 static bool isVectorReductionOp(const User *I) {
2974 const Instruction *Inst = dyn_cast<Instruction>(I);
2975 if (!Inst || !Inst->getType()->isVectorTy())
2976 return false;
2978 auto OpCode = Inst->getOpcode();
2979 switch (OpCode) {
2980 case Instruction::Add:
2981 case Instruction::Mul:
2982 case Instruction::And:
2983 case Instruction::Or:
2984 case Instruction::Xor:
2985 break;
2986 case Instruction::FAdd:
2987 case Instruction::FMul:
2988 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2989 if (FPOp->getFastMathFlags().isFast())
2990 break;
2991 LLVM_FALLTHROUGH;
2992 default:
2993 return false;
2996 unsigned ElemNum = Inst->getType()->getVectorNumElements();
2997 // Ensure the reduction size is a power of 2.
2998 if (!isPowerOf2_32(ElemNum))
2999 return false;
3001 unsigned ElemNumToReduce = ElemNum;
3003 // Do DFS search on the def-use chain from the given instruction. We only
3004 // allow four kinds of operations during the search until we reach the
3005 // instruction that extracts the first element from the vector:
3007 // 1. The reduction operation of the same opcode as the given instruction.
3009 // 2. PHI node.
3011 // 3. ShuffleVector instruction together with a reduction operation that
3012 // does a partial reduction.
3014 // 4. ExtractElement that extracts the first element from the vector, and we
3015 // stop searching the def-use chain here.
3017 // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3018 // from 1-3 to the stack to continue the DFS. The given instruction is not
3019 // a reduction operation if we meet any other instructions other than those
3020 // listed above.
3022 SmallVector<const User *, 16> UsersToVisit{Inst};
3023 SmallPtrSet<const User *, 16> Visited;
3024 bool ReduxExtracted = false;
3026 while (!UsersToVisit.empty()) {
3027 auto User = UsersToVisit.back();
3028 UsersToVisit.pop_back();
3029 if (!Visited.insert(User).second)
3030 continue;
3032 for (const auto &U : User->users()) {
3033 auto Inst = dyn_cast<Instruction>(U);
3034 if (!Inst)
3035 return false;
3037 if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3038 if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3039 if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3040 return false;
3041 UsersToVisit.push_back(U);
3042 } else if (const ShuffleVectorInst *ShufInst =
3043 dyn_cast<ShuffleVectorInst>(U)) {
3044 // Detect the following pattern: A ShuffleVector instruction together
3045 // with a reduction that do partial reduction on the first and second
3046 // ElemNumToReduce / 2 elements, and store the result in
3047 // ElemNumToReduce / 2 elements in another vector.
3049 unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3050 if (ResultElements < ElemNum)
3051 return false;
3053 if (ElemNumToReduce == 1)
3054 return false;
3055 if (!isa<UndefValue>(U->getOperand(1)))
3056 return false;
3057 for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3058 if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3059 return false;
3060 for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3061 if (ShufInst->getMaskValue(i) != -1)
3062 return false;
3064 // There is only one user of this ShuffleVector instruction, which
3065 // must be a reduction operation.
3066 if (!U->hasOneUse())
3067 return false;
3069 auto U2 = dyn_cast<Instruction>(*U->user_begin());
3070 if (!U2 || U2->getOpcode() != OpCode)
3071 return false;
3073 // Check operands of the reduction operation.
3074 if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3075 (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3076 UsersToVisit.push_back(U2);
3077 ElemNumToReduce /= 2;
3078 } else
3079 return false;
3080 } else if (isa<ExtractElementInst>(U)) {
3081 // At this moment we should have reduced all elements in the vector.
3082 if (ElemNumToReduce != 1)
3083 return false;
3085 const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3086 if (!Val || !Val->isZero())
3087 return false;
3089 ReduxExtracted = true;
3090 } else
3091 return false;
3094 return ReduxExtracted;
3097 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3098 SDNodeFlags Flags;
3100 SDValue Op = getValue(I.getOperand(0));
3101 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3102 Op, Flags);
3103 setValue(&I, UnNodeValue);
3106 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3107 SDNodeFlags Flags;
3108 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3109 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3110 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3112 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3113 Flags.setExact(ExactOp->isExact());
3115 if (isVectorReductionOp(&I)) {
3116 Flags.setVectorReduction(true);
3117 LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3120 SDValue Op1 = getValue(I.getOperand(0));
3121 SDValue Op2 = getValue(I.getOperand(1));
3122 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3123 Op1, Op2, Flags);
3124 setValue(&I, BinNodeValue);
3127 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3128 SDValue Op1 = getValue(I.getOperand(0));
3129 SDValue Op2 = getValue(I.getOperand(1));
3131 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3132 Op1.getValueType(), DAG.getDataLayout());
3134 // Coerce the shift amount to the right type if we can.
3135 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3136 unsigned ShiftSize = ShiftTy.getSizeInBits();
3137 unsigned Op2Size = Op2.getValueSizeInBits();
3138 SDLoc DL = getCurSDLoc();
3140 // If the operand is smaller than the shift count type, promote it.
3141 if (ShiftSize > Op2Size)
3142 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3144 // If the operand is larger than the shift count type but the shift
3145 // count type has enough bits to represent any shift value, truncate
3146 // it now. This is a common case and it exposes the truncate to
3147 // optimization early.
3148 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3149 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3150 // Otherwise we'll need to temporarily settle for some other convenient
3151 // type. Type legalization will make adjustments once the shiftee is split.
3152 else
3153 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3156 bool nuw = false;
3157 bool nsw = false;
3158 bool exact = false;
3160 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3162 if (const OverflowingBinaryOperator *OFBinOp =
3163 dyn_cast<const OverflowingBinaryOperator>(&I)) {
3164 nuw = OFBinOp->hasNoUnsignedWrap();
3165 nsw = OFBinOp->hasNoSignedWrap();
3167 if (const PossiblyExactOperator *ExactOp =
3168 dyn_cast<const PossiblyExactOperator>(&I))
3169 exact = ExactOp->isExact();
3171 SDNodeFlags Flags;
3172 Flags.setExact(exact);
3173 Flags.setNoSignedWrap(nsw);
3174 Flags.setNoUnsignedWrap(nuw);
3175 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3176 Flags);
3177 setValue(&I, Res);
3180 void SelectionDAGBuilder::visitSDiv(const User &I) {
3181 SDValue Op1 = getValue(I.getOperand(0));
3182 SDValue Op2 = getValue(I.getOperand(1));
3184 SDNodeFlags Flags;
3185 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3186 cast<PossiblyExactOperator>(&I)->isExact());
3187 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3188 Op2, Flags));
3191 void SelectionDAGBuilder::visitICmp(const User &I) {
3192 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3193 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3194 predicate = IC->getPredicate();
3195 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3196 predicate = ICmpInst::Predicate(IC->getPredicate());
3197 SDValue Op1 = getValue(I.getOperand(0));
3198 SDValue Op2 = getValue(I.getOperand(1));
3199 ISD::CondCode Opcode = getICmpCondCode(predicate);
3201 auto &TLI = DAG.getTargetLoweringInfo();
3202 EVT MemVT =
3203 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3205 // If a pointer's DAG type is larger than its memory type then the DAG values
3206 // are zero-extended. This breaks signed comparisons so truncate back to the
3207 // underlying type before doing the compare.
3208 if (Op1.getValueType() != MemVT) {
3209 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3210 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3213 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3214 I.getType());
3215 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3218 void SelectionDAGBuilder::visitFCmp(const User &I) {
3219 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3220 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3221 predicate = FC->getPredicate();
3222 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3223 predicate = FCmpInst::Predicate(FC->getPredicate());
3224 SDValue Op1 = getValue(I.getOperand(0));
3225 SDValue Op2 = getValue(I.getOperand(1));
3227 ISD::CondCode Condition = getFCmpCondCode(predicate);
3228 auto *FPMO = dyn_cast<FPMathOperator>(&I);
3229 if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3230 Condition = getFCmpCodeWithoutNaN(Condition);
3232 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3233 I.getType());
3234 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3237 // Check if the condition of the select has one use or two users that are both
3238 // selects with the same condition.
3239 static bool hasOnlySelectUsers(const Value *Cond) {
3240 return llvm::all_of(Cond->users(), [](const Value *V) {
3241 return isa<SelectInst>(V);
3245 void SelectionDAGBuilder::visitSelect(const User &I) {
3246 SmallVector<EVT, 4> ValueVTs;
3247 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3248 ValueVTs);
3249 unsigned NumValues = ValueVTs.size();
3250 if (NumValues == 0) return;
3252 SmallVector<SDValue, 4> Values(NumValues);
3253 SDValue Cond = getValue(I.getOperand(0));
3254 SDValue LHSVal = getValue(I.getOperand(1));
3255 SDValue RHSVal = getValue(I.getOperand(2));
3256 auto BaseOps = {Cond};
3257 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3258 ISD::VSELECT : ISD::SELECT;
3260 bool IsUnaryAbs = false;
3262 // Min/max matching is only viable if all output VTs are the same.
3263 if (is_splat(ValueVTs)) {
3264 EVT VT = ValueVTs[0];
3265 LLVMContext &Ctx = *DAG.getContext();
3266 auto &TLI = DAG.getTargetLoweringInfo();
3268 // We care about the legality of the operation after it has been type
3269 // legalized.
3270 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3271 VT = TLI.getTypeToTransformTo(Ctx, VT);
3273 // If the vselect is legal, assume we want to leave this as a vector setcc +
3274 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3275 // min/max is legal on the scalar type.
3276 bool UseScalarMinMax = VT.isVector() &&
3277 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3279 Value *LHS, *RHS;
3280 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3281 ISD::NodeType Opc = ISD::DELETED_NODE;
3282 switch (SPR.Flavor) {
3283 case SPF_UMAX: Opc = ISD::UMAX; break;
3284 case SPF_UMIN: Opc = ISD::UMIN; break;
3285 case SPF_SMAX: Opc = ISD::SMAX; break;
3286 case SPF_SMIN: Opc = ISD::SMIN; break;
3287 case SPF_FMINNUM:
3288 switch (SPR.NaNBehavior) {
3289 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3290 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
3291 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3292 case SPNB_RETURNS_ANY: {
3293 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3294 Opc = ISD::FMINNUM;
3295 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3296 Opc = ISD::FMINIMUM;
3297 else if (UseScalarMinMax)
3298 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3299 ISD::FMINNUM : ISD::FMINIMUM;
3300 break;
3303 break;
3304 case SPF_FMAXNUM:
3305 switch (SPR.NaNBehavior) {
3306 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3307 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
3308 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3309 case SPNB_RETURNS_ANY:
3311 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3312 Opc = ISD::FMAXNUM;
3313 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3314 Opc = ISD::FMAXIMUM;
3315 else if (UseScalarMinMax)
3316 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3317 ISD::FMAXNUM : ISD::FMAXIMUM;
3318 break;
3320 break;
3321 case SPF_ABS:
3322 IsUnaryAbs = true;
3323 Opc = ISD::ABS;
3324 break;
3325 case SPF_NABS:
3326 // TODO: we need to produce sub(0, abs(X)).
3327 default: break;
3330 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3331 (TLI.isOperationLegalOrCustom(Opc, VT) ||
3332 (UseScalarMinMax &&
3333 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3334 // If the underlying comparison instruction is used by any other
3335 // instruction, the consumed instructions won't be destroyed, so it is
3336 // not profitable to convert to a min/max.
3337 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3338 OpCode = Opc;
3339 LHSVal = getValue(LHS);
3340 RHSVal = getValue(RHS);
3341 BaseOps = {};
3344 if (IsUnaryAbs) {
3345 OpCode = Opc;
3346 LHSVal = getValue(LHS);
3347 BaseOps = {};
3351 if (IsUnaryAbs) {
3352 for (unsigned i = 0; i != NumValues; ++i) {
3353 Values[i] =
3354 DAG.getNode(OpCode, getCurSDLoc(),
3355 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3356 SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3358 } else {
3359 for (unsigned i = 0; i != NumValues; ++i) {
3360 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3361 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3362 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3363 Values[i] = DAG.getNode(
3364 OpCode, getCurSDLoc(),
3365 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3369 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3370 DAG.getVTList(ValueVTs), Values));
3373 void SelectionDAGBuilder::visitTrunc(const User &I) {
3374 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3375 SDValue N = getValue(I.getOperand(0));
3376 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3377 I.getType());
3378 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3381 void SelectionDAGBuilder::visitZExt(const User &I) {
3382 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3383 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3384 SDValue N = getValue(I.getOperand(0));
3385 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3386 I.getType());
3387 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3390 void SelectionDAGBuilder::visitSExt(const User &I) {
3391 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3392 // SExt also can't be a cast to bool for same reason. So, nothing much to do
3393 SDValue N = getValue(I.getOperand(0));
3394 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3395 I.getType());
3396 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3399 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3400 // FPTrunc is never a no-op cast, no need to check
3401 SDValue N = getValue(I.getOperand(0));
3402 SDLoc dl = getCurSDLoc();
3403 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3404 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3405 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3406 DAG.getTargetConstant(
3407 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3410 void SelectionDAGBuilder::visitFPExt(const User &I) {
3411 // FPExt is never a no-op cast, no need to check
3412 SDValue N = getValue(I.getOperand(0));
3413 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3414 I.getType());
3415 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3418 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3419 // FPToUI is never a no-op cast, no need to check
3420 SDValue N = getValue(I.getOperand(0));
3421 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3422 I.getType());
3423 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3426 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3427 // FPToSI is never a no-op cast, no need to check
3428 SDValue N = getValue(I.getOperand(0));
3429 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3430 I.getType());
3431 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3434 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3435 // UIToFP is never a no-op cast, no need to check
3436 SDValue N = getValue(I.getOperand(0));
3437 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3438 I.getType());
3439 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3442 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3443 // SIToFP is never a no-op cast, no need to check
3444 SDValue N = getValue(I.getOperand(0));
3445 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3446 I.getType());
3447 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3450 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3451 // What to do depends on the size of the integer and the size of the pointer.
3452 // We can either truncate, zero extend, or no-op, accordingly.
3453 SDValue N = getValue(I.getOperand(0));
3454 auto &TLI = DAG.getTargetLoweringInfo();
3455 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3456 I.getType());
3457 EVT PtrMemVT =
3458 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3459 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3460 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3461 setValue(&I, N);
3464 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3465 // What to do depends on the size of the integer and the size of the pointer.
3466 // We can either truncate, zero extend, or no-op, accordingly.
3467 SDValue N = getValue(I.getOperand(0));
3468 auto &TLI = DAG.getTargetLoweringInfo();
3469 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3470 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3471 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3472 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3473 setValue(&I, N);
3476 void SelectionDAGBuilder::visitBitCast(const User &I) {
3477 SDValue N = getValue(I.getOperand(0));
3478 SDLoc dl = getCurSDLoc();
3479 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3480 I.getType());
3482 // BitCast assures us that source and destination are the same size so this is
3483 // either a BITCAST or a no-op.
3484 if (DestVT != N.getValueType())
3485 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3486 DestVT, N)); // convert types.
3487 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3488 // might fold any kind of constant expression to an integer constant and that
3489 // is not what we are looking for. Only recognize a bitcast of a genuine
3490 // constant integer as an opaque constant.
3491 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3492 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3493 /*isOpaque*/true));
3494 else
3495 setValue(&I, N); // noop cast.
3498 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3499 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3500 const Value *SV = I.getOperand(0);
3501 SDValue N = getValue(SV);
3502 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3504 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3505 unsigned DestAS = I.getType()->getPointerAddressSpace();
3507 if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3508 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3510 setValue(&I, N);
3513 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3514 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3515 SDValue InVec = getValue(I.getOperand(0));
3516 SDValue InVal = getValue(I.getOperand(1));
3517 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3518 TLI.getVectorIdxTy(DAG.getDataLayout()));
3519 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3520 TLI.getValueType(DAG.getDataLayout(), I.getType()),
3521 InVec, InVal, InIdx));
3524 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3525 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3526 SDValue InVec = getValue(I.getOperand(0));
3527 SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3528 TLI.getVectorIdxTy(DAG.getDataLayout()));
3529 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3530 TLI.getValueType(DAG.getDataLayout(), I.getType()),
3531 InVec, InIdx));
3534 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3535 SDValue Src1 = getValue(I.getOperand(0));
3536 SDValue Src2 = getValue(I.getOperand(1));
3537 SDLoc DL = getCurSDLoc();
3539 SmallVector<int, 8> Mask;
3540 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3541 unsigned MaskNumElts = Mask.size();
3543 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3544 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3545 EVT SrcVT = Src1.getValueType();
3546 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3548 if (SrcNumElts == MaskNumElts) {
3549 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3550 return;
3553 // Normalize the shuffle vector since mask and vector length don't match.
3554 if (SrcNumElts < MaskNumElts) {
3555 // Mask is longer than the source vectors. We can use concatenate vector to
3556 // make the mask and vectors lengths match.
3558 if (MaskNumElts % SrcNumElts == 0) {
3559 // Mask length is a multiple of the source vector length.
3560 // Check if the shuffle is some kind of concatenation of the input
3561 // vectors.
3562 unsigned NumConcat = MaskNumElts / SrcNumElts;
3563 bool IsConcat = true;
3564 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3565 for (unsigned i = 0; i != MaskNumElts; ++i) {
3566 int Idx = Mask[i];
3567 if (Idx < 0)
3568 continue;
3569 // Ensure the indices in each SrcVT sized piece are sequential and that
3570 // the same source is used for the whole piece.
3571 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3572 (ConcatSrcs[i / SrcNumElts] >= 0 &&
3573 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3574 IsConcat = false;
3575 break;
3577 // Remember which source this index came from.
3578 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3581 // The shuffle is concatenating multiple vectors together. Just emit
3582 // a CONCAT_VECTORS operation.
3583 if (IsConcat) {
3584 SmallVector<SDValue, 8> ConcatOps;
3585 for (auto Src : ConcatSrcs) {
3586 if (Src < 0)
3587 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3588 else if (Src == 0)
3589 ConcatOps.push_back(Src1);
3590 else
3591 ConcatOps.push_back(Src2);
3593 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3594 return;
3598 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3599 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3600 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3601 PaddedMaskNumElts);
3603 // Pad both vectors with undefs to make them the same length as the mask.
3604 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3606 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3607 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3608 MOps1[0] = Src1;
3609 MOps2[0] = Src2;
3611 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3612 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3614 // Readjust mask for new input vector length.
3615 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3616 for (unsigned i = 0; i != MaskNumElts; ++i) {
3617 int Idx = Mask[i];
3618 if (Idx >= (int)SrcNumElts)
3619 Idx -= SrcNumElts - PaddedMaskNumElts;
3620 MappedOps[i] = Idx;
3623 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3625 // If the concatenated vector was padded, extract a subvector with the
3626 // correct number of elements.
3627 if (MaskNumElts != PaddedMaskNumElts)
3628 Result = DAG.getNode(
3629 ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3630 DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3632 setValue(&I, Result);
3633 return;
3636 if (SrcNumElts > MaskNumElts) {
3637 // Analyze the access pattern of the vector to see if we can extract
3638 // two subvectors and do the shuffle.
3639 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
3640 bool CanExtract = true;
3641 for (int Idx : Mask) {
3642 unsigned Input = 0;
3643 if (Idx < 0)
3644 continue;
3646 if (Idx >= (int)SrcNumElts) {
3647 Input = 1;
3648 Idx -= SrcNumElts;
3651 // If all the indices come from the same MaskNumElts sized portion of
3652 // the sources we can use extract. Also make sure the extract wouldn't
3653 // extract past the end of the source.
3654 int NewStartIdx = alignDown(Idx, MaskNumElts);
3655 if (NewStartIdx + MaskNumElts > SrcNumElts ||
3656 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3657 CanExtract = false;
3658 // Make sure we always update StartIdx as we use it to track if all
3659 // elements are undef.
3660 StartIdx[Input] = NewStartIdx;
3663 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3664 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3665 return;
3667 if (CanExtract) {
3668 // Extract appropriate subvector and generate a vector shuffle
3669 for (unsigned Input = 0; Input < 2; ++Input) {
3670 SDValue &Src = Input == 0 ? Src1 : Src2;
3671 if (StartIdx[Input] < 0)
3672 Src = DAG.getUNDEF(VT);
3673 else {
3674 Src = DAG.getNode(
3675 ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3676 DAG.getConstant(StartIdx[Input], DL,
3677 TLI.getVectorIdxTy(DAG.getDataLayout())));
3681 // Calculate new mask.
3682 SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3683 for (int &Idx : MappedOps) {
3684 if (Idx >= (int)SrcNumElts)
3685 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3686 else if (Idx >= 0)
3687 Idx -= StartIdx[0];
3690 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3691 return;
3695 // We can't use either concat vectors or extract subvectors so fall back to
3696 // replacing the shuffle with extract and build vector.
3697 // to insert and build vector.
3698 EVT EltVT = VT.getVectorElementType();
3699 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3700 SmallVector<SDValue,8> Ops;
3701 for (int Idx : Mask) {
3702 SDValue Res;
3704 if (Idx < 0) {
3705 Res = DAG.getUNDEF(EltVT);
3706 } else {
3707 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3708 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3710 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3711 EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3714 Ops.push_back(Res);
3717 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3720 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3721 ArrayRef<unsigned> Indices;
3722 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3723 Indices = IV->getIndices();
3724 else
3725 Indices = cast<ConstantExpr>(&I)->getIndices();
3727 const Value *Op0 = I.getOperand(0);
3728 const Value *Op1 = I.getOperand(1);
3729 Type *AggTy = I.getType();
3730 Type *ValTy = Op1->getType();
3731 bool IntoUndef = isa<UndefValue>(Op0);
3732 bool FromUndef = isa<UndefValue>(Op1);
3734 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3736 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3737 SmallVector<EVT, 4> AggValueVTs;
3738 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3739 SmallVector<EVT, 4> ValValueVTs;
3740 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3742 unsigned NumAggValues = AggValueVTs.size();
3743 unsigned NumValValues = ValValueVTs.size();
3744 SmallVector<SDValue, 4> Values(NumAggValues);
3746 // Ignore an insertvalue that produces an empty object
3747 if (!NumAggValues) {
3748 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3749 return;
3752 SDValue Agg = getValue(Op0);
3753 unsigned i = 0;
3754 // Copy the beginning value(s) from the original aggregate.
3755 for (; i != LinearIndex; ++i)
3756 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3757 SDValue(Agg.getNode(), Agg.getResNo() + i);
3758 // Copy values from the inserted value(s).
3759 if (NumValValues) {
3760 SDValue Val = getValue(Op1);
3761 for (; i != LinearIndex + NumValValues; ++i)
3762 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3763 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3765 // Copy remaining value(s) from the original aggregate.
3766 for (; i != NumAggValues; ++i)
3767 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3768 SDValue(Agg.getNode(), Agg.getResNo() + i);
3770 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3771 DAG.getVTList(AggValueVTs), Values));
3774 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3775 ArrayRef<unsigned> Indices;
3776 if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3777 Indices = EV->getIndices();
3778 else
3779 Indices = cast<ConstantExpr>(&I)->getIndices();
3781 const Value *Op0 = I.getOperand(0);
3782 Type *AggTy = Op0->getType();
3783 Type *ValTy = I.getType();
3784 bool OutOfUndef = isa<UndefValue>(Op0);
3786 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3788 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3789 SmallVector<EVT, 4> ValValueVTs;
3790 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3792 unsigned NumValValues = ValValueVTs.size();
3794 // Ignore a extractvalue that produces an empty object
3795 if (!NumValValues) {
3796 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3797 return;
3800 SmallVector<SDValue, 4> Values(NumValValues);
3802 SDValue Agg = getValue(Op0);
3803 // Copy out the selected value(s).
3804 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3805 Values[i - LinearIndex] =
3806 OutOfUndef ?
3807 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3808 SDValue(Agg.getNode(), Agg.getResNo() + i);
3810 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3811 DAG.getVTList(ValValueVTs), Values));
3814 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3815 Value *Op0 = I.getOperand(0);
3816 // Note that the pointer operand may be a vector of pointers. Take the scalar
3817 // element which holds a pointer.
3818 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3819 SDValue N = getValue(Op0);
3820 SDLoc dl = getCurSDLoc();
3821 auto &TLI = DAG.getTargetLoweringInfo();
3822 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3823 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3825 // Normalize Vector GEP - all scalar operands should be converted to the
3826 // splat vector.
3827 unsigned VectorWidth = I.getType()->isVectorTy() ?
3828 I.getType()->getVectorNumElements() : 0;
3830 if (VectorWidth && !N.getValueType().isVector()) {
3831 LLVMContext &Context = *DAG.getContext();
3832 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3833 N = DAG.getSplatBuildVector(VT, dl, N);
3836 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3837 GTI != E; ++GTI) {
3838 const Value *Idx = GTI.getOperand();
3839 if (StructType *StTy = GTI.getStructTypeOrNull()) {
3840 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3841 if (Field) {
3842 // N = N + Offset
3843 uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3845 // In an inbounds GEP with an offset that is nonnegative even when
3846 // interpreted as signed, assume there is no unsigned overflow.
3847 SDNodeFlags Flags;
3848 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3849 Flags.setNoUnsignedWrap(true);
3851 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3852 DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3854 } else {
3855 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3856 MVT IdxTy = MVT::getIntegerVT(IdxSize);
3857 APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3859 // If this is a scalar constant or a splat vector of constants,
3860 // handle it quickly.
3861 const auto *C = dyn_cast<Constant>(Idx);
3862 if (C && isa<VectorType>(C->getType()))
3863 C = C->getSplatValue();
3865 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
3866 if (CI->isZero())
3867 continue;
3868 APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3869 LLVMContext &Context = *DAG.getContext();
3870 SDValue OffsVal = VectorWidth ?
3871 DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3872 DAG.getConstant(Offs, dl, IdxTy);
3874 // In an inbounds GEP with an offset that is nonnegative even when
3875 // interpreted as signed, assume there is no unsigned overflow.
3876 SDNodeFlags Flags;
3877 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3878 Flags.setNoUnsignedWrap(true);
3880 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3882 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3883 continue;
3886 // N = N + Idx * ElementSize;
3887 SDValue IdxN = getValue(Idx);
3889 if (!IdxN.getValueType().isVector() && VectorWidth) {
3890 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3891 IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3894 // If the index is smaller or larger than intptr_t, truncate or extend
3895 // it.
3896 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3898 // If this is a multiply by a power of two, turn it into a shl
3899 // immediately. This is a very common case.
3900 if (ElementSize != 1) {
3901 if (ElementSize.isPowerOf2()) {
3902 unsigned Amt = ElementSize.logBase2();
3903 IdxN = DAG.getNode(ISD::SHL, dl,
3904 N.getValueType(), IdxN,
3905 DAG.getConstant(Amt, dl, IdxN.getValueType()));
3906 } else {
3907 SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3908 IdxN.getValueType());
3909 IdxN = DAG.getNode(ISD::MUL, dl,
3910 N.getValueType(), IdxN, Scale);
3914 N = DAG.getNode(ISD::ADD, dl,
3915 N.getValueType(), N, IdxN);
3919 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3920 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3922 setValue(&I, N);
3925 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3926 // If this is a fixed sized alloca in the entry block of the function,
3927 // allocate it statically on the stack.
3928 if (FuncInfo.StaticAllocaMap.count(&I))
3929 return; // getValue will auto-populate this.
3931 SDLoc dl = getCurSDLoc();
3932 Type *Ty = I.getAllocatedType();
3933 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3934 auto &DL = DAG.getDataLayout();
3935 uint64_t TySize = DL.getTypeAllocSize(Ty);
3936 unsigned Align =
3937 std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3939 SDValue AllocSize = getValue(I.getArraySize());
3941 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3942 if (AllocSize.getValueType() != IntPtr)
3943 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3945 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3946 AllocSize,
3947 DAG.getConstant(TySize, dl, IntPtr));
3949 // Handle alignment. If the requested alignment is less than or equal to
3950 // the stack alignment, ignore it. If the size is greater than or equal to
3951 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3952 unsigned StackAlign =
3953 DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3954 if (Align <= StackAlign)
3955 Align = 0;
3957 // Round the size of the allocation up to the stack alignment size
3958 // by add SA-1 to the size. This doesn't overflow because we're computing
3959 // an address inside an alloca.
3960 SDNodeFlags Flags;
3961 Flags.setNoUnsignedWrap(true);
3962 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3963 DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3965 // Mask out the low bits for alignment purposes.
3966 AllocSize =
3967 DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3968 DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3970 SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3971 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3972 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3973 setValue(&I, DSA);
3974 DAG.setRoot(DSA.getValue(1));
3976 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3979 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3980 if (I.isAtomic())
3981 return visitAtomicLoad(I);
3983 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3984 const Value *SV = I.getOperand(0);
3985 if (TLI.supportSwiftError()) {
3986 // Swifterror values can come from either a function parameter with
3987 // swifterror attribute or an alloca with swifterror attribute.
3988 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3989 if (Arg->hasSwiftErrorAttr())
3990 return visitLoadFromSwiftError(I);
3993 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3994 if (Alloca->isSwiftError())
3995 return visitLoadFromSwiftError(I);
3999 SDValue Ptr = getValue(SV);
4001 Type *Ty = I.getType();
4003 bool isVolatile = I.isVolatile();
4004 bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal);
4005 bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load);
4006 bool isDereferenceable =
4007 isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
4008 unsigned Alignment = I.getAlignment();
4010 AAMDNodes AAInfo;
4011 I.getAAMetadata(AAInfo);
4012 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4014 SmallVector<EVT, 4> ValueVTs, MemVTs;
4015 SmallVector<uint64_t, 4> Offsets;
4016 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4017 unsigned NumValues = ValueVTs.size();
4018 if (NumValues == 0)
4019 return;
4021 SDValue Root;
4022 bool ConstantMemory = false;
4023 if (isVolatile || NumValues > MaxParallelChains)
4024 // Serialize volatile loads with other side effects.
4025 Root = getRoot();
4026 else if (AA &&
4027 AA->pointsToConstantMemory(MemoryLocation(
4029 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4030 AAInfo))) {
4031 // Do not serialize (non-volatile) loads of constant memory with anything.
4032 Root = DAG.getEntryNode();
4033 ConstantMemory = true;
4034 } else {
4035 // Do not serialize non-volatile loads against each other.
4036 Root = DAG.getRoot();
4039 SDLoc dl = getCurSDLoc();
4041 if (isVolatile)
4042 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4044 // An aggregate load cannot wrap around the address space, so offsets to its
4045 // parts don't wrap either.
4046 SDNodeFlags Flags;
4047 Flags.setNoUnsignedWrap(true);
4049 SmallVector<SDValue, 4> Values(NumValues);
4050 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4051 EVT PtrVT = Ptr.getValueType();
4052 unsigned ChainI = 0;
4053 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4054 // Serializing loads here may result in excessive register pressure, and
4055 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4056 // could recover a bit by hoisting nodes upward in the chain by recognizing
4057 // they are side-effect free or do not alias. The optimizer should really
4058 // avoid this case by converting large object/array copies to llvm.memcpy
4059 // (MaxParallelChains should always remain as failsafe).
4060 if (ChainI == MaxParallelChains) {
4061 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4062 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4063 makeArrayRef(Chains.data(), ChainI));
4064 Root = Chain;
4065 ChainI = 0;
4067 SDValue A = DAG.getNode(ISD::ADD, dl,
4068 PtrVT, Ptr,
4069 DAG.getConstant(Offsets[i], dl, PtrVT),
4070 Flags);
4071 auto MMOFlags = MachineMemOperand::MONone;
4072 if (isVolatile)
4073 MMOFlags |= MachineMemOperand::MOVolatile;
4074 if (isNonTemporal)
4075 MMOFlags |= MachineMemOperand::MONonTemporal;
4076 if (isInvariant)
4077 MMOFlags |= MachineMemOperand::MOInvariant;
4078 if (isDereferenceable)
4079 MMOFlags |= MachineMemOperand::MODereferenceable;
4080 MMOFlags |= TLI.getMMOFlags(I);
4082 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4083 MachinePointerInfo(SV, Offsets[i]), Alignment,
4084 MMOFlags, AAInfo, Ranges);
4085 Chains[ChainI] = L.getValue(1);
4087 if (MemVTs[i] != ValueVTs[i])
4088 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4090 Values[i] = L;
4093 if (!ConstantMemory) {
4094 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4095 makeArrayRef(Chains.data(), ChainI));
4096 if (isVolatile)
4097 DAG.setRoot(Chain);
4098 else
4099 PendingLoads.push_back(Chain);
4102 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4103 DAG.getVTList(ValueVTs), Values));
4106 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4107 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4108 "call visitStoreToSwiftError when backend supports swifterror");
4110 SmallVector<EVT, 4> ValueVTs;
4111 SmallVector<uint64_t, 4> Offsets;
4112 const Value *SrcV = I.getOperand(0);
4113 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4114 SrcV->getType(), ValueVTs, &Offsets);
4115 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4116 "expect a single EVT for swifterror");
4118 SDValue Src = getValue(SrcV);
4119 // Create a virtual register, then update the virtual register.
4120 Register VReg =
4121 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4122 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4123 // Chain can be getRoot or getControlRoot.
4124 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4125 SDValue(Src.getNode(), Src.getResNo()));
4126 DAG.setRoot(CopyNode);
4129 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4130 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4131 "call visitLoadFromSwiftError when backend supports swifterror");
4133 assert(!I.isVolatile() &&
4134 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4135 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4136 "Support volatile, non temporal, invariant for load_from_swift_error");
4138 const Value *SV = I.getOperand(0);
4139 Type *Ty = I.getType();
4140 AAMDNodes AAInfo;
4141 I.getAAMetadata(AAInfo);
4142 assert(
4143 (!AA ||
4144 !AA->pointsToConstantMemory(MemoryLocation(
4145 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4146 AAInfo))) &&
4147 "load_from_swift_error should not be constant memory");
4149 SmallVector<EVT, 4> ValueVTs;
4150 SmallVector<uint64_t, 4> Offsets;
4151 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4152 ValueVTs, &Offsets);
4153 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4154 "expect a single EVT for swifterror");
4156 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4157 SDValue L = DAG.getCopyFromReg(
4158 getRoot(), getCurSDLoc(),
4159 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4161 setValue(&I, L);
4164 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4165 if (I.isAtomic())
4166 return visitAtomicStore(I);
4168 const Value *SrcV = I.getOperand(0);
4169 const Value *PtrV = I.getOperand(1);
4171 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4172 if (TLI.supportSwiftError()) {
4173 // Swifterror values can come from either a function parameter with
4174 // swifterror attribute or an alloca with swifterror attribute.
4175 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4176 if (Arg->hasSwiftErrorAttr())
4177 return visitStoreToSwiftError(I);
4180 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4181 if (Alloca->isSwiftError())
4182 return visitStoreToSwiftError(I);
4186 SmallVector<EVT, 4> ValueVTs, MemVTs;
4187 SmallVector<uint64_t, 4> Offsets;
4188 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4189 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4190 unsigned NumValues = ValueVTs.size();
4191 if (NumValues == 0)
4192 return;
4194 // Get the lowered operands. Note that we do this after
4195 // checking if NumResults is zero, because with zero results
4196 // the operands won't have values in the map.
4197 SDValue Src = getValue(SrcV);
4198 SDValue Ptr = getValue(PtrV);
4200 SDValue Root = getRoot();
4201 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4202 SDLoc dl = getCurSDLoc();
4203 EVT PtrVT = Ptr.getValueType();
4204 unsigned Alignment = I.getAlignment();
4205 AAMDNodes AAInfo;
4206 I.getAAMetadata(AAInfo);
4208 auto MMOFlags = MachineMemOperand::MONone;
4209 if (I.isVolatile())
4210 MMOFlags |= MachineMemOperand::MOVolatile;
4211 if (I.hasMetadata(LLVMContext::MD_nontemporal))
4212 MMOFlags |= MachineMemOperand::MONonTemporal;
4213 MMOFlags |= TLI.getMMOFlags(I);
4215 // An aggregate load cannot wrap around the address space, so offsets to its
4216 // parts don't wrap either.
4217 SDNodeFlags Flags;
4218 Flags.setNoUnsignedWrap(true);
4220 unsigned ChainI = 0;
4221 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4222 // See visitLoad comments.
4223 if (ChainI == MaxParallelChains) {
4224 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4225 makeArrayRef(Chains.data(), ChainI));
4226 Root = Chain;
4227 ChainI = 0;
4229 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
4230 DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
4231 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4232 if (MemVTs[i] != ValueVTs[i])
4233 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4234 SDValue St =
4235 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4236 Alignment, MMOFlags, AAInfo);
4237 Chains[ChainI] = St;
4240 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4241 makeArrayRef(Chains.data(), ChainI));
4242 DAG.setRoot(StoreNode);
4245 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4246 bool IsCompressing) {
4247 SDLoc sdl = getCurSDLoc();
4249 auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4250 unsigned& Alignment) {
4251 // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4252 Src0 = I.getArgOperand(0);
4253 Ptr = I.getArgOperand(1);
4254 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4255 Mask = I.getArgOperand(3);
4257 auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4258 unsigned& Alignment) {
4259 // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4260 Src0 = I.getArgOperand(0);
4261 Ptr = I.getArgOperand(1);
4262 Mask = I.getArgOperand(2);
4263 Alignment = 0;
4266 Value *PtrOperand, *MaskOperand, *Src0Operand;
4267 unsigned Alignment;
4268 if (IsCompressing)
4269 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4270 else
4271 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4273 SDValue Ptr = getValue(PtrOperand);
4274 SDValue Src0 = getValue(Src0Operand);
4275 SDValue Mask = getValue(MaskOperand);
4277 EVT VT = Src0.getValueType();
4278 if (!Alignment)
4279 Alignment = DAG.getEVTAlignment(VT);
4281 AAMDNodes AAInfo;
4282 I.getAAMetadata(AAInfo);
4284 MachineMemOperand *MMO =
4285 DAG.getMachineFunction().
4286 getMachineMemOperand(MachinePointerInfo(PtrOperand),
4287 MachineMemOperand::MOStore, VT.getStoreSize(),
4288 Alignment, AAInfo);
4289 SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
4290 MMO, false /* Truncating */,
4291 IsCompressing);
4292 DAG.setRoot(StoreNode);
4293 setValue(&I, StoreNode);
4296 // Get a uniform base for the Gather/Scatter intrinsic.
4297 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4298 // We try to represent it as a base pointer + vector of indices.
4299 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4300 // The first operand of the GEP may be a single pointer or a vector of pointers
4301 // Example:
4302 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4303 // or
4304 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
4305 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4307 // When the first GEP operand is a single pointer - it is the uniform base we
4308 // are looking for. If first operand of the GEP is a splat vector - we
4309 // extract the splat value and use it as a uniform base.
4310 // In all other cases the function returns 'false'.
4311 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4312 ISD::MemIndexType &IndexType, SDValue &Scale,
4313 SelectionDAGBuilder *SDB) {
4314 SelectionDAG& DAG = SDB->DAG;
4315 LLVMContext &Context = *DAG.getContext();
4317 assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4318 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4319 if (!GEP)
4320 return false;
4322 const Value *GEPPtr = GEP->getPointerOperand();
4323 if (!GEPPtr->getType()->isVectorTy())
4324 Ptr = GEPPtr;
4325 else if (!(Ptr = getSplatValue(GEPPtr)))
4326 return false;
4328 unsigned FinalIndex = GEP->getNumOperands() - 1;
4329 Value *IndexVal = GEP->getOperand(FinalIndex);
4331 // Ensure all the other indices are 0.
4332 for (unsigned i = 1; i < FinalIndex; ++i) {
4333 auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4334 if (!C)
4335 return false;
4336 if (isa<VectorType>(C->getType()))
4337 C = C->getSplatValue();
4338 auto *CI = dyn_cast_or_null<ConstantInt>(C);
4339 if (!CI || !CI->isZero())
4340 return false;
4343 // The operands of the GEP may be defined in another basic block.
4344 // In this case we'll not find nodes for the operands.
4345 if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4346 return false;
4348 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4349 const DataLayout &DL = DAG.getDataLayout();
4350 Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4351 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4352 Base = SDB->getValue(Ptr);
4353 Index = SDB->getValue(IndexVal);
4354 IndexType = ISD::SIGNED_SCALED;
4356 if (!Index.getValueType().isVector()) {
4357 unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4358 EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4359 Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4361 return true;
4364 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4365 SDLoc sdl = getCurSDLoc();
4367 // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4368 const Value *Ptr = I.getArgOperand(1);
4369 SDValue Src0 = getValue(I.getArgOperand(0));
4370 SDValue Mask = getValue(I.getArgOperand(3));
4371 EVT VT = Src0.getValueType();
4372 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4373 if (!Alignment)
4374 Alignment = DAG.getEVTAlignment(VT);
4375 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4377 AAMDNodes AAInfo;
4378 I.getAAMetadata(AAInfo);
4380 SDValue Base;
4381 SDValue Index;
4382 ISD::MemIndexType IndexType;
4383 SDValue Scale;
4384 const Value *BasePtr = Ptr;
4385 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4386 this);
4388 const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4389 MachineMemOperand *MMO = DAG.getMachineFunction().
4390 getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4391 MachineMemOperand::MOStore, VT.getStoreSize(),
4392 Alignment, AAInfo);
4393 if (!UniformBase) {
4394 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4395 Index = getValue(Ptr);
4396 IndexType = ISD::SIGNED_SCALED;
4397 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4399 SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4400 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4401 Ops, MMO, IndexType);
4402 DAG.setRoot(Scatter);
4403 setValue(&I, Scatter);
4406 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4407 SDLoc sdl = getCurSDLoc();
4409 auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4410 unsigned& Alignment) {
4411 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4412 Ptr = I.getArgOperand(0);
4413 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4414 Mask = I.getArgOperand(2);
4415 Src0 = I.getArgOperand(3);
4417 auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4418 unsigned& Alignment) {
4419 // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4420 Ptr = I.getArgOperand(0);
4421 Alignment = 0;
4422 Mask = I.getArgOperand(1);
4423 Src0 = I.getArgOperand(2);
4426 Value *PtrOperand, *MaskOperand, *Src0Operand;
4427 unsigned Alignment;
4428 if (IsExpanding)
4429 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4430 else
4431 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4433 SDValue Ptr = getValue(PtrOperand);
4434 SDValue Src0 = getValue(Src0Operand);
4435 SDValue Mask = getValue(MaskOperand);
4437 EVT VT = Src0.getValueType();
4438 if (!Alignment)
4439 Alignment = DAG.getEVTAlignment(VT);
4441 AAMDNodes AAInfo;
4442 I.getAAMetadata(AAInfo);
4443 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4445 // Do not serialize masked loads of constant memory with anything.
4446 bool AddToChain =
4447 !AA || !AA->pointsToConstantMemory(MemoryLocation(
4448 PtrOperand,
4449 LocationSize::precise(
4450 DAG.getDataLayout().getTypeStoreSize(I.getType())),
4451 AAInfo));
4452 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4454 MachineMemOperand *MMO =
4455 DAG.getMachineFunction().
4456 getMachineMemOperand(MachinePointerInfo(PtrOperand),
4457 MachineMemOperand::MOLoad, VT.getStoreSize(),
4458 Alignment, AAInfo, Ranges);
4460 SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4461 ISD::NON_EXTLOAD, IsExpanding);
4462 if (AddToChain)
4463 PendingLoads.push_back(Load.getValue(1));
4464 setValue(&I, Load);
4467 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4468 SDLoc sdl = getCurSDLoc();
4470 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4471 const Value *Ptr = I.getArgOperand(0);
4472 SDValue Src0 = getValue(I.getArgOperand(3));
4473 SDValue Mask = getValue(I.getArgOperand(2));
4475 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4476 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4477 unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4478 if (!Alignment)
4479 Alignment = DAG.getEVTAlignment(VT);
4481 AAMDNodes AAInfo;
4482 I.getAAMetadata(AAInfo);
4483 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4485 SDValue Root = DAG.getRoot();
4486 SDValue Base;
4487 SDValue Index;
4488 ISD::MemIndexType IndexType;
4489 SDValue Scale;
4490 const Value *BasePtr = Ptr;
4491 bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4492 this);
4493 bool ConstantMemory = false;
4494 if (UniformBase && AA &&
4495 AA->pointsToConstantMemory(
4496 MemoryLocation(BasePtr,
4497 LocationSize::precise(
4498 DAG.getDataLayout().getTypeStoreSize(I.getType())),
4499 AAInfo))) {
4500 // Do not serialize (non-volatile) loads of constant memory with anything.
4501 Root = DAG.getEntryNode();
4502 ConstantMemory = true;
4505 MachineMemOperand *MMO =
4506 DAG.getMachineFunction().
4507 getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4508 MachineMemOperand::MOLoad, VT.getStoreSize(),
4509 Alignment, AAInfo, Ranges);
4511 if (!UniformBase) {
4512 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4513 Index = getValue(Ptr);
4514 IndexType = ISD::SIGNED_SCALED;
4515 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4517 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4518 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4519 Ops, MMO, IndexType);
4521 SDValue OutChain = Gather.getValue(1);
4522 if (!ConstantMemory)
4523 PendingLoads.push_back(OutChain);
4524 setValue(&I, Gather);
4527 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4528 SDLoc dl = getCurSDLoc();
4529 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4530 AtomicOrdering FailureOrdering = I.getFailureOrdering();
4531 SyncScope::ID SSID = I.getSyncScopeID();
4533 SDValue InChain = getRoot();
4535 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4536 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4538 auto Alignment = DAG.getEVTAlignment(MemVT);
4540 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4541 if (I.isVolatile())
4542 Flags |= MachineMemOperand::MOVolatile;
4543 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4545 MachineFunction &MF = DAG.getMachineFunction();
4546 MachineMemOperand *MMO =
4547 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4548 Flags, MemVT.getStoreSize(), Alignment,
4549 AAMDNodes(), nullptr, SSID, SuccessOrdering,
4550 FailureOrdering);
4552 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4553 dl, MemVT, VTs, InChain,
4554 getValue(I.getPointerOperand()),
4555 getValue(I.getCompareOperand()),
4556 getValue(I.getNewValOperand()), MMO);
4558 SDValue OutChain = L.getValue(2);
4560 setValue(&I, L);
4561 DAG.setRoot(OutChain);
4564 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4565 SDLoc dl = getCurSDLoc();
4566 ISD::NodeType NT;
4567 switch (I.getOperation()) {
4568 default: llvm_unreachable("Unknown atomicrmw operation");
4569 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4570 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
4571 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
4572 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
4573 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4574 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
4575 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
4576 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
4577 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
4578 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4579 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4580 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4581 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4583 AtomicOrdering Ordering = I.getOrdering();
4584 SyncScope::ID SSID = I.getSyncScopeID();
4586 SDValue InChain = getRoot();
4588 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4589 auto Alignment = DAG.getEVTAlignment(MemVT);
4591 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4592 if (I.isVolatile())
4593 Flags |= MachineMemOperand::MOVolatile;
4594 Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4596 MachineFunction &MF = DAG.getMachineFunction();
4597 MachineMemOperand *MMO =
4598 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4599 MemVT.getStoreSize(), Alignment, AAMDNodes(),
4600 nullptr, SSID, Ordering);
4602 SDValue L =
4603 DAG.getAtomic(NT, dl, MemVT, InChain,
4604 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4605 MMO);
4607 SDValue OutChain = L.getValue(1);
4609 setValue(&I, L);
4610 DAG.setRoot(OutChain);
4613 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4614 SDLoc dl = getCurSDLoc();
4615 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4616 SDValue Ops[3];
4617 Ops[0] = getRoot();
4618 Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4619 TLI.getFenceOperandTy(DAG.getDataLayout()));
4620 Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4621 TLI.getFenceOperandTy(DAG.getDataLayout()));
4622 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4625 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4626 SDLoc dl = getCurSDLoc();
4627 AtomicOrdering Order = I.getOrdering();
4628 SyncScope::ID SSID = I.getSyncScopeID();
4630 SDValue InChain = getRoot();
4632 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4633 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4634 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4636 if (!TLI.supportsUnalignedAtomics() &&
4637 I.getAlignment() < MemVT.getSizeInBits() / 8)
4638 report_fatal_error("Cannot generate unaligned atomic load");
4640 auto Flags = MachineMemOperand::MOLoad;
4641 if (I.isVolatile())
4642 Flags |= MachineMemOperand::MOVolatile;
4643 if (I.hasMetadata(LLVMContext::MD_invariant_load))
4644 Flags |= MachineMemOperand::MOInvariant;
4645 if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
4646 DAG.getDataLayout()))
4647 Flags |= MachineMemOperand::MODereferenceable;
4649 Flags |= TLI.getMMOFlags(I);
4651 MachineMemOperand *MMO =
4652 DAG.getMachineFunction().
4653 getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4654 Flags, MemVT.getStoreSize(),
4655 I.getAlignment() ? I.getAlignment() :
4656 DAG.getEVTAlignment(MemVT),
4657 AAMDNodes(), nullptr, SSID, Order);
4659 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4661 SDValue Ptr = getValue(I.getPointerOperand());
4663 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4664 // TODO: Once this is better exercised by tests, it should be merged with
4665 // the normal path for loads to prevent future divergence.
4666 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4667 if (MemVT != VT)
4668 L = DAG.getPtrExtOrTrunc(L, dl, VT);
4670 setValue(&I, L);
4671 if (!I.isUnordered()) {
4672 SDValue OutChain = L.getValue(1);
4673 DAG.setRoot(OutChain);
4675 return;
4678 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4679 Ptr, MMO);
4681 SDValue OutChain = L.getValue(1);
4682 if (MemVT != VT)
4683 L = DAG.getPtrExtOrTrunc(L, dl, VT);
4685 setValue(&I, L);
4686 DAG.setRoot(OutChain);
4689 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4690 SDLoc dl = getCurSDLoc();
4692 AtomicOrdering Ordering = I.getOrdering();
4693 SyncScope::ID SSID = I.getSyncScopeID();
4695 SDValue InChain = getRoot();
4697 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4698 EVT MemVT =
4699 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4701 if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4702 report_fatal_error("Cannot generate unaligned atomic store");
4704 auto Flags = MachineMemOperand::MOStore;
4705 if (I.isVolatile())
4706 Flags |= MachineMemOperand::MOVolatile;
4707 Flags |= TLI.getMMOFlags(I);
4709 MachineFunction &MF = DAG.getMachineFunction();
4710 MachineMemOperand *MMO =
4711 MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4712 MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4713 nullptr, SSID, Ordering);
4715 SDValue Val = getValue(I.getValueOperand());
4716 if (Val.getValueType() != MemVT)
4717 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4718 SDValue Ptr = getValue(I.getPointerOperand());
4720 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4721 // TODO: Once this is better exercised by tests, it should be merged with
4722 // the normal path for stores to prevent future divergence.
4723 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4724 DAG.setRoot(S);
4725 return;
4727 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4728 Ptr, Val, MMO);
4731 DAG.setRoot(OutChain);
4734 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4735 /// node.
4736 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4737 unsigned Intrinsic) {
4738 // Ignore the callsite's attributes. A specific call site may be marked with
4739 // readnone, but the lowering code will expect the chain based on the
4740 // definition.
4741 const Function *F = I.getCalledFunction();
4742 bool HasChain = !F->doesNotAccessMemory();
4743 bool OnlyLoad = HasChain && F->onlyReadsMemory();
4745 // Build the operand list.
4746 SmallVector<SDValue, 8> Ops;
4747 if (HasChain) { // If this intrinsic has side-effects, chainify it.
4748 if (OnlyLoad) {
4749 // We don't need to serialize loads against other loads.
4750 Ops.push_back(DAG.getRoot());
4751 } else {
4752 Ops.push_back(getRoot());
4756 // Info is set by getTgtMemInstrinsic
4757 TargetLowering::IntrinsicInfo Info;
4758 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4759 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4760 DAG.getMachineFunction(),
4761 Intrinsic);
4763 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4764 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4765 Info.opc == ISD::INTRINSIC_W_CHAIN)
4766 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4767 TLI.getPointerTy(DAG.getDataLayout())));
4769 // Add all operands of the call to the operand list.
4770 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4771 const Value *Arg = I.getArgOperand(i);
4772 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4773 Ops.push_back(getValue(Arg));
4774 continue;
4777 // Use TargetConstant instead of a regular constant for immarg.
4778 EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4779 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4780 assert(CI->getBitWidth() <= 64 &&
4781 "large intrinsic immediates not handled");
4782 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4783 } else {
4784 Ops.push_back(
4785 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4789 SmallVector<EVT, 4> ValueVTs;
4790 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4792 if (HasChain)
4793 ValueVTs.push_back(MVT::Other);
4795 SDVTList VTs = DAG.getVTList(ValueVTs);
4797 // Create the node.
4798 SDValue Result;
4799 if (IsTgtIntrinsic) {
4800 // This is target intrinsic that touches memory
4801 AAMDNodes AAInfo;
4802 I.getAAMetadata(AAInfo);
4803 Result = DAG.getMemIntrinsicNode(
4804 Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4805 MachinePointerInfo(Info.ptrVal, Info.offset),
4806 Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4807 } else if (!HasChain) {
4808 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4809 } else if (!I.getType()->isVoidTy()) {
4810 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4811 } else {
4812 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4815 if (HasChain) {
4816 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4817 if (OnlyLoad)
4818 PendingLoads.push_back(Chain);
4819 else
4820 DAG.setRoot(Chain);
4823 if (!I.getType()->isVoidTy()) {
4824 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4825 EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4826 Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4827 } else
4828 Result = lowerRangeToAssertZExt(DAG, I, Result);
4830 setValue(&I, Result);
4834 /// GetSignificand - Get the significand and build it into a floating-point
4835 /// number with exponent of 1:
4837 /// Op = (Op & 0x007fffff) | 0x3f800000;
4839 /// where Op is the hexadecimal representation of floating point value.
4840 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4841 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4842 DAG.getConstant(0x007fffff, dl, MVT::i32));
4843 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4844 DAG.getConstant(0x3f800000, dl, MVT::i32));
4845 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4848 /// GetExponent - Get the exponent:
4850 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4852 /// where Op is the hexadecimal representation of floating point value.
4853 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4854 const TargetLowering &TLI, const SDLoc &dl) {
4855 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4856 DAG.getConstant(0x7f800000, dl, MVT::i32));
4857 SDValue t1 = DAG.getNode(
4858 ISD::SRL, dl, MVT::i32, t0,
4859 DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4860 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4861 DAG.getConstant(127, dl, MVT::i32));
4862 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4865 /// getF32Constant - Get 32-bit floating point constant.
4866 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4867 const SDLoc &dl) {
4868 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4869 MVT::f32);
4872 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4873 SelectionDAG &DAG) {
4874 // TODO: What fast-math-flags should be set on the floating-point nodes?
4876 // IntegerPartOfX = ((int32_t)(t0);
4877 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4879 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
4880 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4881 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4883 // IntegerPartOfX <<= 23;
4884 IntegerPartOfX = DAG.getNode(
4885 ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4886 DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4887 DAG.getDataLayout())));
4889 SDValue TwoToFractionalPartOfX;
4890 if (LimitFloatPrecision <= 6) {
4891 // For floating-point precision of 6:
4893 // TwoToFractionalPartOfX =
4894 // 0.997535578f +
4895 // (0.735607626f + 0.252464424f * x) * x;
4897 // error 0.0144103317, which is 6 bits
4898 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4899 getF32Constant(DAG, 0x3e814304, dl));
4900 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4901 getF32Constant(DAG, 0x3f3c50c8, dl));
4902 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4903 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4904 getF32Constant(DAG, 0x3f7f5e7e, dl));
4905 } else if (LimitFloatPrecision <= 12) {
4906 // For floating-point precision of 12:
4908 // TwoToFractionalPartOfX =
4909 // 0.999892986f +
4910 // (0.696457318f +
4911 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4913 // error 0.000107046256, which is 13 to 14 bits
4914 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4915 getF32Constant(DAG, 0x3da235e3, dl));
4916 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4917 getF32Constant(DAG, 0x3e65b8f3, dl));
4918 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4919 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4920 getF32Constant(DAG, 0x3f324b07, dl));
4921 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4922 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4923 getF32Constant(DAG, 0x3f7ff8fd, dl));
4924 } else { // LimitFloatPrecision <= 18
4925 // For floating-point precision of 18:
4927 // TwoToFractionalPartOfX =
4928 // 0.999999982f +
4929 // (0.693148872f +
4930 // (0.240227044f +
4931 // (0.554906021e-1f +
4932 // (0.961591928e-2f +
4933 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4934 // error 2.47208000*10^(-7), which is better than 18 bits
4935 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4936 getF32Constant(DAG, 0x3924b03e, dl));
4937 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4938 getF32Constant(DAG, 0x3ab24b87, dl));
4939 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4940 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4941 getF32Constant(DAG, 0x3c1d8c17, dl));
4942 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4943 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4944 getF32Constant(DAG, 0x3d634a1d, dl));
4945 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4946 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4947 getF32Constant(DAG, 0x3e75fe14, dl));
4948 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4949 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4950 getF32Constant(DAG, 0x3f317234, dl));
4951 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4952 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4953 getF32Constant(DAG, 0x3f800000, dl));
4956 // Add the exponent into the result in integer domain.
4957 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4958 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4959 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4962 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4963 /// limited-precision mode.
4964 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4965 const TargetLowering &TLI) {
4966 if (Op.getValueType() == MVT::f32 &&
4967 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4969 // Put the exponent in the right bit position for later addition to the
4970 // final result:
4972 // #define LOG2OFe 1.4426950f
4973 // t0 = Op * LOG2OFe
4975 // TODO: What fast-math-flags should be set here?
4976 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4977 getF32Constant(DAG, 0x3fb8aa3b, dl));
4978 return getLimitedPrecisionExp2(t0, dl, DAG);
4981 // No special expansion.
4982 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4985 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4986 /// limited-precision mode.
4987 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4988 const TargetLowering &TLI) {
4989 // TODO: What fast-math-flags should be set on the floating-point nodes?
4991 if (Op.getValueType() == MVT::f32 &&
4992 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4993 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4995 // Scale the exponent by log(2) [0.69314718f].
4996 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4997 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4998 getF32Constant(DAG, 0x3f317218, dl));
5000 // Get the significand and build it into a floating-point number with
5001 // exponent of 1.
5002 SDValue X = GetSignificand(DAG, Op1, dl);
5004 SDValue LogOfMantissa;
5005 if (LimitFloatPrecision <= 6) {
5006 // For floating-point precision of 6:
5008 // LogofMantissa =
5009 // -1.1609546f +
5010 // (1.4034025f - 0.23903021f * x) * x;
5012 // error 0.0034276066, which is better than 8 bits
5013 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5014 getF32Constant(DAG, 0xbe74c456, dl));
5015 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5016 getF32Constant(DAG, 0x3fb3a2b1, dl));
5017 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5018 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5019 getF32Constant(DAG, 0x3f949a29, dl));
5020 } else if (LimitFloatPrecision <= 12) {
5021 // For floating-point precision of 12:
5023 // LogOfMantissa =
5024 // -1.7417939f +
5025 // (2.8212026f +
5026 // (-1.4699568f +
5027 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5029 // error 0.000061011436, which is 14 bits
5030 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5031 getF32Constant(DAG, 0xbd67b6d6, dl));
5032 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5033 getF32Constant(DAG, 0x3ee4f4b8, dl));
5034 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5035 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5036 getF32Constant(DAG, 0x3fbc278b, dl));
5037 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5038 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5039 getF32Constant(DAG, 0x40348e95, dl));
5040 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5041 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5042 getF32Constant(DAG, 0x3fdef31a, dl));
5043 } else { // LimitFloatPrecision <= 18
5044 // For floating-point precision of 18:
5046 // LogOfMantissa =
5047 // -2.1072184f +
5048 // (4.2372794f +
5049 // (-3.7029485f +
5050 // (2.2781945f +
5051 // (-0.87823314f +
5052 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5054 // error 0.0000023660568, which is better than 18 bits
5055 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5056 getF32Constant(DAG, 0xbc91e5ac, dl));
5057 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5058 getF32Constant(DAG, 0x3e4350aa, dl));
5059 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5060 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5061 getF32Constant(DAG, 0x3f60d3e3, dl));
5062 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5063 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5064 getF32Constant(DAG, 0x4011cdf0, dl));
5065 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5066 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5067 getF32Constant(DAG, 0x406cfd1c, dl));
5068 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5069 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5070 getF32Constant(DAG, 0x408797cb, dl));
5071 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5072 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5073 getF32Constant(DAG, 0x4006dcab, dl));
5076 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5079 // No special expansion.
5080 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5083 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5084 /// limited-precision mode.
5085 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5086 const TargetLowering &TLI) {
5087 // TODO: What fast-math-flags should be set on the floating-point nodes?
5089 if (Op.getValueType() == MVT::f32 &&
5090 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5091 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5093 // Get the exponent.
5094 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5096 // Get the significand and build it into a floating-point number with
5097 // exponent of 1.
5098 SDValue X = GetSignificand(DAG, Op1, dl);
5100 // Different possible minimax approximations of significand in
5101 // floating-point for various degrees of accuracy over [1,2].
5102 SDValue Log2ofMantissa;
5103 if (LimitFloatPrecision <= 6) {
5104 // For floating-point precision of 6:
5106 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5108 // error 0.0049451742, which is more than 7 bits
5109 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5110 getF32Constant(DAG, 0xbeb08fe0, dl));
5111 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5112 getF32Constant(DAG, 0x40019463, dl));
5113 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5114 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5115 getF32Constant(DAG, 0x3fd6633d, dl));
5116 } else if (LimitFloatPrecision <= 12) {
5117 // For floating-point precision of 12:
5119 // Log2ofMantissa =
5120 // -2.51285454f +
5121 // (4.07009056f +
5122 // (-2.12067489f +
5123 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5125 // error 0.0000876136000, which is better than 13 bits
5126 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5127 getF32Constant(DAG, 0xbda7262e, dl));
5128 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5129 getF32Constant(DAG, 0x3f25280b, dl));
5130 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5131 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5132 getF32Constant(DAG, 0x4007b923, dl));
5133 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5134 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5135 getF32Constant(DAG, 0x40823e2f, dl));
5136 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5137 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5138 getF32Constant(DAG, 0x4020d29c, dl));
5139 } else { // LimitFloatPrecision <= 18
5140 // For floating-point precision of 18:
5142 // Log2ofMantissa =
5143 // -3.0400495f +
5144 // (6.1129976f +
5145 // (-5.3420409f +
5146 // (3.2865683f +
5147 // (-1.2669343f +
5148 // (0.27515199f -
5149 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5151 // error 0.0000018516, which is better than 18 bits
5152 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5153 getF32Constant(DAG, 0xbcd2769e, dl));
5154 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5155 getF32Constant(DAG, 0x3e8ce0b9, dl));
5156 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5157 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5158 getF32Constant(DAG, 0x3fa22ae7, dl));
5159 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5160 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5161 getF32Constant(DAG, 0x40525723, dl));
5162 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5163 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5164 getF32Constant(DAG, 0x40aaf200, dl));
5165 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5166 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5167 getF32Constant(DAG, 0x40c39dad, dl));
5168 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5169 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5170 getF32Constant(DAG, 0x4042902c, dl));
5173 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5176 // No special expansion.
5177 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5180 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5181 /// limited-precision mode.
5182 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5183 const TargetLowering &TLI) {
5184 // TODO: What fast-math-flags should be set on the floating-point nodes?
5186 if (Op.getValueType() == MVT::f32 &&
5187 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5188 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5190 // Scale the exponent by log10(2) [0.30102999f].
5191 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5192 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5193 getF32Constant(DAG, 0x3e9a209a, dl));
5195 // Get the significand and build it into a floating-point number with
5196 // exponent of 1.
5197 SDValue X = GetSignificand(DAG, Op1, dl);
5199 SDValue Log10ofMantissa;
5200 if (LimitFloatPrecision <= 6) {
5201 // For floating-point precision of 6:
5203 // Log10ofMantissa =
5204 // -0.50419619f +
5205 // (0.60948995f - 0.10380950f * x) * x;
5207 // error 0.0014886165, which is 6 bits
5208 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5209 getF32Constant(DAG, 0xbdd49a13, dl));
5210 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5211 getF32Constant(DAG, 0x3f1c0789, dl));
5212 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5213 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5214 getF32Constant(DAG, 0x3f011300, dl));
5215 } else if (LimitFloatPrecision <= 12) {
5216 // For floating-point precision of 12:
5218 // Log10ofMantissa =
5219 // -0.64831180f +
5220 // (0.91751397f +
5221 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5223 // error 0.00019228036, which is better than 12 bits
5224 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5225 getF32Constant(DAG, 0x3d431f31, dl));
5226 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5227 getF32Constant(DAG, 0x3ea21fb2, dl));
5228 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5229 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5230 getF32Constant(DAG, 0x3f6ae232, dl));
5231 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5232 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5233 getF32Constant(DAG, 0x3f25f7c3, dl));
5234 } else { // LimitFloatPrecision <= 18
5235 // For floating-point precision of 18:
5237 // Log10ofMantissa =
5238 // -0.84299375f +
5239 // (1.5327582f +
5240 // (-1.0688956f +
5241 // (0.49102474f +
5242 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5244 // error 0.0000037995730, which is better than 18 bits
5245 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5246 getF32Constant(DAG, 0x3c5d51ce, dl));
5247 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5248 getF32Constant(DAG, 0x3e00685a, dl));
5249 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5250 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5251 getF32Constant(DAG, 0x3efb6798, dl));
5252 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5253 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5254 getF32Constant(DAG, 0x3f88d192, dl));
5255 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5256 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5257 getF32Constant(DAG, 0x3fc4316c, dl));
5258 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5259 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5260 getF32Constant(DAG, 0x3f57ce70, dl));
5263 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5266 // No special expansion.
5267 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5270 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5271 /// limited-precision mode.
5272 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5273 const TargetLowering &TLI) {
5274 if (Op.getValueType() == MVT::f32 &&
5275 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5276 return getLimitedPrecisionExp2(Op, dl, DAG);
5278 // No special expansion.
5279 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5282 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5283 /// limited-precision mode with x == 10.0f.
5284 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5285 SelectionDAG &DAG, const TargetLowering &TLI) {
5286 bool IsExp10 = false;
5287 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5288 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5289 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5290 APFloat Ten(10.0f);
5291 IsExp10 = LHSC->isExactlyValue(Ten);
5295 // TODO: What fast-math-flags should be set on the FMUL node?
5296 if (IsExp10) {
5297 // Put the exponent in the right bit position for later addition to the
5298 // final result:
5300 // #define LOG2OF10 3.3219281f
5301 // t0 = Op * LOG2OF10;
5302 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5303 getF32Constant(DAG, 0x40549a78, dl));
5304 return getLimitedPrecisionExp2(t0, dl, DAG);
5307 // No special expansion.
5308 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5311 /// ExpandPowI - Expand a llvm.powi intrinsic.
5312 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5313 SelectionDAG &DAG) {
5314 // If RHS is a constant, we can expand this out to a multiplication tree,
5315 // otherwise we end up lowering to a call to __powidf2 (for example). When
5316 // optimizing for size, we only want to do this if the expansion would produce
5317 // a small number of multiplies, otherwise we do the full expansion.
5318 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5319 // Get the exponent as a positive value.
5320 unsigned Val = RHSC->getSExtValue();
5321 if ((int)Val < 0) Val = -Val;
5323 // powi(x, 0) -> 1.0
5324 if (Val == 0)
5325 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5327 const Function &F = DAG.getMachineFunction().getFunction();
5328 if (!F.hasOptSize() ||
5329 // If optimizing for size, don't insert too many multiplies.
5330 // This inserts up to 5 multiplies.
5331 countPopulation(Val) + Log2_32(Val) < 7) {
5332 // We use the simple binary decomposition method to generate the multiply
5333 // sequence. There are more optimal ways to do this (for example,
5334 // powi(x,15) generates one more multiply than it should), but this has
5335 // the benefit of being both really simple and much better than a libcall.
5336 SDValue Res; // Logically starts equal to 1.0
5337 SDValue CurSquare = LHS;
5338 // TODO: Intrinsics should have fast-math-flags that propagate to these
5339 // nodes.
5340 while (Val) {
5341 if (Val & 1) {
5342 if (Res.getNode())
5343 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5344 else
5345 Res = CurSquare; // 1.0*CurSquare.
5348 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5349 CurSquare, CurSquare);
5350 Val >>= 1;
5353 // If the original was negative, invert the result, producing 1/(x*x*x).
5354 if (RHSC->getSExtValue() < 0)
5355 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5356 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5357 return Res;
5361 // Otherwise, expand to a libcall.
5362 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5365 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5366 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5367 static void
5368 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5369 const SDValue &N) {
5370 switch (N.getOpcode()) {
5371 case ISD::CopyFromReg: {
5372 SDValue Op = N.getOperand(1);
5373 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5374 Op.getValueType().getSizeInBits());
5375 return;
5377 case ISD::BITCAST:
5378 case ISD::AssertZext:
5379 case ISD::AssertSext:
5380 case ISD::TRUNCATE:
5381 getUnderlyingArgRegs(Regs, N.getOperand(0));
5382 return;
5383 case ISD::BUILD_PAIR:
5384 case ISD::BUILD_VECTOR:
5385 case ISD::CONCAT_VECTORS:
5386 for (SDValue Op : N->op_values())
5387 getUnderlyingArgRegs(Regs, Op);
5388 return;
5389 default:
5390 return;
5394 /// If the DbgValueInst is a dbg_value of a function argument, create the
5395 /// corresponding DBG_VALUE machine instruction for it now. At the end of
5396 /// instruction selection, they will be inserted to the entry BB.
5397 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5398 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5399 DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5400 const Argument *Arg = dyn_cast<Argument>(V);
5401 if (!Arg)
5402 return false;
5404 if (!IsDbgDeclare) {
5405 // ArgDbgValues are hoisted to the beginning of the entry block. So we
5406 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5407 // the entry block.
5408 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5409 if (!IsInEntryBlock)
5410 return false;
5412 // ArgDbgValues are hoisted to the beginning of the entry block. So we
5413 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5414 // variable that also is a param.
5416 // Although, if we are at the top of the entry block already, we can still
5417 // emit using ArgDbgValue. This might catch some situations when the
5418 // dbg.value refers to an argument that isn't used in the entry block, so
5419 // any CopyToReg node would be optimized out and the only way to express
5420 // this DBG_VALUE is by using the physical reg (or FI) as done in this
5421 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
5422 // we should only emit as ArgDbgValue if the Variable is an argument to the
5423 // current function, and the dbg.value intrinsic is found in the entry
5424 // block.
5425 bool VariableIsFunctionInputArg = Variable->isParameter() &&
5426 !DL->getInlinedAt();
5427 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5428 if (!IsInPrologue && !VariableIsFunctionInputArg)
5429 return false;
5431 // Here we assume that a function argument on IR level only can be used to
5432 // describe one input parameter on source level. If we for example have
5433 // source code like this
5435 // struct A { long x, y; };
5436 // void foo(struct A a, long b) {
5437 // ...
5438 // b = a.x;
5439 // ...
5440 // }
5442 // and IR like this
5444 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
5445 // entry:
5446 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5447 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5448 // call void @llvm.dbg.value(metadata i32 %b, "b",
5449 // ...
5450 // call void @llvm.dbg.value(metadata i32 %a1, "b"
5451 // ...
5453 // then the last dbg.value is describing a parameter "b" using a value that
5454 // is an argument. But since we already has used %a1 to describe a parameter
5455 // we should not handle that last dbg.value here (that would result in an
5456 // incorrect hoisting of the DBG_VALUE to the function entry).
5457 // Notice that we allow one dbg.value per IR level argument, to accomodate
5458 // for the situation with fragments above.
5459 if (VariableIsFunctionInputArg) {
5460 unsigned ArgNo = Arg->getArgNo();
5461 if (ArgNo >= FuncInfo.DescribedArgs.size())
5462 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5463 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5464 return false;
5465 FuncInfo.DescribedArgs.set(ArgNo);
5469 MachineFunction &MF = DAG.getMachineFunction();
5470 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5472 bool IsIndirect = false;
5473 Optional<MachineOperand> Op;
5474 // Some arguments' frame index is recorded during argument lowering.
5475 int FI = FuncInfo.getArgumentFrameIndex(Arg);
5476 if (FI != std::numeric_limits<int>::max())
5477 Op = MachineOperand::CreateFI(FI);
5479 SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5480 if (!Op && N.getNode()) {
5481 getUnderlyingArgRegs(ArgRegsAndSizes, N);
5482 Register Reg;
5483 if (ArgRegsAndSizes.size() == 1)
5484 Reg = ArgRegsAndSizes.front().first;
5486 if (Reg && Reg.isVirtual()) {
5487 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5488 Register PR = RegInfo.getLiveInPhysReg(Reg);
5489 if (PR)
5490 Reg = PR;
5492 if (Reg) {
5493 Op = MachineOperand::CreateReg(Reg, false);
5494 IsIndirect = IsDbgDeclare;
5498 if (!Op && N.getNode()) {
5499 // Check if frame index is available.
5500 SDValue LCandidate = peekThroughBitcasts(N);
5501 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5502 if (FrameIndexSDNode *FINode =
5503 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5504 Op = MachineOperand::CreateFI(FINode->getIndex());
5507 if (!Op) {
5508 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5509 auto splitMultiRegDbgValue
5510 = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5511 unsigned Offset = 0;
5512 for (auto RegAndSize : SplitRegs) {
5513 auto FragmentExpr = DIExpression::createFragmentExpression(
5514 Expr, Offset, RegAndSize.second);
5515 if (!FragmentExpr)
5516 continue;
5517 FuncInfo.ArgDbgValues.push_back(
5518 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5519 RegAndSize.first, Variable, *FragmentExpr));
5520 Offset += RegAndSize.second;
5524 // Check if ValueMap has reg number.
5525 DenseMap<const Value *, unsigned>::const_iterator
5526 VMI = FuncInfo.ValueMap.find(V);
5527 if (VMI != FuncInfo.ValueMap.end()) {
5528 const auto &TLI = DAG.getTargetLoweringInfo();
5529 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5530 V->getType(), getABIRegCopyCC(V));
5531 if (RFV.occupiesMultipleRegs()) {
5532 splitMultiRegDbgValue(RFV.getRegsAndSizes());
5533 return true;
5536 Op = MachineOperand::CreateReg(VMI->second, false);
5537 IsIndirect = IsDbgDeclare;
5538 } else if (ArgRegsAndSizes.size() > 1) {
5539 // This was split due to the calling convention, and no virtual register
5540 // mapping exists for the value.
5541 splitMultiRegDbgValue(ArgRegsAndSizes);
5542 return true;
5546 if (!Op)
5547 return false;
5549 assert(Variable->isValidLocationForIntrinsic(DL) &&
5550 "Expected inlined-at fields to agree");
5551 IsIndirect = (Op->isReg()) ? IsIndirect : true;
5552 FuncInfo.ArgDbgValues.push_back(
5553 BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5554 *Op, Variable, Expr));
5556 return true;
5559 /// Return the appropriate SDDbgValue based on N.
5560 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5561 DILocalVariable *Variable,
5562 DIExpression *Expr,
5563 const DebugLoc &dl,
5564 unsigned DbgSDNodeOrder) {
5565 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5566 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5567 // stack slot locations.
5569 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5570 // debug values here after optimization:
5572 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
5573 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5575 // Both describe the direct values of their associated variables.
5576 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5577 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5579 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5580 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5583 // VisualStudio defines setjmp as _setjmp
5584 #if defined(_MSC_VER) && defined(setjmp) && \
5585 !defined(setjmp_undefined_for_msvc)
5586 # pragma push_macro("setjmp")
5587 # undef setjmp
5588 # define setjmp_undefined_for_msvc
5589 #endif
5591 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5592 switch (Intrinsic) {
5593 case Intrinsic::smul_fix:
5594 return ISD::SMULFIX;
5595 case Intrinsic::umul_fix:
5596 return ISD::UMULFIX;
5597 default:
5598 llvm_unreachable("Unhandled fixed point intrinsic");
5602 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5603 const char *FunctionName) {
5604 assert(FunctionName && "FunctionName must not be nullptr");
5605 SDValue Callee = DAG.getExternalSymbol(
5606 FunctionName,
5607 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5608 LowerCallTo(&I, Callee, I.isTailCall());
5611 /// Lower the call to the specified intrinsic function.
5612 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5613 unsigned Intrinsic) {
5614 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5615 SDLoc sdl = getCurSDLoc();
5616 DebugLoc dl = getCurDebugLoc();
5617 SDValue Res;
5619 switch (Intrinsic) {
5620 default:
5621 // By default, turn this into a target intrinsic node.
5622 visitTargetIntrinsic(I, Intrinsic);
5623 return;
5624 case Intrinsic::vastart: visitVAStart(I); return;
5625 case Intrinsic::vaend: visitVAEnd(I); return;
5626 case Intrinsic::vacopy: visitVACopy(I); return;
5627 case Intrinsic::returnaddress:
5628 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5629 TLI.getPointerTy(DAG.getDataLayout()),
5630 getValue(I.getArgOperand(0))));
5631 return;
5632 case Intrinsic::addressofreturnaddress:
5633 setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5634 TLI.getPointerTy(DAG.getDataLayout())));
5635 return;
5636 case Intrinsic::sponentry:
5637 setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5638 TLI.getFrameIndexTy(DAG.getDataLayout())));
5639 return;
5640 case Intrinsic::frameaddress:
5641 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5642 TLI.getFrameIndexTy(DAG.getDataLayout()),
5643 getValue(I.getArgOperand(0))));
5644 return;
5645 case Intrinsic::read_register: {
5646 Value *Reg = I.getArgOperand(0);
5647 SDValue Chain = getRoot();
5648 SDValue RegName =
5649 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5650 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5651 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5652 DAG.getVTList(VT, MVT::Other), Chain, RegName);
5653 setValue(&I, Res);
5654 DAG.setRoot(Res.getValue(1));
5655 return;
5657 case Intrinsic::write_register: {
5658 Value *Reg = I.getArgOperand(0);
5659 Value *RegValue = I.getArgOperand(1);
5660 SDValue Chain = getRoot();
5661 SDValue RegName =
5662 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5663 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5664 RegName, getValue(RegValue)));
5665 return;
5667 case Intrinsic::setjmp:
5668 lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
5669 return;
5670 case Intrinsic::longjmp:
5671 lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
5672 return;
5673 case Intrinsic::memcpy: {
5674 const auto &MCI = cast<MemCpyInst>(I);
5675 SDValue Op1 = getValue(I.getArgOperand(0));
5676 SDValue Op2 = getValue(I.getArgOperand(1));
5677 SDValue Op3 = getValue(I.getArgOperand(2));
5678 // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5679 unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5680 unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5681 unsigned Align = MinAlign(DstAlign, SrcAlign);
5682 bool isVol = MCI.isVolatile();
5683 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5684 // FIXME: Support passing different dest/src alignments to the memcpy DAG
5685 // node.
5686 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5687 false, isTC,
5688 MachinePointerInfo(I.getArgOperand(0)),
5689 MachinePointerInfo(I.getArgOperand(1)));
5690 updateDAGForMaybeTailCall(MC);
5691 return;
5693 case Intrinsic::memset: {
5694 const auto &MSI = cast<MemSetInst>(I);
5695 SDValue Op1 = getValue(I.getArgOperand(0));
5696 SDValue Op2 = getValue(I.getArgOperand(1));
5697 SDValue Op3 = getValue(I.getArgOperand(2));
5698 // @llvm.memset defines 0 and 1 to both mean no alignment.
5699 unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5700 bool isVol = MSI.isVolatile();
5701 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5702 SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5703 isTC, MachinePointerInfo(I.getArgOperand(0)));
5704 updateDAGForMaybeTailCall(MS);
5705 return;
5707 case Intrinsic::memmove: {
5708 const auto &MMI = cast<MemMoveInst>(I);
5709 SDValue Op1 = getValue(I.getArgOperand(0));
5710 SDValue Op2 = getValue(I.getArgOperand(1));
5711 SDValue Op3 = getValue(I.getArgOperand(2));
5712 // @llvm.memmove defines 0 and 1 to both mean no alignment.
5713 unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5714 unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5715 unsigned Align = MinAlign(DstAlign, SrcAlign);
5716 bool isVol = MMI.isVolatile();
5717 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5718 // FIXME: Support passing different dest/src alignments to the memmove DAG
5719 // node.
5720 SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5721 isTC, MachinePointerInfo(I.getArgOperand(0)),
5722 MachinePointerInfo(I.getArgOperand(1)));
5723 updateDAGForMaybeTailCall(MM);
5724 return;
5726 case Intrinsic::memcpy_element_unordered_atomic: {
5727 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5728 SDValue Dst = getValue(MI.getRawDest());
5729 SDValue Src = getValue(MI.getRawSource());
5730 SDValue Length = getValue(MI.getLength());
5732 unsigned DstAlign = MI.getDestAlignment();
5733 unsigned SrcAlign = MI.getSourceAlignment();
5734 Type *LengthTy = MI.getLength()->getType();
5735 unsigned ElemSz = MI.getElementSizeInBytes();
5736 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5737 SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5738 SrcAlign, Length, LengthTy, ElemSz, isTC,
5739 MachinePointerInfo(MI.getRawDest()),
5740 MachinePointerInfo(MI.getRawSource()));
5741 updateDAGForMaybeTailCall(MC);
5742 return;
5744 case Intrinsic::memmove_element_unordered_atomic: {
5745 auto &MI = cast<AtomicMemMoveInst>(I);
5746 SDValue Dst = getValue(MI.getRawDest());
5747 SDValue Src = getValue(MI.getRawSource());
5748 SDValue Length = getValue(MI.getLength());
5750 unsigned DstAlign = MI.getDestAlignment();
5751 unsigned SrcAlign = MI.getSourceAlignment();
5752 Type *LengthTy = MI.getLength()->getType();
5753 unsigned ElemSz = MI.getElementSizeInBytes();
5754 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5755 SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5756 SrcAlign, Length, LengthTy, ElemSz, isTC,
5757 MachinePointerInfo(MI.getRawDest()),
5758 MachinePointerInfo(MI.getRawSource()));
5759 updateDAGForMaybeTailCall(MC);
5760 return;
5762 case Intrinsic::memset_element_unordered_atomic: {
5763 auto &MI = cast<AtomicMemSetInst>(I);
5764 SDValue Dst = getValue(MI.getRawDest());
5765 SDValue Val = getValue(MI.getValue());
5766 SDValue Length = getValue(MI.getLength());
5768 unsigned DstAlign = MI.getDestAlignment();
5769 Type *LengthTy = MI.getLength()->getType();
5770 unsigned ElemSz = MI.getElementSizeInBytes();
5771 bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5772 SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5773 LengthTy, ElemSz, isTC,
5774 MachinePointerInfo(MI.getRawDest()));
5775 updateDAGForMaybeTailCall(MC);
5776 return;
5778 case Intrinsic::dbg_addr:
5779 case Intrinsic::dbg_declare: {
5780 const auto &DI = cast<DbgVariableIntrinsic>(I);
5781 DILocalVariable *Variable = DI.getVariable();
5782 DIExpression *Expression = DI.getExpression();
5783 dropDanglingDebugInfo(Variable, Expression);
5784 assert(Variable && "Missing variable");
5786 // Check if address has undef value.
5787 const Value *Address = DI.getVariableLocation();
5788 if (!Address || isa<UndefValue>(Address) ||
5789 (Address->use_empty() && !isa<Argument>(Address))) {
5790 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5791 return;
5794 bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5796 // Check if this variable can be described by a frame index, typically
5797 // either as a static alloca or a byval parameter.
5798 int FI = std::numeric_limits<int>::max();
5799 if (const auto *AI =
5800 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5801 if (AI->isStaticAlloca()) {
5802 auto I = FuncInfo.StaticAllocaMap.find(AI);
5803 if (I != FuncInfo.StaticAllocaMap.end())
5804 FI = I->second;
5806 } else if (const auto *Arg = dyn_cast<Argument>(
5807 Address->stripInBoundsConstantOffsets())) {
5808 FI = FuncInfo.getArgumentFrameIndex(Arg);
5811 // llvm.dbg.addr is control dependent and always generates indirect
5812 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5813 // the MachineFunction variable table.
5814 if (FI != std::numeric_limits<int>::max()) {
5815 if (Intrinsic == Intrinsic::dbg_addr) {
5816 SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5817 Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5818 DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5820 return;
5823 SDValue &N = NodeMap[Address];
5824 if (!N.getNode() && isa<Argument>(Address))
5825 // Check unused arguments map.
5826 N = UnusedArgNodeMap[Address];
5827 SDDbgValue *SDV;
5828 if (N.getNode()) {
5829 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5830 Address = BCI->getOperand(0);
5831 // Parameters are handled specially.
5832 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5833 if (isParameter && FINode) {
5834 // Byval parameter. We have a frame index at this point.
5835 SDV =
5836 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5837 /*IsIndirect*/ true, dl, SDNodeOrder);
5838 } else if (isa<Argument>(Address)) {
5839 // Address is an argument, so try to emit its dbg value using
5840 // virtual register info from the FuncInfo.ValueMap.
5841 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5842 return;
5843 } else {
5844 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5845 true, dl, SDNodeOrder);
5847 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5848 } else {
5849 // If Address is an argument then try to emit its dbg value using
5850 // virtual register info from the FuncInfo.ValueMap.
5851 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5852 N)) {
5853 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5856 return;
5858 case Intrinsic::dbg_label: {
5859 const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5860 DILabel *Label = DI.getLabel();
5861 assert(Label && "Missing label");
5863 SDDbgLabel *SDV;
5864 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5865 DAG.AddDbgLabel(SDV);
5866 return;
5868 case Intrinsic::dbg_value: {
5869 const DbgValueInst &DI = cast<DbgValueInst>(I);
5870 assert(DI.getVariable() && "Missing variable");
5872 DILocalVariable *Variable = DI.getVariable();
5873 DIExpression *Expression = DI.getExpression();
5874 dropDanglingDebugInfo(Variable, Expression);
5875 const Value *V = DI.getValue();
5876 if (!V)
5877 return;
5879 if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5880 SDNodeOrder))
5881 return;
5883 // TODO: Dangling debug info will eventually either be resolved or produce
5884 // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5885 // between the original dbg.value location and its resolved DBG_VALUE, which
5886 // we should ideally fill with an extra Undef DBG_VALUE.
5888 DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5889 return;
5892 case Intrinsic::eh_typeid_for: {
5893 // Find the type id for the given typeinfo.
5894 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5895 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5896 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5897 setValue(&I, Res);
5898 return;
5901 case Intrinsic::eh_return_i32:
5902 case Intrinsic::eh_return_i64:
5903 DAG.getMachineFunction().setCallsEHReturn(true);
5904 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5905 MVT::Other,
5906 getControlRoot(),
5907 getValue(I.getArgOperand(0)),
5908 getValue(I.getArgOperand(1))));
5909 return;
5910 case Intrinsic::eh_unwind_init:
5911 DAG.getMachineFunction().setCallsUnwindInit(true);
5912 return;
5913 case Intrinsic::eh_dwarf_cfa:
5914 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5915 TLI.getPointerTy(DAG.getDataLayout()),
5916 getValue(I.getArgOperand(0))));
5917 return;
5918 case Intrinsic::eh_sjlj_callsite: {
5919 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5920 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5921 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5922 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5924 MMI.setCurrentCallSite(CI->getZExtValue());
5925 return;
5927 case Intrinsic::eh_sjlj_functioncontext: {
5928 // Get and store the index of the function context.
5929 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5930 AllocaInst *FnCtx =
5931 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5932 int FI = FuncInfo.StaticAllocaMap[FnCtx];
5933 MFI.setFunctionContextIndex(FI);
5934 return;
5936 case Intrinsic::eh_sjlj_setjmp: {
5937 SDValue Ops[2];
5938 Ops[0] = getRoot();
5939 Ops[1] = getValue(I.getArgOperand(0));
5940 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5941 DAG.getVTList(MVT::i32, MVT::Other), Ops);
5942 setValue(&I, Op.getValue(0));
5943 DAG.setRoot(Op.getValue(1));
5944 return;
5946 case Intrinsic::eh_sjlj_longjmp:
5947 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5948 getRoot(), getValue(I.getArgOperand(0))));
5949 return;
5950 case Intrinsic::eh_sjlj_setup_dispatch:
5951 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5952 getRoot()));
5953 return;
5954 case Intrinsic::masked_gather:
5955 visitMaskedGather(I);
5956 return;
5957 case Intrinsic::masked_load:
5958 visitMaskedLoad(I);
5959 return;
5960 case Intrinsic::masked_scatter:
5961 visitMaskedScatter(I);
5962 return;
5963 case Intrinsic::masked_store:
5964 visitMaskedStore(I);
5965 return;
5966 case Intrinsic::masked_expandload:
5967 visitMaskedLoad(I, true /* IsExpanding */);
5968 return;
5969 case Intrinsic::masked_compressstore:
5970 visitMaskedStore(I, true /* IsCompressing */);
5971 return;
5972 case Intrinsic::powi:
5973 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5974 getValue(I.getArgOperand(1)), DAG));
5975 return;
5976 case Intrinsic::log:
5977 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5978 return;
5979 case Intrinsic::log2:
5980 setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5981 return;
5982 case Intrinsic::log10:
5983 setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5984 return;
5985 case Intrinsic::exp:
5986 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5987 return;
5988 case Intrinsic::exp2:
5989 setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5990 return;
5991 case Intrinsic::pow:
5992 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5993 getValue(I.getArgOperand(1)), DAG, TLI));
5994 return;
5995 case Intrinsic::sqrt:
5996 case Intrinsic::fabs:
5997 case Intrinsic::sin:
5998 case Intrinsic::cos:
5999 case Intrinsic::floor:
6000 case Intrinsic::ceil:
6001 case Intrinsic::trunc:
6002 case Intrinsic::rint:
6003 case Intrinsic::nearbyint:
6004 case Intrinsic::round:
6005 case Intrinsic::canonicalize: {
6006 unsigned Opcode;
6007 switch (Intrinsic) {
6008 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6009 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
6010 case Intrinsic::fabs: Opcode = ISD::FABS; break;
6011 case Intrinsic::sin: Opcode = ISD::FSIN; break;
6012 case Intrinsic::cos: Opcode = ISD::FCOS; break;
6013 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
6014 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
6015 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
6016 case Intrinsic::rint: Opcode = ISD::FRINT; break;
6017 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6018 case Intrinsic::round: Opcode = ISD::FROUND; break;
6019 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6022 setValue(&I, DAG.getNode(Opcode, sdl,
6023 getValue(I.getArgOperand(0)).getValueType(),
6024 getValue(I.getArgOperand(0))));
6025 return;
6027 case Intrinsic::lround:
6028 case Intrinsic::llround:
6029 case Intrinsic::lrint:
6030 case Intrinsic::llrint: {
6031 unsigned Opcode;
6032 switch (Intrinsic) {
6033 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6034 case Intrinsic::lround: Opcode = ISD::LROUND; break;
6035 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6036 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
6037 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
6040 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6041 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6042 getValue(I.getArgOperand(0))));
6043 return;
6045 case Intrinsic::minnum:
6046 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6047 getValue(I.getArgOperand(0)).getValueType(),
6048 getValue(I.getArgOperand(0)),
6049 getValue(I.getArgOperand(1))));
6050 return;
6051 case Intrinsic::maxnum:
6052 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6053 getValue(I.getArgOperand(0)).getValueType(),
6054 getValue(I.getArgOperand(0)),
6055 getValue(I.getArgOperand(1))));
6056 return;
6057 case Intrinsic::minimum:
6058 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6059 getValue(I.getArgOperand(0)).getValueType(),
6060 getValue(I.getArgOperand(0)),
6061 getValue(I.getArgOperand(1))));
6062 return;
6063 case Intrinsic::maximum:
6064 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6065 getValue(I.getArgOperand(0)).getValueType(),
6066 getValue(I.getArgOperand(0)),
6067 getValue(I.getArgOperand(1))));
6068 return;
6069 case Intrinsic::copysign:
6070 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6071 getValue(I.getArgOperand(0)).getValueType(),
6072 getValue(I.getArgOperand(0)),
6073 getValue(I.getArgOperand(1))));
6074 return;
6075 case Intrinsic::fma:
6076 setValue(&I, DAG.getNode(ISD::FMA, sdl,
6077 getValue(I.getArgOperand(0)).getValueType(),
6078 getValue(I.getArgOperand(0)),
6079 getValue(I.getArgOperand(1)),
6080 getValue(I.getArgOperand(2))));
6081 return;
6082 case Intrinsic::experimental_constrained_fadd:
6083 case Intrinsic::experimental_constrained_fsub:
6084 case Intrinsic::experimental_constrained_fmul:
6085 case Intrinsic::experimental_constrained_fdiv:
6086 case Intrinsic::experimental_constrained_frem:
6087 case Intrinsic::experimental_constrained_fma:
6088 case Intrinsic::experimental_constrained_fptosi:
6089 case Intrinsic::experimental_constrained_fptoui:
6090 case Intrinsic::experimental_constrained_fptrunc:
6091 case Intrinsic::experimental_constrained_fpext:
6092 case Intrinsic::experimental_constrained_sqrt:
6093 case Intrinsic::experimental_constrained_pow:
6094 case Intrinsic::experimental_constrained_powi:
6095 case Intrinsic::experimental_constrained_sin:
6096 case Intrinsic::experimental_constrained_cos:
6097 case Intrinsic::experimental_constrained_exp:
6098 case Intrinsic::experimental_constrained_exp2:
6099 case Intrinsic::experimental_constrained_log:
6100 case Intrinsic::experimental_constrained_log10:
6101 case Intrinsic::experimental_constrained_log2:
6102 case Intrinsic::experimental_constrained_rint:
6103 case Intrinsic::experimental_constrained_nearbyint:
6104 case Intrinsic::experimental_constrained_maxnum:
6105 case Intrinsic::experimental_constrained_minnum:
6106 case Intrinsic::experimental_constrained_ceil:
6107 case Intrinsic::experimental_constrained_floor:
6108 case Intrinsic::experimental_constrained_round:
6109 case Intrinsic::experimental_constrained_trunc:
6110 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6111 return;
6112 case Intrinsic::fmuladd: {
6113 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6114 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6115 TLI.isFMAFasterThanFMulAndFAdd(VT)) {
6116 setValue(&I, DAG.getNode(ISD::FMA, sdl,
6117 getValue(I.getArgOperand(0)).getValueType(),
6118 getValue(I.getArgOperand(0)),
6119 getValue(I.getArgOperand(1)),
6120 getValue(I.getArgOperand(2))));
6121 } else {
6122 // TODO: Intrinsic calls should have fast-math-flags.
6123 SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6124 getValue(I.getArgOperand(0)).getValueType(),
6125 getValue(I.getArgOperand(0)),
6126 getValue(I.getArgOperand(1)));
6127 SDValue Add = DAG.getNode(ISD::FADD, sdl,
6128 getValue(I.getArgOperand(0)).getValueType(),
6129 Mul,
6130 getValue(I.getArgOperand(2)));
6131 setValue(&I, Add);
6133 return;
6135 case Intrinsic::convert_to_fp16:
6136 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6137 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6138 getValue(I.getArgOperand(0)),
6139 DAG.getTargetConstant(0, sdl,
6140 MVT::i32))));
6141 return;
6142 case Intrinsic::convert_from_fp16:
6143 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6144 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6145 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6146 getValue(I.getArgOperand(0)))));
6147 return;
6148 case Intrinsic::pcmarker: {
6149 SDValue Tmp = getValue(I.getArgOperand(0));
6150 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6151 return;
6153 case Intrinsic::readcyclecounter: {
6154 SDValue Op = getRoot();
6155 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6156 DAG.getVTList(MVT::i64, MVT::Other), Op);
6157 setValue(&I, Res);
6158 DAG.setRoot(Res.getValue(1));
6159 return;
6161 case Intrinsic::bitreverse:
6162 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6163 getValue(I.getArgOperand(0)).getValueType(),
6164 getValue(I.getArgOperand(0))));
6165 return;
6166 case Intrinsic::bswap:
6167 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6168 getValue(I.getArgOperand(0)).getValueType(),
6169 getValue(I.getArgOperand(0))));
6170 return;
6171 case Intrinsic::cttz: {
6172 SDValue Arg = getValue(I.getArgOperand(0));
6173 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6174 EVT Ty = Arg.getValueType();
6175 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6176 sdl, Ty, Arg));
6177 return;
6179 case Intrinsic::ctlz: {
6180 SDValue Arg = getValue(I.getArgOperand(0));
6181 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6182 EVT Ty = Arg.getValueType();
6183 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6184 sdl, Ty, Arg));
6185 return;
6187 case Intrinsic::ctpop: {
6188 SDValue Arg = getValue(I.getArgOperand(0));
6189 EVT Ty = Arg.getValueType();
6190 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6191 return;
6193 case Intrinsic::fshl:
6194 case Intrinsic::fshr: {
6195 bool IsFSHL = Intrinsic == Intrinsic::fshl;
6196 SDValue X = getValue(I.getArgOperand(0));
6197 SDValue Y = getValue(I.getArgOperand(1));
6198 SDValue Z = getValue(I.getArgOperand(2));
6199 EVT VT = X.getValueType();
6200 SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6201 SDValue Zero = DAG.getConstant(0, sdl, VT);
6202 SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6204 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6205 if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6206 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6207 return;
6210 // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6211 // avoid the select that is necessary in the general case to filter out
6212 // the 0-shift possibility that leads to UB.
6213 if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6214 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6215 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6216 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6217 return;
6220 // Some targets only rotate one way. Try the opposite direction.
6221 RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6222 if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6223 // Negate the shift amount because it is safe to ignore the high bits.
6224 SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6225 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6226 return;
6229 // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6230 // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6231 SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6232 SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6233 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6234 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6235 setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6236 return;
6239 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6240 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6241 SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6242 SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6243 SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6244 SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6246 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6247 // and that is undefined. We must compare and select to avoid UB.
6248 EVT CCVT = MVT::i1;
6249 if (VT.isVector())
6250 CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6252 // For fshl, 0-shift returns the 1st arg (X).
6253 // For fshr, 0-shift returns the 2nd arg (Y).
6254 SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6255 setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6256 return;
6258 case Intrinsic::sadd_sat: {
6259 SDValue Op1 = getValue(I.getArgOperand(0));
6260 SDValue Op2 = getValue(I.getArgOperand(1));
6261 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6262 return;
6264 case Intrinsic::uadd_sat: {
6265 SDValue Op1 = getValue(I.getArgOperand(0));
6266 SDValue Op2 = getValue(I.getArgOperand(1));
6267 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6268 return;
6270 case Intrinsic::ssub_sat: {
6271 SDValue Op1 = getValue(I.getArgOperand(0));
6272 SDValue Op2 = getValue(I.getArgOperand(1));
6273 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6274 return;
6276 case Intrinsic::usub_sat: {
6277 SDValue Op1 = getValue(I.getArgOperand(0));
6278 SDValue Op2 = getValue(I.getArgOperand(1));
6279 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6280 return;
6282 case Intrinsic::smul_fix:
6283 case Intrinsic::umul_fix: {
6284 SDValue Op1 = getValue(I.getArgOperand(0));
6285 SDValue Op2 = getValue(I.getArgOperand(1));
6286 SDValue Op3 = getValue(I.getArgOperand(2));
6287 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6288 Op1.getValueType(), Op1, Op2, Op3));
6289 return;
6291 case Intrinsic::smul_fix_sat: {
6292 SDValue Op1 = getValue(I.getArgOperand(0));
6293 SDValue Op2 = getValue(I.getArgOperand(1));
6294 SDValue Op3 = getValue(I.getArgOperand(2));
6295 setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6296 Op3));
6297 return;
6299 case Intrinsic::umul_fix_sat: {
6300 SDValue Op1 = getValue(I.getArgOperand(0));
6301 SDValue Op2 = getValue(I.getArgOperand(1));
6302 SDValue Op3 = getValue(I.getArgOperand(2));
6303 setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6304 Op3));
6305 return;
6307 case Intrinsic::stacksave: {
6308 SDValue Op = getRoot();
6309 Res = DAG.getNode(
6310 ISD::STACKSAVE, sdl,
6311 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6312 setValue(&I, Res);
6313 DAG.setRoot(Res.getValue(1));
6314 return;
6316 case Intrinsic::stackrestore:
6317 Res = getValue(I.getArgOperand(0));
6318 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6319 return;
6320 case Intrinsic::get_dynamic_area_offset: {
6321 SDValue Op = getRoot();
6322 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6323 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6324 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6325 // target.
6326 if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6327 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6328 " intrinsic!");
6329 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6330 Op);
6331 DAG.setRoot(Op);
6332 setValue(&I, Res);
6333 return;
6335 case Intrinsic::stackguard: {
6336 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6337 MachineFunction &MF = DAG.getMachineFunction();
6338 const Module &M = *MF.getFunction().getParent();
6339 SDValue Chain = getRoot();
6340 if (TLI.useLoadStackGuardNode()) {
6341 Res = getLoadStackGuard(DAG, sdl, Chain);
6342 } else {
6343 const Value *Global = TLI.getSDagStackGuard(M);
6344 unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6345 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6346 MachinePointerInfo(Global, 0), Align,
6347 MachineMemOperand::MOVolatile);
6349 if (TLI.useStackGuardXorFP())
6350 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6351 DAG.setRoot(Chain);
6352 setValue(&I, Res);
6353 return;
6355 case Intrinsic::stackprotector: {
6356 // Emit code into the DAG to store the stack guard onto the stack.
6357 MachineFunction &MF = DAG.getMachineFunction();
6358 MachineFrameInfo &MFI = MF.getFrameInfo();
6359 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6360 SDValue Src, Chain = getRoot();
6362 if (TLI.useLoadStackGuardNode())
6363 Src = getLoadStackGuard(DAG, sdl, Chain);
6364 else
6365 Src = getValue(I.getArgOperand(0)); // The guard's value.
6367 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6369 int FI = FuncInfo.StaticAllocaMap[Slot];
6370 MFI.setStackProtectorIndex(FI);
6372 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6374 // Store the stack protector onto the stack.
6375 Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6376 DAG.getMachineFunction(), FI),
6377 /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6378 setValue(&I, Res);
6379 DAG.setRoot(Res);
6380 return;
6382 case Intrinsic::objectsize: {
6383 // If we don't know by now, we're never going to know.
6384 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6386 assert(CI && "Non-constant type in __builtin_object_size?");
6388 SDValue Arg = getValue(I.getCalledValue());
6389 EVT Ty = Arg.getValueType();
6391 if (CI->isZero())
6392 Res = DAG.getConstant(-1ULL, sdl, Ty);
6393 else
6394 Res = DAG.getConstant(0, sdl, Ty);
6396 setValue(&I, Res);
6397 return;
6400 case Intrinsic::is_constant:
6401 // If this wasn't constant-folded away by now, then it's not a
6402 // constant.
6403 setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6404 return;
6406 case Intrinsic::annotation:
6407 case Intrinsic::ptr_annotation:
6408 case Intrinsic::launder_invariant_group:
6409 case Intrinsic::strip_invariant_group:
6410 // Drop the intrinsic, but forward the value
6411 setValue(&I, getValue(I.getOperand(0)));
6412 return;
6413 case Intrinsic::assume:
6414 case Intrinsic::var_annotation:
6415 case Intrinsic::sideeffect:
6416 // Discard annotate attributes, assumptions, and artificial side-effects.
6417 return;
6419 case Intrinsic::codeview_annotation: {
6420 // Emit a label associated with this metadata.
6421 MachineFunction &MF = DAG.getMachineFunction();
6422 MCSymbol *Label =
6423 MF.getMMI().getContext().createTempSymbol("annotation", true);
6424 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6425 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6426 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6427 DAG.setRoot(Res);
6428 return;
6431 case Intrinsic::init_trampoline: {
6432 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6434 SDValue Ops[6];
6435 Ops[0] = getRoot();
6436 Ops[1] = getValue(I.getArgOperand(0));
6437 Ops[2] = getValue(I.getArgOperand(1));
6438 Ops[3] = getValue(I.getArgOperand(2));
6439 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6440 Ops[5] = DAG.getSrcValue(F);
6442 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6444 DAG.setRoot(Res);
6445 return;
6447 case Intrinsic::adjust_trampoline:
6448 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6449 TLI.getPointerTy(DAG.getDataLayout()),
6450 getValue(I.getArgOperand(0))));
6451 return;
6452 case Intrinsic::gcroot: {
6453 assert(DAG.getMachineFunction().getFunction().hasGC() &&
6454 "only valid in functions with gc specified, enforced by Verifier");
6455 assert(GFI && "implied by previous");
6456 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6457 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6459 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6460 GFI->addStackRoot(FI->getIndex(), TypeMap);
6461 return;
6463 case Intrinsic::gcread:
6464 case Intrinsic::gcwrite:
6465 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6466 case Intrinsic::flt_rounds:
6467 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6468 return;
6470 case Intrinsic::expect:
6471 // Just replace __builtin_expect(exp, c) with EXP.
6472 setValue(&I, getValue(I.getArgOperand(0)));
6473 return;
6475 case Intrinsic::debugtrap:
6476 case Intrinsic::trap: {
6477 StringRef TrapFuncName =
6478 I.getAttributes()
6479 .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6480 .getValueAsString();
6481 if (TrapFuncName.empty()) {
6482 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6483 ISD::TRAP : ISD::DEBUGTRAP;
6484 DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6485 return;
6487 TargetLowering::ArgListTy Args;
6489 TargetLowering::CallLoweringInfo CLI(DAG);
6490 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6491 CallingConv::C, I.getType(),
6492 DAG.getExternalSymbol(TrapFuncName.data(),
6493 TLI.getPointerTy(DAG.getDataLayout())),
6494 std::move(Args));
6496 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6497 DAG.setRoot(Result.second);
6498 return;
6501 case Intrinsic::uadd_with_overflow:
6502 case Intrinsic::sadd_with_overflow:
6503 case Intrinsic::usub_with_overflow:
6504 case Intrinsic::ssub_with_overflow:
6505 case Intrinsic::umul_with_overflow:
6506 case Intrinsic::smul_with_overflow: {
6507 ISD::NodeType Op;
6508 switch (Intrinsic) {
6509 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6510 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6511 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6512 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6513 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6514 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6515 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6517 SDValue Op1 = getValue(I.getArgOperand(0));
6518 SDValue Op2 = getValue(I.getArgOperand(1));
6520 EVT ResultVT = Op1.getValueType();
6521 EVT OverflowVT = MVT::i1;
6522 if (ResultVT.isVector())
6523 OverflowVT = EVT::getVectorVT(
6524 *Context, OverflowVT, ResultVT.getVectorNumElements());
6526 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6527 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6528 return;
6530 case Intrinsic::prefetch: {
6531 SDValue Ops[5];
6532 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6533 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6534 Ops[0] = DAG.getRoot();
6535 Ops[1] = getValue(I.getArgOperand(0));
6536 Ops[2] = getValue(I.getArgOperand(1));
6537 Ops[3] = getValue(I.getArgOperand(2));
6538 Ops[4] = getValue(I.getArgOperand(3));
6539 SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6540 DAG.getVTList(MVT::Other), Ops,
6541 EVT::getIntegerVT(*Context, 8),
6542 MachinePointerInfo(I.getArgOperand(0)),
6543 0, /* align */
6544 Flags);
6546 // Chain the prefetch in parallell with any pending loads, to stay out of
6547 // the way of later optimizations.
6548 PendingLoads.push_back(Result);
6549 Result = getRoot();
6550 DAG.setRoot(Result);
6551 return;
6553 case Intrinsic::lifetime_start:
6554 case Intrinsic::lifetime_end: {
6555 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6556 // Stack coloring is not enabled in O0, discard region information.
6557 if (TM.getOptLevel() == CodeGenOpt::None)
6558 return;
6560 const int64_t ObjectSize =
6561 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6562 Value *const ObjectPtr = I.getArgOperand(1);
6563 SmallVector<const Value *, 4> Allocas;
6564 GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6566 for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6567 E = Allocas.end(); Object != E; ++Object) {
6568 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6570 // Could not find an Alloca.
6571 if (!LifetimeObject)
6572 continue;
6574 // First check that the Alloca is static, otherwise it won't have a
6575 // valid frame index.
6576 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6577 if (SI == FuncInfo.StaticAllocaMap.end())
6578 return;
6580 const int FrameIndex = SI->second;
6581 int64_t Offset;
6582 if (GetPointerBaseWithConstantOffset(
6583 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6584 Offset = -1; // Cannot determine offset from alloca to lifetime object.
6585 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6586 Offset);
6587 DAG.setRoot(Res);
6589 return;
6591 case Intrinsic::invariant_start:
6592 // Discard region information.
6593 setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6594 return;
6595 case Intrinsic::invariant_end:
6596 // Discard region information.
6597 return;
6598 case Intrinsic::clear_cache:
6599 /// FunctionName may be null.
6600 if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6601 lowerCallToExternalSymbol(I, FunctionName);
6602 return;
6603 case Intrinsic::donothing:
6604 // ignore
6605 return;
6606 case Intrinsic::experimental_stackmap:
6607 visitStackmap(I);
6608 return;
6609 case Intrinsic::experimental_patchpoint_void:
6610 case Intrinsic::experimental_patchpoint_i64:
6611 visitPatchpoint(&I);
6612 return;
6613 case Intrinsic::experimental_gc_statepoint:
6614 LowerStatepoint(ImmutableStatepoint(&I));
6615 return;
6616 case Intrinsic::experimental_gc_result:
6617 visitGCResult(cast<GCResultInst>(I));
6618 return;
6619 case Intrinsic::experimental_gc_relocate:
6620 visitGCRelocate(cast<GCRelocateInst>(I));
6621 return;
6622 case Intrinsic::instrprof_increment:
6623 llvm_unreachable("instrprof failed to lower an increment");
6624 case Intrinsic::instrprof_value_profile:
6625 llvm_unreachable("instrprof failed to lower a value profiling call");
6626 case Intrinsic::localescape: {
6627 MachineFunction &MF = DAG.getMachineFunction();
6628 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6630 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6631 // is the same on all targets.
6632 for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6633 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6634 if (isa<ConstantPointerNull>(Arg))
6635 continue; // Skip null pointers. They represent a hole in index space.
6636 AllocaInst *Slot = cast<AllocaInst>(Arg);
6637 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6638 "can only escape static allocas");
6639 int FI = FuncInfo.StaticAllocaMap[Slot];
6640 MCSymbol *FrameAllocSym =
6641 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6642 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6643 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6644 TII->get(TargetOpcode::LOCAL_ESCAPE))
6645 .addSym(FrameAllocSym)
6646 .addFrameIndex(FI);
6649 return;
6652 case Intrinsic::localrecover: {
6653 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6654 MachineFunction &MF = DAG.getMachineFunction();
6655 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6657 // Get the symbol that defines the frame offset.
6658 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6659 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6660 unsigned IdxVal =
6661 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6662 MCSymbol *FrameAllocSym =
6663 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6664 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6666 // Create a MCSymbol for the label to avoid any target lowering
6667 // that would make this PC relative.
6668 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6669 SDValue OffsetVal =
6670 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6672 // Add the offset to the FP.
6673 Value *FP = I.getArgOperand(1);
6674 SDValue FPVal = getValue(FP);
6675 SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6676 setValue(&I, Add);
6678 return;
6681 case Intrinsic::eh_exceptionpointer:
6682 case Intrinsic::eh_exceptioncode: {
6683 // Get the exception pointer vreg, copy from it, and resize it to fit.
6684 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6685 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6686 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6687 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6688 SDValue N =
6689 DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6690 if (Intrinsic == Intrinsic::eh_exceptioncode)
6691 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6692 setValue(&I, N);
6693 return;
6695 case Intrinsic::xray_customevent: {
6696 // Here we want to make sure that the intrinsic behaves as if it has a
6697 // specific calling convention, and only for x86_64.
6698 // FIXME: Support other platforms later.
6699 const auto &Triple = DAG.getTarget().getTargetTriple();
6700 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6701 return;
6703 SDLoc DL = getCurSDLoc();
6704 SmallVector<SDValue, 8> Ops;
6706 // We want to say that we always want the arguments in registers.
6707 SDValue LogEntryVal = getValue(I.getArgOperand(0));
6708 SDValue StrSizeVal = getValue(I.getArgOperand(1));
6709 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6710 SDValue Chain = getRoot();
6711 Ops.push_back(LogEntryVal);
6712 Ops.push_back(StrSizeVal);
6713 Ops.push_back(Chain);
6715 // We need to enforce the calling convention for the callsite, so that
6716 // argument ordering is enforced correctly, and that register allocation can
6717 // see that some registers may be assumed clobbered and have to preserve
6718 // them across calls to the intrinsic.
6719 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6720 DL, NodeTys, Ops);
6721 SDValue patchableNode = SDValue(MN, 0);
6722 DAG.setRoot(patchableNode);
6723 setValue(&I, patchableNode);
6724 return;
6726 case Intrinsic::xray_typedevent: {
6727 // Here we want to make sure that the intrinsic behaves as if it has a
6728 // specific calling convention, and only for x86_64.
6729 // FIXME: Support other platforms later.
6730 const auto &Triple = DAG.getTarget().getTargetTriple();
6731 if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6732 return;
6734 SDLoc DL = getCurSDLoc();
6735 SmallVector<SDValue, 8> Ops;
6737 // We want to say that we always want the arguments in registers.
6738 // It's unclear to me how manipulating the selection DAG here forces callers
6739 // to provide arguments in registers instead of on the stack.
6740 SDValue LogTypeId = getValue(I.getArgOperand(0));
6741 SDValue LogEntryVal = getValue(I.getArgOperand(1));
6742 SDValue StrSizeVal = getValue(I.getArgOperand(2));
6743 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6744 SDValue Chain = getRoot();
6745 Ops.push_back(LogTypeId);
6746 Ops.push_back(LogEntryVal);
6747 Ops.push_back(StrSizeVal);
6748 Ops.push_back(Chain);
6750 // We need to enforce the calling convention for the callsite, so that
6751 // argument ordering is enforced correctly, and that register allocation can
6752 // see that some registers may be assumed clobbered and have to preserve
6753 // them across calls to the intrinsic.
6754 MachineSDNode *MN = DAG.getMachineNode(
6755 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6756 SDValue patchableNode = SDValue(MN, 0);
6757 DAG.setRoot(patchableNode);
6758 setValue(&I, patchableNode);
6759 return;
6761 case Intrinsic::experimental_deoptimize:
6762 LowerDeoptimizeCall(&I);
6763 return;
6765 case Intrinsic::experimental_vector_reduce_v2_fadd:
6766 case Intrinsic::experimental_vector_reduce_v2_fmul:
6767 case Intrinsic::experimental_vector_reduce_add:
6768 case Intrinsic::experimental_vector_reduce_mul:
6769 case Intrinsic::experimental_vector_reduce_and:
6770 case Intrinsic::experimental_vector_reduce_or:
6771 case Intrinsic::experimental_vector_reduce_xor:
6772 case Intrinsic::experimental_vector_reduce_smax:
6773 case Intrinsic::experimental_vector_reduce_smin:
6774 case Intrinsic::experimental_vector_reduce_umax:
6775 case Intrinsic::experimental_vector_reduce_umin:
6776 case Intrinsic::experimental_vector_reduce_fmax:
6777 case Intrinsic::experimental_vector_reduce_fmin:
6778 visitVectorReduce(I, Intrinsic);
6779 return;
6781 case Intrinsic::icall_branch_funnel: {
6782 SmallVector<SDValue, 16> Ops;
6783 Ops.push_back(getValue(I.getArgOperand(0)));
6785 int64_t Offset;
6786 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6787 I.getArgOperand(1), Offset, DAG.getDataLayout()));
6788 if (!Base)
6789 report_fatal_error(
6790 "llvm.icall.branch.funnel operand must be a GlobalValue");
6791 Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6793 struct BranchFunnelTarget {
6794 int64_t Offset;
6795 SDValue Target;
6797 SmallVector<BranchFunnelTarget, 8> Targets;
6799 for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6800 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6801 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6802 if (ElemBase != Base)
6803 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6804 "to the same GlobalValue");
6806 SDValue Val = getValue(I.getArgOperand(Op + 1));
6807 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6808 if (!GA)
6809 report_fatal_error(
6810 "llvm.icall.branch.funnel operand must be a GlobalValue");
6811 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6812 GA->getGlobal(), getCurSDLoc(),
6813 Val.getValueType(), GA->getOffset())});
6815 llvm::sort(Targets,
6816 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6817 return T1.Offset < T2.Offset;
6820 for (auto &T : Targets) {
6821 Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6822 Ops.push_back(T.Target);
6825 Ops.push_back(DAG.getRoot()); // Chain
6826 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6827 getCurSDLoc(), MVT::Other, Ops),
6829 DAG.setRoot(N);
6830 setValue(&I, N);
6831 HasTailCall = true;
6832 return;
6835 case Intrinsic::wasm_landingpad_index:
6836 // Information this intrinsic contained has been transferred to
6837 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6838 // delete it now.
6839 return;
6841 case Intrinsic::aarch64_settag:
6842 case Intrinsic::aarch64_settag_zero: {
6843 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6844 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6845 SDValue Val = TSI.EmitTargetCodeForSetTag(
6846 DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6847 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6848 ZeroMemory);
6849 DAG.setRoot(Val);
6850 setValue(&I, Val);
6851 return;
6853 case Intrinsic::ptrmask: {
6854 SDValue Ptr = getValue(I.getOperand(0));
6855 SDValue Const = getValue(I.getOperand(1));
6857 EVT DestVT =
6858 EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6860 setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6861 DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6862 return;
6867 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6868 const ConstrainedFPIntrinsic &FPI) {
6869 SDLoc sdl = getCurSDLoc();
6870 unsigned Opcode;
6871 switch (FPI.getIntrinsicID()) {
6872 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6873 case Intrinsic::experimental_constrained_fadd:
6874 Opcode = ISD::STRICT_FADD;
6875 break;
6876 case Intrinsic::experimental_constrained_fsub:
6877 Opcode = ISD::STRICT_FSUB;
6878 break;
6879 case Intrinsic::experimental_constrained_fmul:
6880 Opcode = ISD::STRICT_FMUL;
6881 break;
6882 case Intrinsic::experimental_constrained_fdiv:
6883 Opcode = ISD::STRICT_FDIV;
6884 break;
6885 case Intrinsic::experimental_constrained_frem:
6886 Opcode = ISD::STRICT_FREM;
6887 break;
6888 case Intrinsic::experimental_constrained_fma:
6889 Opcode = ISD::STRICT_FMA;
6890 break;
6891 case Intrinsic::experimental_constrained_fptosi:
6892 Opcode = ISD::STRICT_FP_TO_SINT;
6893 break;
6894 case Intrinsic::experimental_constrained_fptoui:
6895 Opcode = ISD::STRICT_FP_TO_UINT;
6896 break;
6897 case Intrinsic::experimental_constrained_fptrunc:
6898 Opcode = ISD::STRICT_FP_ROUND;
6899 break;
6900 case Intrinsic::experimental_constrained_fpext:
6901 Opcode = ISD::STRICT_FP_EXTEND;
6902 break;
6903 case Intrinsic::experimental_constrained_sqrt:
6904 Opcode = ISD::STRICT_FSQRT;
6905 break;
6906 case Intrinsic::experimental_constrained_pow:
6907 Opcode = ISD::STRICT_FPOW;
6908 break;
6909 case Intrinsic::experimental_constrained_powi:
6910 Opcode = ISD::STRICT_FPOWI;
6911 break;
6912 case Intrinsic::experimental_constrained_sin:
6913 Opcode = ISD::STRICT_FSIN;
6914 break;
6915 case Intrinsic::experimental_constrained_cos:
6916 Opcode = ISD::STRICT_FCOS;
6917 break;
6918 case Intrinsic::experimental_constrained_exp:
6919 Opcode = ISD::STRICT_FEXP;
6920 break;
6921 case Intrinsic::experimental_constrained_exp2:
6922 Opcode = ISD::STRICT_FEXP2;
6923 break;
6924 case Intrinsic::experimental_constrained_log:
6925 Opcode = ISD::STRICT_FLOG;
6926 break;
6927 case Intrinsic::experimental_constrained_log10:
6928 Opcode = ISD::STRICT_FLOG10;
6929 break;
6930 case Intrinsic::experimental_constrained_log2:
6931 Opcode = ISD::STRICT_FLOG2;
6932 break;
6933 case Intrinsic::experimental_constrained_rint:
6934 Opcode = ISD::STRICT_FRINT;
6935 break;
6936 case Intrinsic::experimental_constrained_nearbyint:
6937 Opcode = ISD::STRICT_FNEARBYINT;
6938 break;
6939 case Intrinsic::experimental_constrained_maxnum:
6940 Opcode = ISD::STRICT_FMAXNUM;
6941 break;
6942 case Intrinsic::experimental_constrained_minnum:
6943 Opcode = ISD::STRICT_FMINNUM;
6944 break;
6945 case Intrinsic::experimental_constrained_ceil:
6946 Opcode = ISD::STRICT_FCEIL;
6947 break;
6948 case Intrinsic::experimental_constrained_floor:
6949 Opcode = ISD::STRICT_FFLOOR;
6950 break;
6951 case Intrinsic::experimental_constrained_round:
6952 Opcode = ISD::STRICT_FROUND;
6953 break;
6954 case Intrinsic::experimental_constrained_trunc:
6955 Opcode = ISD::STRICT_FTRUNC;
6956 break;
6958 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6959 SDValue Chain = getRoot();
6960 SmallVector<EVT, 4> ValueVTs;
6961 ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6962 ValueVTs.push_back(MVT::Other); // Out chain
6964 SDVTList VTs = DAG.getVTList(ValueVTs);
6965 SDValue Result;
6966 if (Opcode == ISD::STRICT_FP_ROUND)
6967 Result = DAG.getNode(Opcode, sdl, VTs,
6968 { Chain, getValue(FPI.getArgOperand(0)),
6969 DAG.getTargetConstant(0, sdl,
6970 TLI.getPointerTy(DAG.getDataLayout())) });
6971 else if (FPI.isUnaryOp())
6972 Result = DAG.getNode(Opcode, sdl, VTs,
6973 { Chain, getValue(FPI.getArgOperand(0)) });
6974 else if (FPI.isTernaryOp())
6975 Result = DAG.getNode(Opcode, sdl, VTs,
6976 { Chain, getValue(FPI.getArgOperand(0)),
6977 getValue(FPI.getArgOperand(1)),
6978 getValue(FPI.getArgOperand(2)) });
6979 else
6980 Result = DAG.getNode(Opcode, sdl, VTs,
6981 { Chain, getValue(FPI.getArgOperand(0)),
6982 getValue(FPI.getArgOperand(1)) });
6984 if (FPI.getExceptionBehavior() !=
6985 ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) {
6986 SDNodeFlags Flags;
6987 Flags.setFPExcept(true);
6988 Result->setFlags(Flags);
6991 assert(Result.getNode()->getNumValues() == 2);
6992 SDValue OutChain = Result.getValue(1);
6993 DAG.setRoot(OutChain);
6994 SDValue FPResult = Result.getValue(0);
6995 setValue(&FPI, FPResult);
6998 std::pair<SDValue, SDValue>
6999 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7000 const BasicBlock *EHPadBB) {
7001 MachineFunction &MF = DAG.getMachineFunction();
7002 MachineModuleInfo &MMI = MF.getMMI();
7003 MCSymbol *BeginLabel = nullptr;
7005 if (EHPadBB) {
7006 // Insert a label before the invoke call to mark the try range. This can be
7007 // used to detect deletion of the invoke via the MachineModuleInfo.
7008 BeginLabel = MMI.getContext().createTempSymbol();
7010 // For SjLj, keep track of which landing pads go with which invokes
7011 // so as to maintain the ordering of pads in the LSDA.
7012 unsigned CallSiteIndex = MMI.getCurrentCallSite();
7013 if (CallSiteIndex) {
7014 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7015 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7017 // Now that the call site is handled, stop tracking it.
7018 MMI.setCurrentCallSite(0);
7021 // Both PendingLoads and PendingExports must be flushed here;
7022 // this call might not return.
7023 (void)getRoot();
7024 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7026 CLI.setChain(getRoot());
7028 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7029 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7031 assert((CLI.IsTailCall || Result.second.getNode()) &&
7032 "Non-null chain expected with non-tail call!");
7033 assert((Result.second.getNode() || !Result.first.getNode()) &&
7034 "Null value expected with tail call!");
7036 if (!Result.second.getNode()) {
7037 // As a special case, a null chain means that a tail call has been emitted
7038 // and the DAG root is already updated.
7039 HasTailCall = true;
7041 // Since there's no actual continuation from this block, nothing can be
7042 // relying on us setting vregs for them.
7043 PendingExports.clear();
7044 } else {
7045 DAG.setRoot(Result.second);
7048 if (EHPadBB) {
7049 // Insert a label at the end of the invoke call to mark the try range. This
7050 // can be used to detect deletion of the invoke via the MachineModuleInfo.
7051 MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7052 DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7054 // Inform MachineModuleInfo of range.
7055 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7056 // There is a platform (e.g. wasm) that uses funclet style IR but does not
7057 // actually use outlined funclets and their LSDA info style.
7058 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7059 assert(CLI.CS);
7060 WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7061 EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7062 BeginLabel, EndLabel);
7063 } else if (!isScopedEHPersonality(Pers)) {
7064 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7068 return Result;
7071 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7072 bool isTailCall,
7073 const BasicBlock *EHPadBB) {
7074 auto &DL = DAG.getDataLayout();
7075 FunctionType *FTy = CS.getFunctionType();
7076 Type *RetTy = CS.getType();
7078 TargetLowering::ArgListTy Args;
7079 Args.reserve(CS.arg_size());
7081 const Value *SwiftErrorVal = nullptr;
7082 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7084 // We can't tail call inside a function with a swifterror argument. Lowering
7085 // does not support this yet. It would have to move into the swifterror
7086 // register before the call.
7087 auto *Caller = CS.getInstruction()->getParent()->getParent();
7088 if (TLI.supportSwiftError() &&
7089 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7090 isTailCall = false;
7092 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7093 i != e; ++i) {
7094 TargetLowering::ArgListEntry Entry;
7095 const Value *V = *i;
7097 // Skip empty types
7098 if (V->getType()->isEmptyTy())
7099 continue;
7101 SDValue ArgNode = getValue(V);
7102 Entry.Node = ArgNode; Entry.Ty = V->getType();
7104 Entry.setAttributes(&CS, i - CS.arg_begin());
7106 // Use swifterror virtual register as input to the call.
7107 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7108 SwiftErrorVal = V;
7109 // We find the virtual register for the actual swifterror argument.
7110 // Instead of using the Value, we use the virtual register instead.
7111 Entry.Node = DAG.getRegister(
7112 SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7113 EVT(TLI.getPointerTy(DL)));
7116 Args.push_back(Entry);
7118 // If we have an explicit sret argument that is an Instruction, (i.e., it
7119 // might point to function-local memory), we can't meaningfully tail-call.
7120 if (Entry.IsSRet && isa<Instruction>(V))
7121 isTailCall = false;
7124 // Check if target-independent constraints permit a tail call here.
7125 // Target-dependent constraints are checked within TLI->LowerCallTo.
7126 if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7127 isTailCall = false;
7129 // Disable tail calls if there is an swifterror argument. Targets have not
7130 // been updated to support tail calls.
7131 if (TLI.supportSwiftError() && SwiftErrorVal)
7132 isTailCall = false;
7134 TargetLowering::CallLoweringInfo CLI(DAG);
7135 CLI.setDebugLoc(getCurSDLoc())
7136 .setChain(getRoot())
7137 .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7138 .setTailCall(isTailCall)
7139 .setConvergent(CS.isConvergent());
7140 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7142 if (Result.first.getNode()) {
7143 const Instruction *Inst = CS.getInstruction();
7144 Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7145 setValue(Inst, Result.first);
7148 // The last element of CLI.InVals has the SDValue for swifterror return.
7149 // Here we copy it to a virtual register and update SwiftErrorMap for
7150 // book-keeping.
7151 if (SwiftErrorVal && TLI.supportSwiftError()) {
7152 // Get the last element of InVals.
7153 SDValue Src = CLI.InVals.back();
7154 Register VReg = SwiftError.getOrCreateVRegDefAt(
7155 CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7156 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7157 DAG.setRoot(CopyNode);
7161 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7162 SelectionDAGBuilder &Builder) {
7163 // Check to see if this load can be trivially constant folded, e.g. if the
7164 // input is from a string literal.
7165 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7166 // Cast pointer to the type we really want to load.
7167 Type *LoadTy =
7168 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7169 if (LoadVT.isVector())
7170 LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7172 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7173 PointerType::getUnqual(LoadTy));
7175 if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7176 const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7177 return Builder.getValue(LoadCst);
7180 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
7181 // still constant memory, the input chain can be the entry node.
7182 SDValue Root;
7183 bool ConstantMemory = false;
7185 // Do not serialize (non-volatile) loads of constant memory with anything.
7186 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7187 Root = Builder.DAG.getEntryNode();
7188 ConstantMemory = true;
7189 } else {
7190 // Do not serialize non-volatile loads against each other.
7191 Root = Builder.DAG.getRoot();
7194 SDValue Ptr = Builder.getValue(PtrVal);
7195 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7196 Ptr, MachinePointerInfo(PtrVal),
7197 /* Alignment = */ 1);
7199 if (!ConstantMemory)
7200 Builder.PendingLoads.push_back(LoadVal.getValue(1));
7201 return LoadVal;
7204 /// Record the value for an instruction that produces an integer result,
7205 /// converting the type where necessary.
7206 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7207 SDValue Value,
7208 bool IsSigned) {
7209 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7210 I.getType(), true);
7211 if (IsSigned)
7212 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7213 else
7214 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7215 setValue(&I, Value);
7218 /// See if we can lower a memcmp call into an optimized form. If so, return
7219 /// true and lower it. Otherwise return false, and it will be lowered like a
7220 /// normal call.
7221 /// The caller already checked that \p I calls the appropriate LibFunc with a
7222 /// correct prototype.
7223 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7224 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7225 const Value *Size = I.getArgOperand(2);
7226 const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7227 if (CSize && CSize->getZExtValue() == 0) {
7228 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7229 I.getType(), true);
7230 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7231 return true;
7234 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7235 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7236 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7237 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7238 if (Res.first.getNode()) {
7239 processIntegerCallValue(I, Res.first, true);
7240 PendingLoads.push_back(Res.second);
7241 return true;
7244 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
7245 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
7246 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7247 return false;
7249 // If the target has a fast compare for the given size, it will return a
7250 // preferred load type for that size. Require that the load VT is legal and
7251 // that the target supports unaligned loads of that type. Otherwise, return
7252 // INVALID.
7253 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7254 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7255 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7256 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7257 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7258 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7259 // TODO: Check alignment of src and dest ptrs.
7260 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7261 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7262 if (!TLI.isTypeLegal(LVT) ||
7263 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7264 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7265 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7268 return LVT;
7271 // This turns into unaligned loads. We only do this if the target natively
7272 // supports the MVT we'll be loading or if it is small enough (<= 4) that
7273 // we'll only produce a small number of byte loads.
7274 MVT LoadVT;
7275 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7276 switch (NumBitsToCompare) {
7277 default:
7278 return false;
7279 case 16:
7280 LoadVT = MVT::i16;
7281 break;
7282 case 32:
7283 LoadVT = MVT::i32;
7284 break;
7285 case 64:
7286 case 128:
7287 case 256:
7288 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7289 break;
7292 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7293 return false;
7295 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7296 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7298 // Bitcast to a wide integer type if the loads are vectors.
7299 if (LoadVT.isVector()) {
7300 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7301 LoadL = DAG.getBitcast(CmpVT, LoadL);
7302 LoadR = DAG.getBitcast(CmpVT, LoadR);
7305 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7306 processIntegerCallValue(I, Cmp, false);
7307 return true;
7310 /// See if we can lower a memchr call into an optimized form. If so, return
7311 /// true and lower it. Otherwise return false, and it will be lowered like a
7312 /// normal call.
7313 /// The caller already checked that \p I calls the appropriate LibFunc with a
7314 /// correct prototype.
7315 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7316 const Value *Src = I.getArgOperand(0);
7317 const Value *Char = I.getArgOperand(1);
7318 const Value *Length = I.getArgOperand(2);
7320 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7321 std::pair<SDValue, SDValue> Res =
7322 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7323 getValue(Src), getValue(Char), getValue(Length),
7324 MachinePointerInfo(Src));
7325 if (Res.first.getNode()) {
7326 setValue(&I, Res.first);
7327 PendingLoads.push_back(Res.second);
7328 return true;
7331 return false;
7334 /// See if we can lower a mempcpy call into an optimized form. If so, return
7335 /// true and lower it. Otherwise return false, and it will be lowered like a
7336 /// normal call.
7337 /// The caller already checked that \p I calls the appropriate LibFunc with a
7338 /// correct prototype.
7339 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7340 SDValue Dst = getValue(I.getArgOperand(0));
7341 SDValue Src = getValue(I.getArgOperand(1));
7342 SDValue Size = getValue(I.getArgOperand(2));
7344 unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7345 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7346 unsigned Align = std::min(DstAlign, SrcAlign);
7347 if (Align == 0) // Alignment of one or both could not be inferred.
7348 Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7350 bool isVol = false;
7351 SDLoc sdl = getCurSDLoc();
7353 // In the mempcpy context we need to pass in a false value for isTailCall
7354 // because the return pointer needs to be adjusted by the size of
7355 // the copied memory.
7356 SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7357 false, /*isTailCall=*/false,
7358 MachinePointerInfo(I.getArgOperand(0)),
7359 MachinePointerInfo(I.getArgOperand(1)));
7360 assert(MC.getNode() != nullptr &&
7361 "** memcpy should not be lowered as TailCall in mempcpy context **");
7362 DAG.setRoot(MC);
7364 // Check if Size needs to be truncated or extended.
7365 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7367 // Adjust return pointer to point just past the last dst byte.
7368 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7369 Dst, Size);
7370 setValue(&I, DstPlusSize);
7371 return true;
7374 /// See if we can lower a strcpy call into an optimized form. If so, return
7375 /// true and lower it, otherwise return false and it will be lowered like a
7376 /// normal call.
7377 /// The caller already checked that \p I calls the appropriate LibFunc with a
7378 /// correct prototype.
7379 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7380 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7382 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7383 std::pair<SDValue, SDValue> Res =
7384 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7385 getValue(Arg0), getValue(Arg1),
7386 MachinePointerInfo(Arg0),
7387 MachinePointerInfo(Arg1), isStpcpy);
7388 if (Res.first.getNode()) {
7389 setValue(&I, Res.first);
7390 DAG.setRoot(Res.second);
7391 return true;
7394 return false;
7397 /// See if we can lower a strcmp call into an optimized form. If so, return
7398 /// true and lower it, otherwise return false and it will be lowered like a
7399 /// normal call.
7400 /// The caller already checked that \p I calls the appropriate LibFunc with a
7401 /// correct prototype.
7402 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7403 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7405 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7406 std::pair<SDValue, SDValue> Res =
7407 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7408 getValue(Arg0), getValue(Arg1),
7409 MachinePointerInfo(Arg0),
7410 MachinePointerInfo(Arg1));
7411 if (Res.first.getNode()) {
7412 processIntegerCallValue(I, Res.first, true);
7413 PendingLoads.push_back(Res.second);
7414 return true;
7417 return false;
7420 /// See if we can lower a strlen call into an optimized form. If so, return
7421 /// true and lower it, otherwise return false and it will be lowered like a
7422 /// normal call.
7423 /// The caller already checked that \p I calls the appropriate LibFunc with a
7424 /// correct prototype.
7425 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7426 const Value *Arg0 = I.getArgOperand(0);
7428 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7429 std::pair<SDValue, SDValue> Res =
7430 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7431 getValue(Arg0), MachinePointerInfo(Arg0));
7432 if (Res.first.getNode()) {
7433 processIntegerCallValue(I, Res.first, false);
7434 PendingLoads.push_back(Res.second);
7435 return true;
7438 return false;
7441 /// See if we can lower a strnlen call into an optimized form. If so, return
7442 /// true and lower it, otherwise return false and it will be lowered like a
7443 /// normal call.
7444 /// The caller already checked that \p I calls the appropriate LibFunc with a
7445 /// correct prototype.
7446 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7447 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7449 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7450 std::pair<SDValue, SDValue> Res =
7451 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7452 getValue(Arg0), getValue(Arg1),
7453 MachinePointerInfo(Arg0));
7454 if (Res.first.getNode()) {
7455 processIntegerCallValue(I, Res.first, false);
7456 PendingLoads.push_back(Res.second);
7457 return true;
7460 return false;
7463 /// See if we can lower a unary floating-point operation into an SDNode with
7464 /// the specified Opcode. If so, return true and lower it, otherwise return
7465 /// false and it will be lowered like a normal call.
7466 /// The caller already checked that \p I calls the appropriate LibFunc with a
7467 /// correct prototype.
7468 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7469 unsigned Opcode) {
7470 // We already checked this call's prototype; verify it doesn't modify errno.
7471 if (!I.onlyReadsMemory())
7472 return false;
7474 SDValue Tmp = getValue(I.getArgOperand(0));
7475 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7476 return true;
7479 /// See if we can lower a binary floating-point operation into an SDNode with
7480 /// the specified Opcode. If so, return true and lower it. Otherwise return
7481 /// false, and it will be lowered like a normal call.
7482 /// The caller already checked that \p I calls the appropriate LibFunc with a
7483 /// correct prototype.
7484 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7485 unsigned Opcode) {
7486 // We already checked this call's prototype; verify it doesn't modify errno.
7487 if (!I.onlyReadsMemory())
7488 return false;
7490 SDValue Tmp0 = getValue(I.getArgOperand(0));
7491 SDValue Tmp1 = getValue(I.getArgOperand(1));
7492 EVT VT = Tmp0.getValueType();
7493 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7494 return true;
7497 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7498 // Handle inline assembly differently.
7499 if (isa<InlineAsm>(I.getCalledValue())) {
7500 visitInlineAsm(&I);
7501 return;
7504 if (Function *F = I.getCalledFunction()) {
7505 if (F->isDeclaration()) {
7506 // Is this an LLVM intrinsic or a target-specific intrinsic?
7507 unsigned IID = F->getIntrinsicID();
7508 if (!IID)
7509 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7510 IID = II->getIntrinsicID(F);
7512 if (IID) {
7513 visitIntrinsicCall(I, IID);
7514 return;
7518 // Check for well-known libc/libm calls. If the function is internal, it
7519 // can't be a library call. Don't do the check if marked as nobuiltin for
7520 // some reason or the call site requires strict floating point semantics.
7521 LibFunc Func;
7522 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7523 F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7524 LibInfo->hasOptimizedCodeGen(Func)) {
7525 switch (Func) {
7526 default: break;
7527 case LibFunc_copysign:
7528 case LibFunc_copysignf:
7529 case LibFunc_copysignl:
7530 // We already checked this call's prototype; verify it doesn't modify
7531 // errno.
7532 if (I.onlyReadsMemory()) {
7533 SDValue LHS = getValue(I.getArgOperand(0));
7534 SDValue RHS = getValue(I.getArgOperand(1));
7535 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7536 LHS.getValueType(), LHS, RHS));
7537 return;
7539 break;
7540 case LibFunc_fabs:
7541 case LibFunc_fabsf:
7542 case LibFunc_fabsl:
7543 if (visitUnaryFloatCall(I, ISD::FABS))
7544 return;
7545 break;
7546 case LibFunc_fmin:
7547 case LibFunc_fminf:
7548 case LibFunc_fminl:
7549 if (visitBinaryFloatCall(I, ISD::FMINNUM))
7550 return;
7551 break;
7552 case LibFunc_fmax:
7553 case LibFunc_fmaxf:
7554 case LibFunc_fmaxl:
7555 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7556 return;
7557 break;
7558 case LibFunc_sin:
7559 case LibFunc_sinf:
7560 case LibFunc_sinl:
7561 if (visitUnaryFloatCall(I, ISD::FSIN))
7562 return;
7563 break;
7564 case LibFunc_cos:
7565 case LibFunc_cosf:
7566 case LibFunc_cosl:
7567 if (visitUnaryFloatCall(I, ISD::FCOS))
7568 return;
7569 break;
7570 case LibFunc_sqrt:
7571 case LibFunc_sqrtf:
7572 case LibFunc_sqrtl:
7573 case LibFunc_sqrt_finite:
7574 case LibFunc_sqrtf_finite:
7575 case LibFunc_sqrtl_finite:
7576 if (visitUnaryFloatCall(I, ISD::FSQRT))
7577 return;
7578 break;
7579 case LibFunc_floor:
7580 case LibFunc_floorf:
7581 case LibFunc_floorl:
7582 if (visitUnaryFloatCall(I, ISD::FFLOOR))
7583 return;
7584 break;
7585 case LibFunc_nearbyint:
7586 case LibFunc_nearbyintf:
7587 case LibFunc_nearbyintl:
7588 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7589 return;
7590 break;
7591 case LibFunc_ceil:
7592 case LibFunc_ceilf:
7593 case LibFunc_ceill:
7594 if (visitUnaryFloatCall(I, ISD::FCEIL))
7595 return;
7596 break;
7597 case LibFunc_rint:
7598 case LibFunc_rintf:
7599 case LibFunc_rintl:
7600 if (visitUnaryFloatCall(I, ISD::FRINT))
7601 return;
7602 break;
7603 case LibFunc_round:
7604 case LibFunc_roundf:
7605 case LibFunc_roundl:
7606 if (visitUnaryFloatCall(I, ISD::FROUND))
7607 return;
7608 break;
7609 case LibFunc_trunc:
7610 case LibFunc_truncf:
7611 case LibFunc_truncl:
7612 if (visitUnaryFloatCall(I, ISD::FTRUNC))
7613 return;
7614 break;
7615 case LibFunc_log2:
7616 case LibFunc_log2f:
7617 case LibFunc_log2l:
7618 if (visitUnaryFloatCall(I, ISD::FLOG2))
7619 return;
7620 break;
7621 case LibFunc_exp2:
7622 case LibFunc_exp2f:
7623 case LibFunc_exp2l:
7624 if (visitUnaryFloatCall(I, ISD::FEXP2))
7625 return;
7626 break;
7627 case LibFunc_memcmp:
7628 if (visitMemCmpCall(I))
7629 return;
7630 break;
7631 case LibFunc_mempcpy:
7632 if (visitMemPCpyCall(I))
7633 return;
7634 break;
7635 case LibFunc_memchr:
7636 if (visitMemChrCall(I))
7637 return;
7638 break;
7639 case LibFunc_strcpy:
7640 if (visitStrCpyCall(I, false))
7641 return;
7642 break;
7643 case LibFunc_stpcpy:
7644 if (visitStrCpyCall(I, true))
7645 return;
7646 break;
7647 case LibFunc_strcmp:
7648 if (visitStrCmpCall(I))
7649 return;
7650 break;
7651 case LibFunc_strlen:
7652 if (visitStrLenCall(I))
7653 return;
7654 break;
7655 case LibFunc_strnlen:
7656 if (visitStrNLenCall(I))
7657 return;
7658 break;
7663 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7664 // have to do anything here to lower funclet bundles.
7665 assert(!I.hasOperandBundlesOtherThan(
7666 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7667 "Cannot lower calls with arbitrary operand bundles!");
7669 SDValue Callee = getValue(I.getCalledValue());
7671 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7672 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7673 else
7674 // Check if we can potentially perform a tail call. More detailed checking
7675 // is be done within LowerCallTo, after more information about the call is
7676 // known.
7677 LowerCallTo(&I, Callee, I.isTailCall());
7680 namespace {
7682 /// AsmOperandInfo - This contains information for each constraint that we are
7683 /// lowering.
7684 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7685 public:
7686 /// CallOperand - If this is the result output operand or a clobber
7687 /// this is null, otherwise it is the incoming operand to the CallInst.
7688 /// This gets modified as the asm is processed.
7689 SDValue CallOperand;
7691 /// AssignedRegs - If this is a register or register class operand, this
7692 /// contains the set of register corresponding to the operand.
7693 RegsForValue AssignedRegs;
7695 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7696 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7699 /// Whether or not this operand accesses memory
7700 bool hasMemory(const TargetLowering &TLI) const {
7701 // Indirect operand accesses access memory.
7702 if (isIndirect)
7703 return true;
7705 for (const auto &Code : Codes)
7706 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7707 return true;
7709 return false;
7712 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7713 /// corresponds to. If there is no Value* for this operand, it returns
7714 /// MVT::Other.
7715 EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7716 const DataLayout &DL) const {
7717 if (!CallOperandVal) return MVT::Other;
7719 if (isa<BasicBlock>(CallOperandVal))
7720 return TLI.getPointerTy(DL);
7722 llvm::Type *OpTy = CallOperandVal->getType();
7724 // FIXME: code duplicated from TargetLowering::ParseConstraints().
7725 // If this is an indirect operand, the operand is a pointer to the
7726 // accessed type.
7727 if (isIndirect) {
7728 PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7729 if (!PtrTy)
7730 report_fatal_error("Indirect operand for inline asm not a pointer!");
7731 OpTy = PtrTy->getElementType();
7734 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7735 if (StructType *STy = dyn_cast<StructType>(OpTy))
7736 if (STy->getNumElements() == 1)
7737 OpTy = STy->getElementType(0);
7739 // If OpTy is not a single value, it may be a struct/union that we
7740 // can tile with integers.
7741 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7742 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7743 switch (BitSize) {
7744 default: break;
7745 case 1:
7746 case 8:
7747 case 16:
7748 case 32:
7749 case 64:
7750 case 128:
7751 OpTy = IntegerType::get(Context, BitSize);
7752 break;
7756 return TLI.getValueType(DL, OpTy, true);
7760 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7762 } // end anonymous namespace
7764 /// Make sure that the output operand \p OpInfo and its corresponding input
7765 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7766 /// out).
7767 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7768 SDISelAsmOperandInfo &MatchingOpInfo,
7769 SelectionDAG &DAG) {
7770 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7771 return;
7773 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7774 const auto &TLI = DAG.getTargetLoweringInfo();
7776 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7777 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7778 OpInfo.ConstraintVT);
7779 std::pair<unsigned, const TargetRegisterClass *> InputRC =
7780 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7781 MatchingOpInfo.ConstraintVT);
7782 if ((OpInfo.ConstraintVT.isInteger() !=
7783 MatchingOpInfo.ConstraintVT.isInteger()) ||
7784 (MatchRC.second != InputRC.second)) {
7785 // FIXME: error out in a more elegant fashion
7786 report_fatal_error("Unsupported asm: input constraint"
7787 " with a matching output constraint of"
7788 " incompatible type!");
7790 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7793 /// Get a direct memory input to behave well as an indirect operand.
7794 /// This may introduce stores, hence the need for a \p Chain.
7795 /// \return The (possibly updated) chain.
7796 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7797 SDISelAsmOperandInfo &OpInfo,
7798 SelectionDAG &DAG) {
7799 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7801 // If we don't have an indirect input, put it in the constpool if we can,
7802 // otherwise spill it to a stack slot.
7803 // TODO: This isn't quite right. We need to handle these according to
7804 // the addressing mode that the constraint wants. Also, this may take
7805 // an additional register for the computation and we don't want that
7806 // either.
7808 // If the operand is a float, integer, or vector constant, spill to a
7809 // constant pool entry to get its address.
7810 const Value *OpVal = OpInfo.CallOperandVal;
7811 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7812 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7813 OpInfo.CallOperand = DAG.getConstantPool(
7814 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7815 return Chain;
7818 // Otherwise, create a stack slot and emit a store to it before the asm.
7819 Type *Ty = OpVal->getType();
7820 auto &DL = DAG.getDataLayout();
7821 uint64_t TySize = DL.getTypeAllocSize(Ty);
7822 unsigned Align = DL.getPrefTypeAlignment(Ty);
7823 MachineFunction &MF = DAG.getMachineFunction();
7824 int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7825 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7826 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7827 MachinePointerInfo::getFixedStack(MF, SSFI),
7828 TLI.getMemValueType(DL, Ty));
7829 OpInfo.CallOperand = StackSlot;
7831 return Chain;
7834 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7835 /// specified operand. We prefer to assign virtual registers, to allow the
7836 /// register allocator to handle the assignment process. However, if the asm
7837 /// uses features that we can't model on machineinstrs, we have SDISel do the
7838 /// allocation. This produces generally horrible, but correct, code.
7840 /// OpInfo describes the operand
7841 /// RefOpInfo describes the matching operand if any, the operand otherwise
7842 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7843 SDISelAsmOperandInfo &OpInfo,
7844 SDISelAsmOperandInfo &RefOpInfo) {
7845 LLVMContext &Context = *DAG.getContext();
7846 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7848 MachineFunction &MF = DAG.getMachineFunction();
7849 SmallVector<unsigned, 4> Regs;
7850 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7852 // No work to do for memory operations.
7853 if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7854 return;
7856 // If this is a constraint for a single physreg, or a constraint for a
7857 // register class, find it.
7858 unsigned AssignedReg;
7859 const TargetRegisterClass *RC;
7860 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7861 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7862 // RC is unset only on failure. Return immediately.
7863 if (!RC)
7864 return;
7866 // Get the actual register value type. This is important, because the user
7867 // may have asked for (e.g.) the AX register in i32 type. We need to
7868 // remember that AX is actually i16 to get the right extension.
7869 const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7871 if (OpInfo.ConstraintVT != MVT::Other) {
7872 // If this is an FP operand in an integer register (or visa versa), or more
7873 // generally if the operand value disagrees with the register class we plan
7874 // to stick it in, fix the operand type.
7876 // If this is an input value, the bitcast to the new type is done now.
7877 // Bitcast for output value is done at the end of visitInlineAsm().
7878 if ((OpInfo.Type == InlineAsm::isOutput ||
7879 OpInfo.Type == InlineAsm::isInput) &&
7880 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7881 // Try to convert to the first EVT that the reg class contains. If the
7882 // types are identical size, use a bitcast to convert (e.g. two differing
7883 // vector types). Note: output bitcast is done at the end of
7884 // visitInlineAsm().
7885 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7886 // Exclude indirect inputs while they are unsupported because the code
7887 // to perform the load is missing and thus OpInfo.CallOperand still
7888 // refers to the input address rather than the pointed-to value.
7889 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7890 OpInfo.CallOperand =
7891 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7892 OpInfo.ConstraintVT = RegVT;
7893 // If the operand is an FP value and we want it in integer registers,
7894 // use the corresponding integer type. This turns an f64 value into
7895 // i64, which can be passed with two i32 values on a 32-bit machine.
7896 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7897 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7898 if (OpInfo.Type == InlineAsm::isInput)
7899 OpInfo.CallOperand =
7900 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7901 OpInfo.ConstraintVT = VT;
7906 // No need to allocate a matching input constraint since the constraint it's
7907 // matching to has already been allocated.
7908 if (OpInfo.isMatchingInputConstraint())
7909 return;
7911 EVT ValueVT = OpInfo.ConstraintVT;
7912 if (OpInfo.ConstraintVT == MVT::Other)
7913 ValueVT = RegVT;
7915 // Initialize NumRegs.
7916 unsigned NumRegs = 1;
7917 if (OpInfo.ConstraintVT != MVT::Other)
7918 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7920 // If this is a constraint for a specific physical register, like {r17},
7921 // assign it now.
7923 // If this associated to a specific register, initialize iterator to correct
7924 // place. If virtual, make sure we have enough registers
7926 // Initialize iterator if necessary
7927 TargetRegisterClass::iterator I = RC->begin();
7928 MachineRegisterInfo &RegInfo = MF.getRegInfo();
7930 // Do not check for single registers.
7931 if (AssignedReg) {
7932 for (; *I != AssignedReg; ++I)
7933 assert(I != RC->end() && "AssignedReg should be member of RC");
7936 for (; NumRegs; --NumRegs, ++I) {
7937 assert(I != RC->end() && "Ran out of registers to allocate!");
7938 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7939 Regs.push_back(R);
7942 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7945 static unsigned
7946 findMatchingInlineAsmOperand(unsigned OperandNo,
7947 const std::vector<SDValue> &AsmNodeOperands) {
7948 // Scan until we find the definition we already emitted of this operand.
7949 unsigned CurOp = InlineAsm::Op_FirstOperand;
7950 for (; OperandNo; --OperandNo) {
7951 // Advance to the next operand.
7952 unsigned OpFlag =
7953 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7954 assert((InlineAsm::isRegDefKind(OpFlag) ||
7955 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7956 InlineAsm::isMemKind(OpFlag)) &&
7957 "Skipped past definitions?");
7958 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7960 return CurOp;
7963 namespace {
7965 class ExtraFlags {
7966 unsigned Flags = 0;
7968 public:
7969 explicit ExtraFlags(ImmutableCallSite CS) {
7970 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7971 if (IA->hasSideEffects())
7972 Flags |= InlineAsm::Extra_HasSideEffects;
7973 if (IA->isAlignStack())
7974 Flags |= InlineAsm::Extra_IsAlignStack;
7975 if (CS.isConvergent())
7976 Flags |= InlineAsm::Extra_IsConvergent;
7977 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7980 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7981 // Ideally, we would only check against memory constraints. However, the
7982 // meaning of an Other constraint can be target-specific and we can't easily
7983 // reason about it. Therefore, be conservative and set MayLoad/MayStore
7984 // for Other constraints as well.
7985 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7986 OpInfo.ConstraintType == TargetLowering::C_Other) {
7987 if (OpInfo.Type == InlineAsm::isInput)
7988 Flags |= InlineAsm::Extra_MayLoad;
7989 else if (OpInfo.Type == InlineAsm::isOutput)
7990 Flags |= InlineAsm::Extra_MayStore;
7991 else if (OpInfo.Type == InlineAsm::isClobber)
7992 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7996 unsigned get() const { return Flags; }
7999 } // end anonymous namespace
8001 /// visitInlineAsm - Handle a call to an InlineAsm object.
8002 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
8003 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8005 /// ConstraintOperands - Information about all of the constraints.
8006 SDISelAsmOperandInfoVector ConstraintOperands;
8008 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8009 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8010 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8012 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8013 // AsmDialect, MayLoad, MayStore).
8014 bool HasSideEffect = IA->hasSideEffects();
8015 ExtraFlags ExtraInfo(CS);
8017 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
8018 unsigned ResNo = 0; // ResNo - The result number of the next output.
8019 for (auto &T : TargetConstraints) {
8020 ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8021 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8023 // Compute the value type for each operand.
8024 if (OpInfo.Type == InlineAsm::isInput ||
8025 (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8026 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8028 // Process the call argument. BasicBlocks are labels, currently appearing
8029 // only in asm's.
8030 const Instruction *I = CS.getInstruction();
8031 if (isa<CallBrInst>(I) &&
8032 (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8033 cast<CallBrInst>(I)->getNumIndirectDests())) {
8034 const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8035 EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8036 OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8037 } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8038 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8039 } else {
8040 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8043 OpInfo.ConstraintVT =
8044 OpInfo
8045 .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8046 .getSimpleVT();
8047 } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8048 // The return value of the call is this value. As such, there is no
8049 // corresponding argument.
8050 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8051 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8052 OpInfo.ConstraintVT = TLI.getSimpleValueType(
8053 DAG.getDataLayout(), STy->getElementType(ResNo));
8054 } else {
8055 assert(ResNo == 0 && "Asm only has one result!");
8056 OpInfo.ConstraintVT =
8057 TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8059 ++ResNo;
8060 } else {
8061 OpInfo.ConstraintVT = MVT::Other;
8064 if (!HasSideEffect)
8065 HasSideEffect = OpInfo.hasMemory(TLI);
8067 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8068 // FIXME: Could we compute this on OpInfo rather than T?
8070 // Compute the constraint code and ConstraintType to use.
8071 TLI.ComputeConstraintToUse(T, SDValue());
8073 if (T.ConstraintType == TargetLowering::C_Immediate &&
8074 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8075 // We've delayed emitting a diagnostic like the "n" constraint because
8076 // inlining could cause an integer showing up.
8077 return emitInlineAsmError(
8078 CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8079 "integer constant expression");
8081 ExtraInfo.update(T);
8085 // We won't need to flush pending loads if this asm doesn't touch
8086 // memory and is nonvolatile.
8087 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8089 bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8090 if (IsCallBr) {
8091 // If this is a callbr we need to flush pending exports since inlineasm_br
8092 // is a terminator. We need to do this before nodes are glued to
8093 // the inlineasm_br node.
8094 Chain = getControlRoot();
8097 // Second pass over the constraints: compute which constraint option to use.
8098 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8099 // If this is an output operand with a matching input operand, look up the
8100 // matching input. If their types mismatch, e.g. one is an integer, the
8101 // other is floating point, or their sizes are different, flag it as an
8102 // error.
8103 if (OpInfo.hasMatchingInput()) {
8104 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8105 patchMatchingInput(OpInfo, Input, DAG);
8108 // Compute the constraint code and ConstraintType to use.
8109 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8111 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8112 OpInfo.Type == InlineAsm::isClobber)
8113 continue;
8115 // If this is a memory input, and if the operand is not indirect, do what we
8116 // need to provide an address for the memory input.
8117 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8118 !OpInfo.isIndirect) {
8119 assert((OpInfo.isMultipleAlternative ||
8120 (OpInfo.Type == InlineAsm::isInput)) &&
8121 "Can only indirectify direct input operands!");
8123 // Memory operands really want the address of the value.
8124 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8126 // There is no longer a Value* corresponding to this operand.
8127 OpInfo.CallOperandVal = nullptr;
8129 // It is now an indirect operand.
8130 OpInfo.isIndirect = true;
8135 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8136 std::vector<SDValue> AsmNodeOperands;
8137 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
8138 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8139 IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8141 // If we have a !srcloc metadata node associated with it, we want to attach
8142 // this to the ultimately generated inline asm machineinstr. To do this, we
8143 // pass in the third operand as this (potentially null) inline asm MDNode.
8144 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8145 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8147 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8148 // bits as operand 3.
8149 AsmNodeOperands.push_back(DAG.getTargetConstant(
8150 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8152 // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8153 // this, assign virtual and physical registers for inputs and otput.
8154 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8155 // Assign Registers.
8156 SDISelAsmOperandInfo &RefOpInfo =
8157 OpInfo.isMatchingInputConstraint()
8158 ? ConstraintOperands[OpInfo.getMatchedOperand()]
8159 : OpInfo;
8160 GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8162 switch (OpInfo.Type) {
8163 case InlineAsm::isOutput:
8164 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8165 ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8166 OpInfo.ConstraintType == TargetLowering::C_Other) &&
8167 OpInfo.isIndirect)) {
8168 unsigned ConstraintID =
8169 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8170 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8171 "Failed to convert memory constraint code to constraint id.");
8173 // Add information to the INLINEASM node to know about this output.
8174 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8175 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8176 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8177 MVT::i32));
8178 AsmNodeOperands.push_back(OpInfo.CallOperand);
8179 break;
8180 } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8181 OpInfo.ConstraintType == TargetLowering::C_Other) &&
8182 !OpInfo.isIndirect) ||
8183 OpInfo.ConstraintType == TargetLowering::C_Register ||
8184 OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
8185 // Otherwise, this outputs to a register (directly for C_Register /
8186 // C_RegisterClass, and a target-defined fashion for
8187 // C_Immediate/C_Other). Find a register that we can use.
8188 if (OpInfo.AssignedRegs.Regs.empty()) {
8189 emitInlineAsmError(
8190 CS, "couldn't allocate output register for constraint '" +
8191 Twine(OpInfo.ConstraintCode) + "'");
8192 return;
8195 // Add information to the INLINEASM node to know that this register is
8196 // set.
8197 OpInfo.AssignedRegs.AddInlineAsmOperands(
8198 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8199 : InlineAsm::Kind_RegDef,
8200 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8202 break;
8204 case InlineAsm::isInput: {
8205 SDValue InOperandVal = OpInfo.CallOperand;
8207 if (OpInfo.isMatchingInputConstraint()) {
8208 // If this is required to match an output register we have already set,
8209 // just use its register.
8210 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8211 AsmNodeOperands);
8212 unsigned OpFlag =
8213 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8214 if (InlineAsm::isRegDefKind(OpFlag) ||
8215 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8216 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8217 if (OpInfo.isIndirect) {
8218 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8219 emitInlineAsmError(CS, "inline asm not supported yet:"
8220 " don't know how to handle tied "
8221 "indirect register inputs");
8222 return;
8225 MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8226 SmallVector<unsigned, 4> Regs;
8228 if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8229 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8230 MachineRegisterInfo &RegInfo =
8231 DAG.getMachineFunction().getRegInfo();
8232 for (unsigned i = 0; i != NumRegs; ++i)
8233 Regs.push_back(RegInfo.createVirtualRegister(RC));
8234 } else {
8235 emitInlineAsmError(CS, "inline asm error: This value type register "
8236 "class is not natively supported!");
8237 return;
8240 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8242 SDLoc dl = getCurSDLoc();
8243 // Use the produced MatchedRegs object to
8244 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8245 CS.getInstruction());
8246 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8247 true, OpInfo.getMatchedOperand(), dl,
8248 DAG, AsmNodeOperands);
8249 break;
8252 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8253 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8254 "Unexpected number of operands");
8255 // Add information to the INLINEASM node to know about this input.
8256 // See InlineAsm.h isUseOperandTiedToDef.
8257 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8258 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8259 OpInfo.getMatchedOperand());
8260 AsmNodeOperands.push_back(DAG.getTargetConstant(
8261 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8262 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8263 break;
8266 // Treat indirect 'X' constraint as memory.
8267 if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8268 OpInfo.ConstraintType == TargetLowering::C_Other) &&
8269 OpInfo.isIndirect)
8270 OpInfo.ConstraintType = TargetLowering::C_Memory;
8272 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8273 OpInfo.ConstraintType == TargetLowering::C_Other) {
8274 std::vector<SDValue> Ops;
8275 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8276 Ops, DAG);
8277 if (Ops.empty()) {
8278 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8279 if (isa<ConstantSDNode>(InOperandVal)) {
8280 emitInlineAsmError(CS, "value out of range for constraint '" +
8281 Twine(OpInfo.ConstraintCode) + "'");
8282 return;
8285 emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8286 Twine(OpInfo.ConstraintCode) + "'");
8287 return;
8290 // Add information to the INLINEASM node to know about this input.
8291 unsigned ResOpType =
8292 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8293 AsmNodeOperands.push_back(DAG.getTargetConstant(
8294 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8295 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8296 break;
8299 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8300 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8301 assert(InOperandVal.getValueType() ==
8302 TLI.getPointerTy(DAG.getDataLayout()) &&
8303 "Memory operands expect pointer values");
8305 unsigned ConstraintID =
8306 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8307 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8308 "Failed to convert memory constraint code to constraint id.");
8310 // Add information to the INLINEASM node to know about this input.
8311 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8312 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8313 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8314 getCurSDLoc(),
8315 MVT::i32));
8316 AsmNodeOperands.push_back(InOperandVal);
8317 break;
8320 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8321 OpInfo.ConstraintType == TargetLowering::C_Register ||
8322 OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
8323 "Unknown constraint type!");
8325 // TODO: Support this.
8326 if (OpInfo.isIndirect) {
8327 emitInlineAsmError(
8328 CS, "Don't know how to handle indirect register inputs yet "
8329 "for constraint '" +
8330 Twine(OpInfo.ConstraintCode) + "'");
8331 return;
8334 // Copy the input into the appropriate registers.
8335 if (OpInfo.AssignedRegs.Regs.empty()) {
8336 emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8337 Twine(OpInfo.ConstraintCode) + "'");
8338 return;
8341 SDLoc dl = getCurSDLoc();
8343 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8344 Chain, &Flag, CS.getInstruction());
8346 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8347 dl, DAG, AsmNodeOperands);
8348 break;
8350 case InlineAsm::isClobber:
8351 // Add the clobbered value to the operand list, so that the register
8352 // allocator is aware that the physreg got clobbered.
8353 if (!OpInfo.AssignedRegs.Regs.empty())
8354 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8355 false, 0, getCurSDLoc(), DAG,
8356 AsmNodeOperands);
8357 break;
8361 // Finish up input operands. Set the input chain and add the flag last.
8362 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8363 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8365 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8366 Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8367 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8368 Flag = Chain.getValue(1);
8370 // Do additional work to generate outputs.
8372 SmallVector<EVT, 1> ResultVTs;
8373 SmallVector<SDValue, 1> ResultValues;
8374 SmallVector<SDValue, 8> OutChains;
8376 llvm::Type *CSResultType = CS.getType();
8377 ArrayRef<Type *> ResultTypes;
8378 if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8379 ResultTypes = StructResult->elements();
8380 else if (!CSResultType->isVoidTy())
8381 ResultTypes = makeArrayRef(CSResultType);
8383 auto CurResultType = ResultTypes.begin();
8384 auto handleRegAssign = [&](SDValue V) {
8385 assert(CurResultType != ResultTypes.end() && "Unexpected value");
8386 assert((*CurResultType)->isSized() && "Unexpected unsized type");
8387 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8388 ++CurResultType;
8389 // If the type of the inline asm call site return value is different but has
8390 // same size as the type of the asm output bitcast it. One example of this
8391 // is for vectors with different width / number of elements. This can
8392 // happen for register classes that can contain multiple different value
8393 // types. The preg or vreg allocated may not have the same VT as was
8394 // expected.
8396 // This can also happen for a return value that disagrees with the register
8397 // class it is put in, eg. a double in a general-purpose register on a
8398 // 32-bit machine.
8399 if (ResultVT != V.getValueType() &&
8400 ResultVT.getSizeInBits() == V.getValueSizeInBits())
8401 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8402 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8403 V.getValueType().isInteger()) {
8404 // If a result value was tied to an input value, the computed result
8405 // may have a wider width than the expected result. Extract the
8406 // relevant portion.
8407 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8409 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8410 ResultVTs.push_back(ResultVT);
8411 ResultValues.push_back(V);
8414 // Deal with output operands.
8415 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8416 if (OpInfo.Type == InlineAsm::isOutput) {
8417 SDValue Val;
8418 // Skip trivial output operands.
8419 if (OpInfo.AssignedRegs.Regs.empty())
8420 continue;
8422 switch (OpInfo.ConstraintType) {
8423 case TargetLowering::C_Register:
8424 case TargetLowering::C_RegisterClass:
8425 Val = OpInfo.AssignedRegs.getCopyFromRegs(
8426 DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8427 break;
8428 case TargetLowering::C_Immediate:
8429 case TargetLowering::C_Other:
8430 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8431 OpInfo, DAG);
8432 break;
8433 case TargetLowering::C_Memory:
8434 break; // Already handled.
8435 case TargetLowering::C_Unknown:
8436 assert(false && "Unexpected unknown constraint");
8439 // Indirect output manifest as stores. Record output chains.
8440 if (OpInfo.isIndirect) {
8441 const Value *Ptr = OpInfo.CallOperandVal;
8442 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8443 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8444 MachinePointerInfo(Ptr));
8445 OutChains.push_back(Store);
8446 } else {
8447 // generate CopyFromRegs to associated registers.
8448 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8449 if (Val.getOpcode() == ISD::MERGE_VALUES) {
8450 for (const SDValue &V : Val->op_values())
8451 handleRegAssign(V);
8452 } else
8453 handleRegAssign(Val);
8458 // Set results.
8459 if (!ResultValues.empty()) {
8460 assert(CurResultType == ResultTypes.end() &&
8461 "Mismatch in number of ResultTypes");
8462 assert(ResultValues.size() == ResultTypes.size() &&
8463 "Mismatch in number of output operands in asm result");
8465 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8466 DAG.getVTList(ResultVTs), ResultValues);
8467 setValue(CS.getInstruction(), V);
8470 // Collect store chains.
8471 if (!OutChains.empty())
8472 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8474 // Only Update Root if inline assembly has a memory effect.
8475 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8476 DAG.setRoot(Chain);
8479 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8480 const Twine &Message) {
8481 LLVMContext &Ctx = *DAG.getContext();
8482 Ctx.emitError(CS.getInstruction(), Message);
8484 // Make sure we leave the DAG in a valid state
8485 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8486 SmallVector<EVT, 1> ValueVTs;
8487 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8489 if (ValueVTs.empty())
8490 return;
8492 SmallVector<SDValue, 1> Ops;
8493 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8494 Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8496 setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8499 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8500 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8501 MVT::Other, getRoot(),
8502 getValue(I.getArgOperand(0)),
8503 DAG.getSrcValue(I.getArgOperand(0))));
8506 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8507 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8508 const DataLayout &DL = DAG.getDataLayout();
8509 SDValue V = DAG.getVAArg(
8510 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8511 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8512 DL.getABITypeAlignment(I.getType()));
8513 DAG.setRoot(V.getValue(1));
8515 if (I.getType()->isPointerTy())
8516 V = DAG.getPtrExtOrTrunc(
8517 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8518 setValue(&I, V);
8521 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8522 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8523 MVT::Other, getRoot(),
8524 getValue(I.getArgOperand(0)),
8525 DAG.getSrcValue(I.getArgOperand(0))));
8528 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8529 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8530 MVT::Other, getRoot(),
8531 getValue(I.getArgOperand(0)),
8532 getValue(I.getArgOperand(1)),
8533 DAG.getSrcValue(I.getArgOperand(0)),
8534 DAG.getSrcValue(I.getArgOperand(1))));
8537 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8538 const Instruction &I,
8539 SDValue Op) {
8540 const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8541 if (!Range)
8542 return Op;
8544 ConstantRange CR = getConstantRangeFromMetadata(*Range);
8545 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8546 return Op;
8548 APInt Lo = CR.getUnsignedMin();
8549 if (!Lo.isMinValue())
8550 return Op;
8552 APInt Hi = CR.getUnsignedMax();
8553 unsigned Bits = std::max(Hi.getActiveBits(),
8554 static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8556 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8558 SDLoc SL = getCurSDLoc();
8560 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8561 DAG.getValueType(SmallVT));
8562 unsigned NumVals = Op.getNode()->getNumValues();
8563 if (NumVals == 1)
8564 return ZExt;
8566 SmallVector<SDValue, 4> Ops;
8568 Ops.push_back(ZExt);
8569 for (unsigned I = 1; I != NumVals; ++I)
8570 Ops.push_back(Op.getValue(I));
8572 return DAG.getMergeValues(Ops, SL);
8575 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8576 /// the call being lowered.
8578 /// This is a helper for lowering intrinsics that follow a target calling
8579 /// convention or require stack pointer adjustment. Only a subset of the
8580 /// intrinsic's operands need to participate in the calling convention.
8581 void SelectionDAGBuilder::populateCallLoweringInfo(
8582 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8583 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8584 bool IsPatchPoint) {
8585 TargetLowering::ArgListTy Args;
8586 Args.reserve(NumArgs);
8588 // Populate the argument list.
8589 // Attributes for args start at offset 1, after the return attribute.
8590 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8591 ArgI != ArgE; ++ArgI) {
8592 const Value *V = Call->getOperand(ArgI);
8594 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8596 TargetLowering::ArgListEntry Entry;
8597 Entry.Node = getValue(V);
8598 Entry.Ty = V->getType();
8599 Entry.setAttributes(Call, ArgI);
8600 Args.push_back(Entry);
8603 CLI.setDebugLoc(getCurSDLoc())
8604 .setChain(getRoot())
8605 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8606 .setDiscardResult(Call->use_empty())
8607 .setIsPatchPoint(IsPatchPoint);
8610 /// Add a stack map intrinsic call's live variable operands to a stackmap
8611 /// or patchpoint target node's operand list.
8613 /// Constants are converted to TargetConstants purely as an optimization to
8614 /// avoid constant materialization and register allocation.
8616 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8617 /// generate addess computation nodes, and so FinalizeISel can convert the
8618 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8619 /// address materialization and register allocation, but may also be required
8620 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8621 /// alloca in the entry block, then the runtime may assume that the alloca's
8622 /// StackMap location can be read immediately after compilation and that the
8623 /// location is valid at any point during execution (this is similar to the
8624 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8625 /// only available in a register, then the runtime would need to trap when
8626 /// execution reaches the StackMap in order to read the alloca's location.
8627 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8628 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8629 SelectionDAGBuilder &Builder) {
8630 for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8631 SDValue OpVal = Builder.getValue(CS.getArgument(i));
8632 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8633 Ops.push_back(
8634 Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8635 Ops.push_back(
8636 Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8637 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8638 const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8639 Ops.push_back(Builder.DAG.getTargetFrameIndex(
8640 FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8641 } else
8642 Ops.push_back(OpVal);
8646 /// Lower llvm.experimental.stackmap directly to its target opcode.
8647 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8648 // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8649 // [live variables...])
8651 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8653 SDValue Chain, InFlag, Callee, NullPtr;
8654 SmallVector<SDValue, 32> Ops;
8656 SDLoc DL = getCurSDLoc();
8657 Callee = getValue(CI.getCalledValue());
8658 NullPtr = DAG.getIntPtrConstant(0, DL, true);
8660 // The stackmap intrinsic only records the live variables (the arguemnts
8661 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8662 // intrinsic, this won't be lowered to a function call. This means we don't
8663 // have to worry about calling conventions and target specific lowering code.
8664 // Instead we perform the call lowering right here.
8666 // chain, flag = CALLSEQ_START(chain, 0, 0)
8667 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8668 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8670 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8671 InFlag = Chain.getValue(1);
8673 // Add the <id> and <numBytes> constants.
8674 SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8675 Ops.push_back(DAG.getTargetConstant(
8676 cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8677 SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8678 Ops.push_back(DAG.getTargetConstant(
8679 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8680 MVT::i32));
8682 // Push live variables for the stack map.
8683 addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8685 // We are not pushing any register mask info here on the operands list,
8686 // because the stackmap doesn't clobber anything.
8688 // Push the chain and the glue flag.
8689 Ops.push_back(Chain);
8690 Ops.push_back(InFlag);
8692 // Create the STACKMAP node.
8693 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8694 SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8695 Chain = SDValue(SM, 0);
8696 InFlag = Chain.getValue(1);
8698 Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8700 // Stackmaps don't generate values, so nothing goes into the NodeMap.
8702 // Set the root to the target-lowered call chain.
8703 DAG.setRoot(Chain);
8705 // Inform the Frame Information that we have a stackmap in this function.
8706 FuncInfo.MF->getFrameInfo().setHasStackMap();
8709 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8710 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8711 const BasicBlock *EHPadBB) {
8712 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8713 // i32 <numBytes>,
8714 // i8* <target>,
8715 // i32 <numArgs>,
8716 // [Args...],
8717 // [live variables...])
8719 CallingConv::ID CC = CS.getCallingConv();
8720 bool IsAnyRegCC = CC == CallingConv::AnyReg;
8721 bool HasDef = !CS->getType()->isVoidTy();
8722 SDLoc dl = getCurSDLoc();
8723 SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8725 // Handle immediate and symbolic callees.
8726 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8727 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8728 /*isTarget=*/true);
8729 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8730 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8731 SDLoc(SymbolicCallee),
8732 SymbolicCallee->getValueType(0));
8734 // Get the real number of arguments participating in the call <numArgs>
8735 SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8736 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8738 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8739 // Intrinsics include all meta-operands up to but not including CC.
8740 unsigned NumMetaOpers = PatchPointOpers::CCPos;
8741 assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8742 "Not enough arguments provided to the patchpoint intrinsic");
8744 // For AnyRegCC the arguments are lowered later on manually.
8745 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8746 Type *ReturnTy =
8747 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8749 TargetLowering::CallLoweringInfo CLI(DAG);
8750 populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8751 NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8752 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8754 SDNode *CallEnd = Result.second.getNode();
8755 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8756 CallEnd = CallEnd->getOperand(0).getNode();
8758 /// Get a call instruction from the call sequence chain.
8759 /// Tail calls are not allowed.
8760 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8761 "Expected a callseq node.");
8762 SDNode *Call = CallEnd->getOperand(0).getNode();
8763 bool HasGlue = Call->getGluedNode();
8765 // Replace the target specific call node with the patchable intrinsic.
8766 SmallVector<SDValue, 8> Ops;
8768 // Add the <id> and <numBytes> constants.
8769 SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8770 Ops.push_back(DAG.getTargetConstant(
8771 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8772 SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8773 Ops.push_back(DAG.getTargetConstant(
8774 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8775 MVT::i32));
8777 // Add the callee.
8778 Ops.push_back(Callee);
8780 // Adjust <numArgs> to account for any arguments that have been passed on the
8781 // stack instead.
8782 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8783 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8784 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8785 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8787 // Add the calling convention
8788 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8790 // Add the arguments we omitted previously. The register allocator should
8791 // place these in any free register.
8792 if (IsAnyRegCC)
8793 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8794 Ops.push_back(getValue(CS.getArgument(i)));
8796 // Push the arguments from the call instruction up to the register mask.
8797 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8798 Ops.append(Call->op_begin() + 2, e);
8800 // Push live variables for the stack map.
8801 addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8803 // Push the register mask info.
8804 if (HasGlue)
8805 Ops.push_back(*(Call->op_end()-2));
8806 else
8807 Ops.push_back(*(Call->op_end()-1));
8809 // Push the chain (this is originally the first operand of the call, but
8810 // becomes now the last or second to last operand).
8811 Ops.push_back(*(Call->op_begin()));
8813 // Push the glue flag (last operand).
8814 if (HasGlue)
8815 Ops.push_back(*(Call->op_end()-1));
8817 SDVTList NodeTys;
8818 if (IsAnyRegCC && HasDef) {
8819 // Create the return types based on the intrinsic definition
8820 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8821 SmallVector<EVT, 3> ValueVTs;
8822 ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8823 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8825 // There is always a chain and a glue type at the end
8826 ValueVTs.push_back(MVT::Other);
8827 ValueVTs.push_back(MVT::Glue);
8828 NodeTys = DAG.getVTList(ValueVTs);
8829 } else
8830 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8832 // Replace the target specific call node with a PATCHPOINT node.
8833 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8834 dl, NodeTys, Ops);
8836 // Update the NodeMap.
8837 if (HasDef) {
8838 if (IsAnyRegCC)
8839 setValue(CS.getInstruction(), SDValue(MN, 0));
8840 else
8841 setValue(CS.getInstruction(), Result.first);
8844 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8845 // call sequence. Furthermore the location of the chain and glue can change
8846 // when the AnyReg calling convention is used and the intrinsic returns a
8847 // value.
8848 if (IsAnyRegCC && HasDef) {
8849 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8850 SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8851 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8852 } else
8853 DAG.ReplaceAllUsesWith(Call, MN);
8854 DAG.DeleteNode(Call);
8856 // Inform the Frame Information that we have a patchpoint in this function.
8857 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8860 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8861 unsigned Intrinsic) {
8862 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8863 SDValue Op1 = getValue(I.getArgOperand(0));
8864 SDValue Op2;
8865 if (I.getNumArgOperands() > 1)
8866 Op2 = getValue(I.getArgOperand(1));
8867 SDLoc dl = getCurSDLoc();
8868 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8869 SDValue Res;
8870 FastMathFlags FMF;
8871 if (isa<FPMathOperator>(I))
8872 FMF = I.getFastMathFlags();
8874 switch (Intrinsic) {
8875 case Intrinsic::experimental_vector_reduce_v2_fadd:
8876 if (FMF.allowReassoc())
8877 Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8878 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8879 else
8880 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8881 break;
8882 case Intrinsic::experimental_vector_reduce_v2_fmul:
8883 if (FMF.allowReassoc())
8884 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8885 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8886 else
8887 Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8888 break;
8889 case Intrinsic::experimental_vector_reduce_add:
8890 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8891 break;
8892 case Intrinsic::experimental_vector_reduce_mul:
8893 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8894 break;
8895 case Intrinsic::experimental_vector_reduce_and:
8896 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8897 break;
8898 case Intrinsic::experimental_vector_reduce_or:
8899 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8900 break;
8901 case Intrinsic::experimental_vector_reduce_xor:
8902 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8903 break;
8904 case Intrinsic::experimental_vector_reduce_smax:
8905 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8906 break;
8907 case Intrinsic::experimental_vector_reduce_smin:
8908 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8909 break;
8910 case Intrinsic::experimental_vector_reduce_umax:
8911 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8912 break;
8913 case Intrinsic::experimental_vector_reduce_umin:
8914 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8915 break;
8916 case Intrinsic::experimental_vector_reduce_fmax:
8917 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8918 break;
8919 case Intrinsic::experimental_vector_reduce_fmin:
8920 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8921 break;
8922 default:
8923 llvm_unreachable("Unhandled vector reduce intrinsic");
8925 setValue(&I, Res);
8928 /// Returns an AttributeList representing the attributes applied to the return
8929 /// value of the given call.
8930 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8931 SmallVector<Attribute::AttrKind, 2> Attrs;
8932 if (CLI.RetSExt)
8933 Attrs.push_back(Attribute::SExt);
8934 if (CLI.RetZExt)
8935 Attrs.push_back(Attribute::ZExt);
8936 if (CLI.IsInReg)
8937 Attrs.push_back(Attribute::InReg);
8939 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8940 Attrs);
8943 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8944 /// implementation, which just calls LowerCall.
8945 /// FIXME: When all targets are
8946 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8947 std::pair<SDValue, SDValue>
8948 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8949 // Handle the incoming return values from the call.
8950 CLI.Ins.clear();
8951 Type *OrigRetTy = CLI.RetTy;
8952 SmallVector<EVT, 4> RetTys;
8953 SmallVector<uint64_t, 4> Offsets;
8954 auto &DL = CLI.DAG.getDataLayout();
8955 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8957 if (CLI.IsPostTypeLegalization) {
8958 // If we are lowering a libcall after legalization, split the return type.
8959 SmallVector<EVT, 4> OldRetTys;
8960 SmallVector<uint64_t, 4> OldOffsets;
8961 RetTys.swap(OldRetTys);
8962 Offsets.swap(OldOffsets);
8964 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8965 EVT RetVT = OldRetTys[i];
8966 uint64_t Offset = OldOffsets[i];
8967 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8968 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8969 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8970 RetTys.append(NumRegs, RegisterVT);
8971 for (unsigned j = 0; j != NumRegs; ++j)
8972 Offsets.push_back(Offset + j * RegisterVTByteSZ);
8976 SmallVector<ISD::OutputArg, 4> Outs;
8977 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8979 bool CanLowerReturn =
8980 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8981 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8983 SDValue DemoteStackSlot;
8984 int DemoteStackIdx = -100;
8985 if (!CanLowerReturn) {
8986 // FIXME: equivalent assert?
8987 // assert(!CS.hasInAllocaArgument() &&
8988 // "sret demotion is incompatible with inalloca");
8989 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8990 unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8991 MachineFunction &MF = CLI.DAG.getMachineFunction();
8992 DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8993 Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8994 DL.getAllocaAddrSpace());
8996 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8997 ArgListEntry Entry;
8998 Entry.Node = DemoteStackSlot;
8999 Entry.Ty = StackSlotPtrType;
9000 Entry.IsSExt = false;
9001 Entry.IsZExt = false;
9002 Entry.IsInReg = false;
9003 Entry.IsSRet = true;
9004 Entry.IsNest = false;
9005 Entry.IsByVal = false;
9006 Entry.IsReturned = false;
9007 Entry.IsSwiftSelf = false;
9008 Entry.IsSwiftError = false;
9009 Entry.Alignment = Align;
9010 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9011 CLI.NumFixedArgs += 1;
9012 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9014 // sret demotion isn't compatible with tail-calls, since the sret argument
9015 // points into the callers stack frame.
9016 CLI.IsTailCall = false;
9017 } else {
9018 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9019 CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9020 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9021 ISD::ArgFlagsTy Flags;
9022 if (NeedsRegBlock) {
9023 Flags.setInConsecutiveRegs();
9024 if (I == RetTys.size() - 1)
9025 Flags.setInConsecutiveRegsLast();
9027 EVT VT = RetTys[I];
9028 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9029 CLI.CallConv, VT);
9030 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9031 CLI.CallConv, VT);
9032 for (unsigned i = 0; i != NumRegs; ++i) {
9033 ISD::InputArg MyFlags;
9034 MyFlags.Flags = Flags;
9035 MyFlags.VT = RegisterVT;
9036 MyFlags.ArgVT = VT;
9037 MyFlags.Used = CLI.IsReturnValueUsed;
9038 if (CLI.RetTy->isPointerTy()) {
9039 MyFlags.Flags.setPointer();
9040 MyFlags.Flags.setPointerAddrSpace(
9041 cast<PointerType>(CLI.RetTy)->getAddressSpace());
9043 if (CLI.RetSExt)
9044 MyFlags.Flags.setSExt();
9045 if (CLI.RetZExt)
9046 MyFlags.Flags.setZExt();
9047 if (CLI.IsInReg)
9048 MyFlags.Flags.setInReg();
9049 CLI.Ins.push_back(MyFlags);
9054 // We push in swifterror return as the last element of CLI.Ins.
9055 ArgListTy &Args = CLI.getArgs();
9056 if (supportSwiftError()) {
9057 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9058 if (Args[i].IsSwiftError) {
9059 ISD::InputArg MyFlags;
9060 MyFlags.VT = getPointerTy(DL);
9061 MyFlags.ArgVT = EVT(getPointerTy(DL));
9062 MyFlags.Flags.setSwiftError();
9063 CLI.Ins.push_back(MyFlags);
9068 // Handle all of the outgoing arguments.
9069 CLI.Outs.clear();
9070 CLI.OutVals.clear();
9071 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9072 SmallVector<EVT, 4> ValueVTs;
9073 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9074 // FIXME: Split arguments if CLI.IsPostTypeLegalization
9075 Type *FinalType = Args[i].Ty;
9076 if (Args[i].IsByVal)
9077 FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9078 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9079 FinalType, CLI.CallConv, CLI.IsVarArg);
9080 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9081 ++Value) {
9082 EVT VT = ValueVTs[Value];
9083 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9084 SDValue Op = SDValue(Args[i].Node.getNode(),
9085 Args[i].Node.getResNo() + Value);
9086 ISD::ArgFlagsTy Flags;
9088 // Certain targets (such as MIPS), may have a different ABI alignment
9089 // for a type depending on the context. Give the target a chance to
9090 // specify the alignment it wants.
9091 unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
9093 if (Args[i].Ty->isPointerTy()) {
9094 Flags.setPointer();
9095 Flags.setPointerAddrSpace(
9096 cast<PointerType>(Args[i].Ty)->getAddressSpace());
9098 if (Args[i].IsZExt)
9099 Flags.setZExt();
9100 if (Args[i].IsSExt)
9101 Flags.setSExt();
9102 if (Args[i].IsInReg) {
9103 // If we are using vectorcall calling convention, a structure that is
9104 // passed InReg - is surely an HVA
9105 if (CLI.CallConv == CallingConv::X86_VectorCall &&
9106 isa<StructType>(FinalType)) {
9107 // The first value of a structure is marked
9108 if (0 == Value)
9109 Flags.setHvaStart();
9110 Flags.setHva();
9112 // Set InReg Flag
9113 Flags.setInReg();
9115 if (Args[i].IsSRet)
9116 Flags.setSRet();
9117 if (Args[i].IsSwiftSelf)
9118 Flags.setSwiftSelf();
9119 if (Args[i].IsSwiftError)
9120 Flags.setSwiftError();
9121 if (Args[i].IsByVal)
9122 Flags.setByVal();
9123 if (Args[i].IsInAlloca) {
9124 Flags.setInAlloca();
9125 // Set the byval flag for CCAssignFn callbacks that don't know about
9126 // inalloca. This way we can know how many bytes we should've allocated
9127 // and how many bytes a callee cleanup function will pop. If we port
9128 // inalloca to more targets, we'll have to add custom inalloca handling
9129 // in the various CC lowering callbacks.
9130 Flags.setByVal();
9132 if (Args[i].IsByVal || Args[i].IsInAlloca) {
9133 PointerType *Ty = cast<PointerType>(Args[i].Ty);
9134 Type *ElementTy = Ty->getElementType();
9136 unsigned FrameSize = DL.getTypeAllocSize(
9137 Args[i].ByValType ? Args[i].ByValType : ElementTy);
9138 Flags.setByValSize(FrameSize);
9140 // info is not there but there are cases it cannot get right.
9141 unsigned FrameAlign;
9142 if (Args[i].Alignment)
9143 FrameAlign = Args[i].Alignment;
9144 else
9145 FrameAlign = getByValTypeAlignment(ElementTy, DL);
9146 Flags.setByValAlign(FrameAlign);
9148 if (Args[i].IsNest)
9149 Flags.setNest();
9150 if (NeedsRegBlock)
9151 Flags.setInConsecutiveRegs();
9152 Flags.setOrigAlign(OriginalAlignment);
9154 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9155 CLI.CallConv, VT);
9156 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9157 CLI.CallConv, VT);
9158 SmallVector<SDValue, 4> Parts(NumParts);
9159 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9161 if (Args[i].IsSExt)
9162 ExtendKind = ISD::SIGN_EXTEND;
9163 else if (Args[i].IsZExt)
9164 ExtendKind = ISD::ZERO_EXTEND;
9166 // Conservatively only handle 'returned' on non-vectors that can be lowered,
9167 // for now.
9168 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9169 CanLowerReturn) {
9170 assert((CLI.RetTy == Args[i].Ty ||
9171 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9172 CLI.RetTy->getPointerAddressSpace() ==
9173 Args[i].Ty->getPointerAddressSpace())) &&
9174 RetTys.size() == NumValues && "unexpected use of 'returned'");
9175 // Before passing 'returned' to the target lowering code, ensure that
9176 // either the register MVT and the actual EVT are the same size or that
9177 // the return value and argument are extended in the same way; in these
9178 // cases it's safe to pass the argument register value unchanged as the
9179 // return register value (although it's at the target's option whether
9180 // to do so)
9181 // TODO: allow code generation to take advantage of partially preserved
9182 // registers rather than clobbering the entire register when the
9183 // parameter extension method is not compatible with the return
9184 // extension method
9185 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9186 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9187 CLI.RetZExt == Args[i].IsZExt))
9188 Flags.setReturned();
9191 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9192 CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9194 for (unsigned j = 0; j != NumParts; ++j) {
9195 // if it isn't first piece, alignment must be 1
9196 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9197 i < CLI.NumFixedArgs,
9198 i, j*Parts[j].getValueType().getStoreSize());
9199 if (NumParts > 1 && j == 0)
9200 MyFlags.Flags.setSplit();
9201 else if (j != 0) {
9202 MyFlags.Flags.setOrigAlign(1);
9203 if (j == NumParts - 1)
9204 MyFlags.Flags.setSplitEnd();
9207 CLI.Outs.push_back(MyFlags);
9208 CLI.OutVals.push_back(Parts[j]);
9211 if (NeedsRegBlock && Value == NumValues - 1)
9212 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9216 SmallVector<SDValue, 4> InVals;
9217 CLI.Chain = LowerCall(CLI, InVals);
9219 // Update CLI.InVals to use outside of this function.
9220 CLI.InVals = InVals;
9222 // Verify that the target's LowerCall behaved as expected.
9223 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9224 "LowerCall didn't return a valid chain!");
9225 assert((!CLI.IsTailCall || InVals.empty()) &&
9226 "LowerCall emitted a return value for a tail call!");
9227 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9228 "LowerCall didn't emit the correct number of values!");
9230 // For a tail call, the return value is merely live-out and there aren't
9231 // any nodes in the DAG representing it. Return a special value to
9232 // indicate that a tail call has been emitted and no more Instructions
9233 // should be processed in the current block.
9234 if (CLI.IsTailCall) {
9235 CLI.DAG.setRoot(CLI.Chain);
9236 return std::make_pair(SDValue(), SDValue());
9239 #ifndef NDEBUG
9240 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9241 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9242 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9243 "LowerCall emitted a value with the wrong type!");
9245 #endif
9247 SmallVector<SDValue, 4> ReturnValues;
9248 if (!CanLowerReturn) {
9249 // The instruction result is the result of loading from the
9250 // hidden sret parameter.
9251 SmallVector<EVT, 1> PVTs;
9252 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9254 ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9255 assert(PVTs.size() == 1 && "Pointers should fit in one register");
9256 EVT PtrVT = PVTs[0];
9258 unsigned NumValues = RetTys.size();
9259 ReturnValues.resize(NumValues);
9260 SmallVector<SDValue, 4> Chains(NumValues);
9262 // An aggregate return value cannot wrap around the address space, so
9263 // offsets to its parts don't wrap either.
9264 SDNodeFlags Flags;
9265 Flags.setNoUnsignedWrap(true);
9267 for (unsigned i = 0; i < NumValues; ++i) {
9268 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9269 CLI.DAG.getConstant(Offsets[i], CLI.DL,
9270 PtrVT), Flags);
9271 SDValue L = CLI.DAG.getLoad(
9272 RetTys[i], CLI.DL, CLI.Chain, Add,
9273 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9274 DemoteStackIdx, Offsets[i]),
9275 /* Alignment = */ 1);
9276 ReturnValues[i] = L;
9277 Chains[i] = L.getValue(1);
9280 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9281 } else {
9282 // Collect the legal value parts into potentially illegal values
9283 // that correspond to the original function's return values.
9284 Optional<ISD::NodeType> AssertOp;
9285 if (CLI.RetSExt)
9286 AssertOp = ISD::AssertSext;
9287 else if (CLI.RetZExt)
9288 AssertOp = ISD::AssertZext;
9289 unsigned CurReg = 0;
9290 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9291 EVT VT = RetTys[I];
9292 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9293 CLI.CallConv, VT);
9294 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9295 CLI.CallConv, VT);
9297 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9298 NumRegs, RegisterVT, VT, nullptr,
9299 CLI.CallConv, AssertOp));
9300 CurReg += NumRegs;
9303 // For a function returning void, there is no return value. We can't create
9304 // such a node, so we just return a null return value in that case. In
9305 // that case, nothing will actually look at the value.
9306 if (ReturnValues.empty())
9307 return std::make_pair(SDValue(), CLI.Chain);
9310 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9311 CLI.DAG.getVTList(RetTys), ReturnValues);
9312 return std::make_pair(Res, CLI.Chain);
9315 void TargetLowering::LowerOperationWrapper(SDNode *N,
9316 SmallVectorImpl<SDValue> &Results,
9317 SelectionDAG &DAG) const {
9318 if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9319 Results.push_back(Res);
9322 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9323 llvm_unreachable("LowerOperation not implemented for this target!");
9326 void
9327 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9328 SDValue Op = getNonRegisterValue(V);
9329 assert((Op.getOpcode() != ISD::CopyFromReg ||
9330 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9331 "Copy from a reg to the same reg!");
9332 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9334 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9335 // If this is an InlineAsm we have to match the registers required, not the
9336 // notional registers required by the type.
9338 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9339 None); // This is not an ABI copy.
9340 SDValue Chain = DAG.getEntryNode();
9342 ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9343 FuncInfo.PreferredExtendType.end())
9344 ? ISD::ANY_EXTEND
9345 : FuncInfo.PreferredExtendType[V];
9346 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9347 PendingExports.push_back(Chain);
9350 #include "llvm/CodeGen/SelectionDAGISel.h"
9352 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9353 /// entry block, return true. This includes arguments used by switches, since
9354 /// the switch may expand into multiple basic blocks.
9355 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9356 // With FastISel active, we may be splitting blocks, so force creation
9357 // of virtual registers for all non-dead arguments.
9358 if (FastISel)
9359 return A->use_empty();
9361 const BasicBlock &Entry = A->getParent()->front();
9362 for (const User *U : A->users())
9363 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9364 return false; // Use not in entry block.
9366 return true;
9369 using ArgCopyElisionMapTy =
9370 DenseMap<const Argument *,
9371 std::pair<const AllocaInst *, const StoreInst *>>;
9373 /// Scan the entry block of the function in FuncInfo for arguments that look
9374 /// like copies into a local alloca. Record any copied arguments in
9375 /// ArgCopyElisionCandidates.
9376 static void
9377 findArgumentCopyElisionCandidates(const DataLayout &DL,
9378 FunctionLoweringInfo *FuncInfo,
9379 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9380 // Record the state of every static alloca used in the entry block. Argument
9381 // allocas are all used in the entry block, so we need approximately as many
9382 // entries as we have arguments.
9383 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9384 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9385 unsigned NumArgs = FuncInfo->Fn->arg_size();
9386 StaticAllocas.reserve(NumArgs * 2);
9388 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9389 if (!V)
9390 return nullptr;
9391 V = V->stripPointerCasts();
9392 const auto *AI = dyn_cast<AllocaInst>(V);
9393 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9394 return nullptr;
9395 auto Iter = StaticAllocas.insert({AI, Unknown});
9396 return &Iter.first->second;
9399 // Look for stores of arguments to static allocas. Look through bitcasts and
9400 // GEPs to handle type coercions, as long as the alloca is fully initialized
9401 // by the store. Any non-store use of an alloca escapes it and any subsequent
9402 // unanalyzed store might write it.
9403 // FIXME: Handle structs initialized with multiple stores.
9404 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9405 // Look for stores, and handle non-store uses conservatively.
9406 const auto *SI = dyn_cast<StoreInst>(&I);
9407 if (!SI) {
9408 // We will look through cast uses, so ignore them completely.
9409 if (I.isCast())
9410 continue;
9411 // Ignore debug info intrinsics, they don't escape or store to allocas.
9412 if (isa<DbgInfoIntrinsic>(I))
9413 continue;
9414 // This is an unknown instruction. Assume it escapes or writes to all
9415 // static alloca operands.
9416 for (const Use &U : I.operands()) {
9417 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9418 *Info = StaticAllocaInfo::Clobbered;
9420 continue;
9423 // If the stored value is a static alloca, mark it as escaped.
9424 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9425 *Info = StaticAllocaInfo::Clobbered;
9427 // Check if the destination is a static alloca.
9428 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9429 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9430 if (!Info)
9431 continue;
9432 const AllocaInst *AI = cast<AllocaInst>(Dst);
9434 // Skip allocas that have been initialized or clobbered.
9435 if (*Info != StaticAllocaInfo::Unknown)
9436 continue;
9438 // Check if the stored value is an argument, and that this store fully
9439 // initializes the alloca. Don't elide copies from the same argument twice.
9440 const Value *Val = SI->getValueOperand()->stripPointerCasts();
9441 const auto *Arg = dyn_cast<Argument>(Val);
9442 if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9443 Arg->getType()->isEmptyTy() ||
9444 DL.getTypeStoreSize(Arg->getType()) !=
9445 DL.getTypeAllocSize(AI->getAllocatedType()) ||
9446 ArgCopyElisionCandidates.count(Arg)) {
9447 *Info = StaticAllocaInfo::Clobbered;
9448 continue;
9451 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9452 << '\n');
9454 // Mark this alloca and store for argument copy elision.
9455 *Info = StaticAllocaInfo::Elidable;
9456 ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9458 // Stop scanning if we've seen all arguments. This will happen early in -O0
9459 // builds, which is useful, because -O0 builds have large entry blocks and
9460 // many allocas.
9461 if (ArgCopyElisionCandidates.size() == NumArgs)
9462 break;
9466 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9467 /// ArgVal is a load from a suitable fixed stack object.
9468 static void tryToElideArgumentCopy(
9469 FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9470 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9471 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9472 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9473 SDValue ArgVal, bool &ArgHasUses) {
9474 // Check if this is a load from a fixed stack object.
9475 auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9476 if (!LNode)
9477 return;
9478 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9479 if (!FINode)
9480 return;
9482 // Check that the fixed stack object is the right size and alignment.
9483 // Look at the alignment that the user wrote on the alloca instead of looking
9484 // at the stack object.
9485 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9486 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9487 const AllocaInst *AI = ArgCopyIter->second.first;
9488 int FixedIndex = FINode->getIndex();
9489 int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9490 int OldIndex = AllocaIndex;
9491 MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9492 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9493 LLVM_DEBUG(
9494 dbgs() << " argument copy elision failed due to bad fixed stack "
9495 "object size\n");
9496 return;
9498 unsigned RequiredAlignment = AI->getAlignment();
9499 if (!RequiredAlignment) {
9500 RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9501 AI->getAllocatedType());
9503 if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9504 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
9505 "greater than stack argument alignment ("
9506 << RequiredAlignment << " vs "
9507 << MFI.getObjectAlignment(FixedIndex) << ")\n");
9508 return;
9511 // Perform the elision. Delete the old stack object and replace its only use
9512 // in the variable info map. Mark the stack object as mutable.
9513 LLVM_DEBUG({
9514 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9515 << " Replacing frame index " << OldIndex << " with " << FixedIndex
9516 << '\n';
9518 MFI.RemoveStackObject(OldIndex);
9519 MFI.setIsImmutableObjectIndex(FixedIndex, false);
9520 AllocaIndex = FixedIndex;
9521 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9522 Chains.push_back(ArgVal.getValue(1));
9524 // Avoid emitting code for the store implementing the copy.
9525 const StoreInst *SI = ArgCopyIter->second.second;
9526 ElidedArgCopyInstrs.insert(SI);
9528 // Check for uses of the argument again so that we can avoid exporting ArgVal
9529 // if it is't used by anything other than the store.
9530 for (const Value *U : Arg.users()) {
9531 if (U != SI) {
9532 ArgHasUses = true;
9533 break;
9538 void SelectionDAGISel::LowerArguments(const Function &F) {
9539 SelectionDAG &DAG = SDB->DAG;
9540 SDLoc dl = SDB->getCurSDLoc();
9541 const DataLayout &DL = DAG.getDataLayout();
9542 SmallVector<ISD::InputArg, 16> Ins;
9544 if (!FuncInfo->CanLowerReturn) {
9545 // Put in an sret pointer parameter before all the other parameters.
9546 SmallVector<EVT, 1> ValueVTs;
9547 ComputeValueVTs(*TLI, DAG.getDataLayout(),
9548 F.getReturnType()->getPointerTo(
9549 DAG.getDataLayout().getAllocaAddrSpace()),
9550 ValueVTs);
9552 // NOTE: Assuming that a pointer will never break down to more than one VT
9553 // or one register.
9554 ISD::ArgFlagsTy Flags;
9555 Flags.setSRet();
9556 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9557 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9558 ISD::InputArg::NoArgIndex, 0);
9559 Ins.push_back(RetArg);
9562 // Look for stores of arguments to static allocas. Mark such arguments with a
9563 // flag to ask the target to give us the memory location of that argument if
9564 // available.
9565 ArgCopyElisionMapTy ArgCopyElisionCandidates;
9566 findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9568 // Set up the incoming argument description vector.
9569 for (const Argument &Arg : F.args()) {
9570 unsigned ArgNo = Arg.getArgNo();
9571 SmallVector<EVT, 4> ValueVTs;
9572 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9573 bool isArgValueUsed = !Arg.use_empty();
9574 unsigned PartBase = 0;
9575 Type *FinalType = Arg.getType();
9576 if (Arg.hasAttribute(Attribute::ByVal))
9577 FinalType = Arg.getParamByValType();
9578 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9579 FinalType, F.getCallingConv(), F.isVarArg());
9580 for (unsigned Value = 0, NumValues = ValueVTs.size();
9581 Value != NumValues; ++Value) {
9582 EVT VT = ValueVTs[Value];
9583 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9584 ISD::ArgFlagsTy Flags;
9586 // Certain targets (such as MIPS), may have a different ABI alignment
9587 // for a type depending on the context. Give the target a chance to
9588 // specify the alignment it wants.
9589 unsigned OriginalAlignment =
9590 TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9592 if (Arg.getType()->isPointerTy()) {
9593 Flags.setPointer();
9594 Flags.setPointerAddrSpace(
9595 cast<PointerType>(Arg.getType())->getAddressSpace());
9597 if (Arg.hasAttribute(Attribute::ZExt))
9598 Flags.setZExt();
9599 if (Arg.hasAttribute(Attribute::SExt))
9600 Flags.setSExt();
9601 if (Arg.hasAttribute(Attribute::InReg)) {
9602 // If we are using vectorcall calling convention, a structure that is
9603 // passed InReg - is surely an HVA
9604 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9605 isa<StructType>(Arg.getType())) {
9606 // The first value of a structure is marked
9607 if (0 == Value)
9608 Flags.setHvaStart();
9609 Flags.setHva();
9611 // Set InReg Flag
9612 Flags.setInReg();
9614 if (Arg.hasAttribute(Attribute::StructRet))
9615 Flags.setSRet();
9616 if (Arg.hasAttribute(Attribute::SwiftSelf))
9617 Flags.setSwiftSelf();
9618 if (Arg.hasAttribute(Attribute::SwiftError))
9619 Flags.setSwiftError();
9620 if (Arg.hasAttribute(Attribute::ByVal))
9621 Flags.setByVal();
9622 if (Arg.hasAttribute(Attribute::InAlloca)) {
9623 Flags.setInAlloca();
9624 // Set the byval flag for CCAssignFn callbacks that don't know about
9625 // inalloca. This way we can know how many bytes we should've allocated
9626 // and how many bytes a callee cleanup function will pop. If we port
9627 // inalloca to more targets, we'll have to add custom inalloca handling
9628 // in the various CC lowering callbacks.
9629 Flags.setByVal();
9631 if (F.getCallingConv() == CallingConv::X86_INTR) {
9632 // IA Interrupt passes frame (1st parameter) by value in the stack.
9633 if (ArgNo == 0)
9634 Flags.setByVal();
9636 if (Flags.isByVal() || Flags.isInAlloca()) {
9637 Type *ElementTy = Arg.getParamByValType();
9639 // For ByVal, size and alignment should be passed from FE. BE will
9640 // guess if this info is not there but there are cases it cannot get
9641 // right.
9642 unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9643 Flags.setByValSize(FrameSize);
9645 unsigned FrameAlign;
9646 if (Arg.getParamAlignment())
9647 FrameAlign = Arg.getParamAlignment();
9648 else
9649 FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9650 Flags.setByValAlign(FrameAlign);
9652 if (Arg.hasAttribute(Attribute::Nest))
9653 Flags.setNest();
9654 if (NeedsRegBlock)
9655 Flags.setInConsecutiveRegs();
9656 Flags.setOrigAlign(OriginalAlignment);
9657 if (ArgCopyElisionCandidates.count(&Arg))
9658 Flags.setCopyElisionCandidate();
9659 if (Arg.hasAttribute(Attribute::Returned))
9660 Flags.setReturned();
9662 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9663 *CurDAG->getContext(), F.getCallingConv(), VT);
9664 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9665 *CurDAG->getContext(), F.getCallingConv(), VT);
9666 for (unsigned i = 0; i != NumRegs; ++i) {
9667 ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9668 ArgNo, PartBase+i*RegisterVT.getStoreSize());
9669 if (NumRegs > 1 && i == 0)
9670 MyFlags.Flags.setSplit();
9671 // if it isn't first piece, alignment must be 1
9672 else if (i > 0) {
9673 MyFlags.Flags.setOrigAlign(1);
9674 if (i == NumRegs - 1)
9675 MyFlags.Flags.setSplitEnd();
9677 Ins.push_back(MyFlags);
9679 if (NeedsRegBlock && Value == NumValues - 1)
9680 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9681 PartBase += VT.getStoreSize();
9685 // Call the target to set up the argument values.
9686 SmallVector<SDValue, 8> InVals;
9687 SDValue NewRoot = TLI->LowerFormalArguments(
9688 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9690 // Verify that the target's LowerFormalArguments behaved as expected.
9691 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9692 "LowerFormalArguments didn't return a valid chain!");
9693 assert(InVals.size() == Ins.size() &&
9694 "LowerFormalArguments didn't emit the correct number of values!");
9695 LLVM_DEBUG({
9696 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9697 assert(InVals[i].getNode() &&
9698 "LowerFormalArguments emitted a null value!");
9699 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9700 "LowerFormalArguments emitted a value with the wrong type!");
9704 // Update the DAG with the new chain value resulting from argument lowering.
9705 DAG.setRoot(NewRoot);
9707 // Set up the argument values.
9708 unsigned i = 0;
9709 if (!FuncInfo->CanLowerReturn) {
9710 // Create a virtual register for the sret pointer, and put in a copy
9711 // from the sret argument into it.
9712 SmallVector<EVT, 1> ValueVTs;
9713 ComputeValueVTs(*TLI, DAG.getDataLayout(),
9714 F.getReturnType()->getPointerTo(
9715 DAG.getDataLayout().getAllocaAddrSpace()),
9716 ValueVTs);
9717 MVT VT = ValueVTs[0].getSimpleVT();
9718 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9719 Optional<ISD::NodeType> AssertOp = None;
9720 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9721 nullptr, F.getCallingConv(), AssertOp);
9723 MachineFunction& MF = SDB->DAG.getMachineFunction();
9724 MachineRegisterInfo& RegInfo = MF.getRegInfo();
9725 Register SRetReg =
9726 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9727 FuncInfo->DemoteRegister = SRetReg;
9728 NewRoot =
9729 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9730 DAG.setRoot(NewRoot);
9732 // i indexes lowered arguments. Bump it past the hidden sret argument.
9733 ++i;
9736 SmallVector<SDValue, 4> Chains;
9737 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9738 for (const Argument &Arg : F.args()) {
9739 SmallVector<SDValue, 4> ArgValues;
9740 SmallVector<EVT, 4> ValueVTs;
9741 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9742 unsigned NumValues = ValueVTs.size();
9743 if (NumValues == 0)
9744 continue;
9746 bool ArgHasUses = !Arg.use_empty();
9748 // Elide the copying store if the target loaded this argument from a
9749 // suitable fixed stack object.
9750 if (Ins[i].Flags.isCopyElisionCandidate()) {
9751 tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9752 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9753 InVals[i], ArgHasUses);
9756 // If this argument is unused then remember its value. It is used to generate
9757 // debugging information.
9758 bool isSwiftErrorArg =
9759 TLI->supportSwiftError() &&
9760 Arg.hasAttribute(Attribute::SwiftError);
9761 if (!ArgHasUses && !isSwiftErrorArg) {
9762 SDB->setUnusedArgValue(&Arg, InVals[i]);
9764 // Also remember any frame index for use in FastISel.
9765 if (FrameIndexSDNode *FI =
9766 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9767 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9770 for (unsigned Val = 0; Val != NumValues; ++Val) {
9771 EVT VT = ValueVTs[Val];
9772 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9773 F.getCallingConv(), VT);
9774 unsigned NumParts = TLI->getNumRegistersForCallingConv(
9775 *CurDAG->getContext(), F.getCallingConv(), VT);
9777 // Even an apparant 'unused' swifterror argument needs to be returned. So
9778 // we do generate a copy for it that can be used on return from the
9779 // function.
9780 if (ArgHasUses || isSwiftErrorArg) {
9781 Optional<ISD::NodeType> AssertOp;
9782 if (Arg.hasAttribute(Attribute::SExt))
9783 AssertOp = ISD::AssertSext;
9784 else if (Arg.hasAttribute(Attribute::ZExt))
9785 AssertOp = ISD::AssertZext;
9787 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9788 PartVT, VT, nullptr,
9789 F.getCallingConv(), AssertOp));
9792 i += NumParts;
9795 // We don't need to do anything else for unused arguments.
9796 if (ArgValues.empty())
9797 continue;
9799 // Note down frame index.
9800 if (FrameIndexSDNode *FI =
9801 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9802 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9804 SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9805 SDB->getCurSDLoc());
9807 SDB->setValue(&Arg, Res);
9808 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9809 // We want to associate the argument with the frame index, among
9810 // involved operands, that correspond to the lowest address. The
9811 // getCopyFromParts function, called earlier, is swapping the order of
9812 // the operands to BUILD_PAIR depending on endianness. The result of
9813 // that swapping is that the least significant bits of the argument will
9814 // be in the first operand of the BUILD_PAIR node, and the most
9815 // significant bits will be in the second operand.
9816 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9817 if (LoadSDNode *LNode =
9818 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9819 if (FrameIndexSDNode *FI =
9820 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9821 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9824 // Analyses past this point are naive and don't expect an assertion.
9825 if (Res.getOpcode() == ISD::AssertZext)
9826 Res = Res.getOperand(0);
9828 // Update the SwiftErrorVRegDefMap.
9829 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9830 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9831 if (Register::isVirtualRegister(Reg))
9832 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9833 Reg);
9836 // If this argument is live outside of the entry block, insert a copy from
9837 // wherever we got it to the vreg that other BB's will reference it as.
9838 if (Res.getOpcode() == ISD::CopyFromReg) {
9839 // If we can, though, try to skip creating an unnecessary vreg.
9840 // FIXME: This isn't very clean... it would be nice to make this more
9841 // general.
9842 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9843 if (Register::isVirtualRegister(Reg)) {
9844 FuncInfo->ValueMap[&Arg] = Reg;
9845 continue;
9848 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9849 FuncInfo->InitializeRegForValue(&Arg);
9850 SDB->CopyToExportRegsIfNeeded(&Arg);
9854 if (!Chains.empty()) {
9855 Chains.push_back(NewRoot);
9856 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9859 DAG.setRoot(NewRoot);
9861 assert(i == InVals.size() && "Argument register count mismatch!");
9863 // If any argument copy elisions occurred and we have debug info, update the
9864 // stale frame indices used in the dbg.declare variable info table.
9865 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9866 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9867 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9868 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9869 if (I != ArgCopyElisionFrameIndexMap.end())
9870 VI.Slot = I->second;
9874 // Finally, if the target has anything special to do, allow it to do so.
9875 EmitFunctionEntryCode();
9878 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
9879 /// ensure constants are generated when needed. Remember the virtual registers
9880 /// that need to be added to the Machine PHI nodes as input. We cannot just
9881 /// directly add them, because expansion might result in multiple MBB's for one
9882 /// BB. As such, the start of the BB might correspond to a different MBB than
9883 /// the end.
9884 void
9885 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9886 const Instruction *TI = LLVMBB->getTerminator();
9888 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9890 // Check PHI nodes in successors that expect a value to be available from this
9891 // block.
9892 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9893 const BasicBlock *SuccBB = TI->getSuccessor(succ);
9894 if (!isa<PHINode>(SuccBB->begin())) continue;
9895 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9897 // If this terminator has multiple identical successors (common for
9898 // switches), only handle each succ once.
9899 if (!SuccsHandled.insert(SuccMBB).second)
9900 continue;
9902 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9904 // At this point we know that there is a 1-1 correspondence between LLVM PHI
9905 // nodes and Machine PHI nodes, but the incoming operands have not been
9906 // emitted yet.
9907 for (const PHINode &PN : SuccBB->phis()) {
9908 // Ignore dead phi's.
9909 if (PN.use_empty())
9910 continue;
9912 // Skip empty types
9913 if (PN.getType()->isEmptyTy())
9914 continue;
9916 unsigned Reg;
9917 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9919 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9920 unsigned &RegOut = ConstantsOut[C];
9921 if (RegOut == 0) {
9922 RegOut = FuncInfo.CreateRegs(C);
9923 CopyValueToVirtualRegister(C, RegOut);
9925 Reg = RegOut;
9926 } else {
9927 DenseMap<const Value *, unsigned>::iterator I =
9928 FuncInfo.ValueMap.find(PHIOp);
9929 if (I != FuncInfo.ValueMap.end())
9930 Reg = I->second;
9931 else {
9932 assert(isa<AllocaInst>(PHIOp) &&
9933 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9934 "Didn't codegen value into a register!??");
9935 Reg = FuncInfo.CreateRegs(PHIOp);
9936 CopyValueToVirtualRegister(PHIOp, Reg);
9940 // Remember that this register needs to added to the machine PHI node as
9941 // the input for this MBB.
9942 SmallVector<EVT, 4> ValueVTs;
9943 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9944 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9945 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9946 EVT VT = ValueVTs[vti];
9947 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9948 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9949 FuncInfo.PHINodesToUpdate.push_back(
9950 std::make_pair(&*MBBI++, Reg + i));
9951 Reg += NumRegisters;
9956 ConstantsOut.clear();
9959 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9960 /// is 0.
9961 MachineBasicBlock *
9962 SelectionDAGBuilder::StackProtectorDescriptor::
9963 AddSuccessorMBB(const BasicBlock *BB,
9964 MachineBasicBlock *ParentMBB,
9965 bool IsLikely,
9966 MachineBasicBlock *SuccMBB) {
9967 // If SuccBB has not been created yet, create it.
9968 if (!SuccMBB) {
9969 MachineFunction *MF = ParentMBB->getParent();
9970 MachineFunction::iterator BBI(ParentMBB);
9971 SuccMBB = MF->CreateMachineBasicBlock(BB);
9972 MF->insert(++BBI, SuccMBB);
9974 // Add it as a successor of ParentMBB.
9975 ParentMBB->addSuccessor(
9976 SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9977 return SuccMBB;
9980 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9981 MachineFunction::iterator I(MBB);
9982 if (++I == FuncInfo.MF->end())
9983 return nullptr;
9984 return &*I;
9987 /// During lowering new call nodes can be created (such as memset, etc.).
9988 /// Those will become new roots of the current DAG, but complications arise
9989 /// when they are tail calls. In such cases, the call lowering will update
9990 /// the root, but the builder still needs to know that a tail call has been
9991 /// lowered in order to avoid generating an additional return.
9992 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9993 // If the node is null, we do have a tail call.
9994 if (MaybeTC.getNode() != nullptr)
9995 DAG.setRoot(MaybeTC);
9996 else
9997 HasTailCall = true;
10000 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10001 MachineBasicBlock *SwitchMBB,
10002 MachineBasicBlock *DefaultMBB) {
10003 MachineFunction *CurMF = FuncInfo.MF;
10004 MachineBasicBlock *NextMBB = nullptr;
10005 MachineFunction::iterator BBI(W.MBB);
10006 if (++BBI != FuncInfo.MF->end())
10007 NextMBB = &*BBI;
10009 unsigned Size = W.LastCluster - W.FirstCluster + 1;
10011 BranchProbabilityInfo *BPI = FuncInfo.BPI;
10013 if (Size == 2 && W.MBB == SwitchMBB) {
10014 // If any two of the cases has the same destination, and if one value
10015 // is the same as the other, but has one bit unset that the other has set,
10016 // use bit manipulation to do two compares at once. For example:
10017 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10018 // TODO: This could be extended to merge any 2 cases in switches with 3
10019 // cases.
10020 // TODO: Handle cases where W.CaseBB != SwitchBB.
10021 CaseCluster &Small = *W.FirstCluster;
10022 CaseCluster &Big = *W.LastCluster;
10024 if (Small.Low == Small.High && Big.Low == Big.High &&
10025 Small.MBB == Big.MBB) {
10026 const APInt &SmallValue = Small.Low->getValue();
10027 const APInt &BigValue = Big.Low->getValue();
10029 // Check that there is only one bit different.
10030 APInt CommonBit = BigValue ^ SmallValue;
10031 if (CommonBit.isPowerOf2()) {
10032 SDValue CondLHS = getValue(Cond);
10033 EVT VT = CondLHS.getValueType();
10034 SDLoc DL = getCurSDLoc();
10036 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10037 DAG.getConstant(CommonBit, DL, VT));
10038 SDValue Cond = DAG.getSetCC(
10039 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10040 ISD::SETEQ);
10042 // Update successor info.
10043 // Both Small and Big will jump to Small.BB, so we sum up the
10044 // probabilities.
10045 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10046 if (BPI)
10047 addSuccessorWithProb(
10048 SwitchMBB, DefaultMBB,
10049 // The default destination is the first successor in IR.
10050 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10051 else
10052 addSuccessorWithProb(SwitchMBB, DefaultMBB);
10054 // Insert the true branch.
10055 SDValue BrCond =
10056 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10057 DAG.getBasicBlock(Small.MBB));
10058 // Insert the false branch.
10059 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10060 DAG.getBasicBlock(DefaultMBB));
10062 DAG.setRoot(BrCond);
10063 return;
10068 if (TM.getOptLevel() != CodeGenOpt::None) {
10069 // Here, we order cases by probability so the most likely case will be
10070 // checked first. However, two clusters can have the same probability in
10071 // which case their relative ordering is non-deterministic. So we use Low
10072 // as a tie-breaker as clusters are guaranteed to never overlap.
10073 llvm::sort(W.FirstCluster, W.LastCluster + 1,
10074 [](const CaseCluster &a, const CaseCluster &b) {
10075 return a.Prob != b.Prob ?
10076 a.Prob > b.Prob :
10077 a.Low->getValue().slt(b.Low->getValue());
10080 // Rearrange the case blocks so that the last one falls through if possible
10081 // without changing the order of probabilities.
10082 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10083 --I;
10084 if (I->Prob > W.LastCluster->Prob)
10085 break;
10086 if (I->Kind == CC_Range && I->MBB == NextMBB) {
10087 std::swap(*I, *W.LastCluster);
10088 break;
10093 // Compute total probability.
10094 BranchProbability DefaultProb = W.DefaultProb;
10095 BranchProbability UnhandledProbs = DefaultProb;
10096 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10097 UnhandledProbs += I->Prob;
10099 MachineBasicBlock *CurMBB = W.MBB;
10100 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10101 bool FallthroughUnreachable = false;
10102 MachineBasicBlock *Fallthrough;
10103 if (I == W.LastCluster) {
10104 // For the last cluster, fall through to the default destination.
10105 Fallthrough = DefaultMBB;
10106 FallthroughUnreachable = isa<UnreachableInst>(
10107 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10108 } else {
10109 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10110 CurMF->insert(BBI, Fallthrough);
10111 // Put Cond in a virtual register to make it available from the new blocks.
10112 ExportFromCurrentBlock(Cond);
10114 UnhandledProbs -= I->Prob;
10116 switch (I->Kind) {
10117 case CC_JumpTable: {
10118 // FIXME: Optimize away range check based on pivot comparisons.
10119 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10120 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10122 // The jump block hasn't been inserted yet; insert it here.
10123 MachineBasicBlock *JumpMBB = JT->MBB;
10124 CurMF->insert(BBI, JumpMBB);
10126 auto JumpProb = I->Prob;
10127 auto FallthroughProb = UnhandledProbs;
10129 // If the default statement is a target of the jump table, we evenly
10130 // distribute the default probability to successors of CurMBB. Also
10131 // update the probability on the edge from JumpMBB to Fallthrough.
10132 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10133 SE = JumpMBB->succ_end();
10134 SI != SE; ++SI) {
10135 if (*SI == DefaultMBB) {
10136 JumpProb += DefaultProb / 2;
10137 FallthroughProb -= DefaultProb / 2;
10138 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10139 JumpMBB->normalizeSuccProbs();
10140 break;
10144 if (FallthroughUnreachable) {
10145 // Skip the range check if the fallthrough block is unreachable.
10146 JTH->OmitRangeCheck = true;
10149 if (!JTH->OmitRangeCheck)
10150 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10151 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10152 CurMBB->normalizeSuccProbs();
10154 // The jump table header will be inserted in our current block, do the
10155 // range check, and fall through to our fallthrough block.
10156 JTH->HeaderBB = CurMBB;
10157 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10159 // If we're in the right place, emit the jump table header right now.
10160 if (CurMBB == SwitchMBB) {
10161 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10162 JTH->Emitted = true;
10164 break;
10166 case CC_BitTests: {
10167 // FIXME: If Fallthrough is unreachable, skip the range check.
10169 // FIXME: Optimize away range check based on pivot comparisons.
10170 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10172 // The bit test blocks haven't been inserted yet; insert them here.
10173 for (BitTestCase &BTC : BTB->Cases)
10174 CurMF->insert(BBI, BTC.ThisBB);
10176 // Fill in fields of the BitTestBlock.
10177 BTB->Parent = CurMBB;
10178 BTB->Default = Fallthrough;
10180 BTB->DefaultProb = UnhandledProbs;
10181 // If the cases in bit test don't form a contiguous range, we evenly
10182 // distribute the probability on the edge to Fallthrough to two
10183 // successors of CurMBB.
10184 if (!BTB->ContiguousRange) {
10185 BTB->Prob += DefaultProb / 2;
10186 BTB->DefaultProb -= DefaultProb / 2;
10189 // If we're in the right place, emit the bit test header right now.
10190 if (CurMBB == SwitchMBB) {
10191 visitBitTestHeader(*BTB, SwitchMBB);
10192 BTB->Emitted = true;
10194 break;
10196 case CC_Range: {
10197 const Value *RHS, *LHS, *MHS;
10198 ISD::CondCode CC;
10199 if (I->Low == I->High) {
10200 // Check Cond == I->Low.
10201 CC = ISD::SETEQ;
10202 LHS = Cond;
10203 RHS=I->Low;
10204 MHS = nullptr;
10205 } else {
10206 // Check I->Low <= Cond <= I->High.
10207 CC = ISD::SETLE;
10208 LHS = I->Low;
10209 MHS = Cond;
10210 RHS = I->High;
10213 // If Fallthrough is unreachable, fold away the comparison.
10214 if (FallthroughUnreachable)
10215 CC = ISD::SETTRUE;
10217 // The false probability is the sum of all unhandled cases.
10218 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10219 getCurSDLoc(), I->Prob, UnhandledProbs);
10221 if (CurMBB == SwitchMBB)
10222 visitSwitchCase(CB, SwitchMBB);
10223 else
10224 SL->SwitchCases.push_back(CB);
10226 break;
10229 CurMBB = Fallthrough;
10233 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10234 CaseClusterIt First,
10235 CaseClusterIt Last) {
10236 return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10237 if (X.Prob != CC.Prob)
10238 return X.Prob > CC.Prob;
10240 // Ties are broken by comparing the case value.
10241 return X.Low->getValue().slt(CC.Low->getValue());
10245 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10246 const SwitchWorkListItem &W,
10247 Value *Cond,
10248 MachineBasicBlock *SwitchMBB) {
10249 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10250 "Clusters not sorted?");
10252 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10254 // Balance the tree based on branch probabilities to create a near-optimal (in
10255 // terms of search time given key frequency) binary search tree. See e.g. Kurt
10256 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10257 CaseClusterIt LastLeft = W.FirstCluster;
10258 CaseClusterIt FirstRight = W.LastCluster;
10259 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10260 auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10262 // Move LastLeft and FirstRight towards each other from opposite directions to
10263 // find a partitioning of the clusters which balances the probability on both
10264 // sides. If LeftProb and RightProb are equal, alternate which side is
10265 // taken to ensure 0-probability nodes are distributed evenly.
10266 unsigned I = 0;
10267 while (LastLeft + 1 < FirstRight) {
10268 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10269 LeftProb += (++LastLeft)->Prob;
10270 else
10271 RightProb += (--FirstRight)->Prob;
10272 I++;
10275 while (true) {
10276 // Our binary search tree differs from a typical BST in that ours can have up
10277 // to three values in each leaf. The pivot selection above doesn't take that
10278 // into account, which means the tree might require more nodes and be less
10279 // efficient. We compensate for this here.
10281 unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10282 unsigned NumRight = W.LastCluster - FirstRight + 1;
10284 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10285 // If one side has less than 3 clusters, and the other has more than 3,
10286 // consider taking a cluster from the other side.
10288 if (NumLeft < NumRight) {
10289 // Consider moving the first cluster on the right to the left side.
10290 CaseCluster &CC = *FirstRight;
10291 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10292 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10293 if (LeftSideRank <= RightSideRank) {
10294 // Moving the cluster to the left does not demote it.
10295 ++LastLeft;
10296 ++FirstRight;
10297 continue;
10299 } else {
10300 assert(NumRight < NumLeft);
10301 // Consider moving the last element on the left to the right side.
10302 CaseCluster &CC = *LastLeft;
10303 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10304 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10305 if (RightSideRank <= LeftSideRank) {
10306 // Moving the cluster to the right does not demot it.
10307 --LastLeft;
10308 --FirstRight;
10309 continue;
10313 break;
10316 assert(LastLeft + 1 == FirstRight);
10317 assert(LastLeft >= W.FirstCluster);
10318 assert(FirstRight <= W.LastCluster);
10320 // Use the first element on the right as pivot since we will make less-than
10321 // comparisons against it.
10322 CaseClusterIt PivotCluster = FirstRight;
10323 assert(PivotCluster > W.FirstCluster);
10324 assert(PivotCluster <= W.LastCluster);
10326 CaseClusterIt FirstLeft = W.FirstCluster;
10327 CaseClusterIt LastRight = W.LastCluster;
10329 const ConstantInt *Pivot = PivotCluster->Low;
10331 // New blocks will be inserted immediately after the current one.
10332 MachineFunction::iterator BBI(W.MBB);
10333 ++BBI;
10335 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10336 // we can branch to its destination directly if it's squeezed exactly in
10337 // between the known lower bound and Pivot - 1.
10338 MachineBasicBlock *LeftMBB;
10339 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10340 FirstLeft->Low == W.GE &&
10341 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10342 LeftMBB = FirstLeft->MBB;
10343 } else {
10344 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10345 FuncInfo.MF->insert(BBI, LeftMBB);
10346 WorkList.push_back(
10347 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10348 // Put Cond in a virtual register to make it available from the new blocks.
10349 ExportFromCurrentBlock(Cond);
10352 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10353 // single cluster, RHS.Low == Pivot, and we can branch to its destination
10354 // directly if RHS.High equals the current upper bound.
10355 MachineBasicBlock *RightMBB;
10356 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10357 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10358 RightMBB = FirstRight->MBB;
10359 } else {
10360 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10361 FuncInfo.MF->insert(BBI, RightMBB);
10362 WorkList.push_back(
10363 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10364 // Put Cond in a virtual register to make it available from the new blocks.
10365 ExportFromCurrentBlock(Cond);
10368 // Create the CaseBlock record that will be used to lower the branch.
10369 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10370 getCurSDLoc(), LeftProb, RightProb);
10372 if (W.MBB == SwitchMBB)
10373 visitSwitchCase(CB, SwitchMBB);
10374 else
10375 SL->SwitchCases.push_back(CB);
10378 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10379 // from the swith statement.
10380 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10381 BranchProbability PeeledCaseProb) {
10382 if (PeeledCaseProb == BranchProbability::getOne())
10383 return BranchProbability::getZero();
10384 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10386 uint32_t Numerator = CaseProb.getNumerator();
10387 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10388 return BranchProbability(Numerator, std::max(Numerator, Denominator));
10391 // Try to peel the top probability case if it exceeds the threshold.
10392 // Return current MachineBasicBlock for the switch statement if the peeling
10393 // does not occur.
10394 // If the peeling is performed, return the newly created MachineBasicBlock
10395 // for the peeled switch statement. Also update Clusters to remove the peeled
10396 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10397 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10398 const SwitchInst &SI, CaseClusterVector &Clusters,
10399 BranchProbability &PeeledCaseProb) {
10400 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10401 // Don't perform if there is only one cluster or optimizing for size.
10402 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10403 TM.getOptLevel() == CodeGenOpt::None ||
10404 SwitchMBB->getParent()->getFunction().hasMinSize())
10405 return SwitchMBB;
10407 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10408 unsigned PeeledCaseIndex = 0;
10409 bool SwitchPeeled = false;
10410 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10411 CaseCluster &CC = Clusters[Index];
10412 if (CC.Prob < TopCaseProb)
10413 continue;
10414 TopCaseProb = CC.Prob;
10415 PeeledCaseIndex = Index;
10416 SwitchPeeled = true;
10418 if (!SwitchPeeled)
10419 return SwitchMBB;
10421 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10422 << TopCaseProb << "\n");
10424 // Record the MBB for the peeled switch statement.
10425 MachineFunction::iterator BBI(SwitchMBB);
10426 ++BBI;
10427 MachineBasicBlock *PeeledSwitchMBB =
10428 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10429 FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10431 ExportFromCurrentBlock(SI.getCondition());
10432 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10433 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10434 nullptr, nullptr, TopCaseProb.getCompl()};
10435 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10437 Clusters.erase(PeeledCaseIt);
10438 for (CaseCluster &CC : Clusters) {
10439 LLVM_DEBUG(
10440 dbgs() << "Scale the probablity for one cluster, before scaling: "
10441 << CC.Prob << "\n");
10442 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10443 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10445 PeeledCaseProb = TopCaseProb;
10446 return PeeledSwitchMBB;
10449 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10450 // Extract cases from the switch.
10451 BranchProbabilityInfo *BPI = FuncInfo.BPI;
10452 CaseClusterVector Clusters;
10453 Clusters.reserve(SI.getNumCases());
10454 for (auto I : SI.cases()) {
10455 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10456 const ConstantInt *CaseVal = I.getCaseValue();
10457 BranchProbability Prob =
10458 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10459 : BranchProbability(1, SI.getNumCases() + 1);
10460 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10463 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10465 // Cluster adjacent cases with the same destination. We do this at all
10466 // optimization levels because it's cheap to do and will make codegen faster
10467 // if there are many clusters.
10468 sortAndRangeify(Clusters);
10470 // The branch probablity of the peeled case.
10471 BranchProbability PeeledCaseProb = BranchProbability::getZero();
10472 MachineBasicBlock *PeeledSwitchMBB =
10473 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10475 // If there is only the default destination, jump there directly.
10476 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10477 if (Clusters.empty()) {
10478 assert(PeeledSwitchMBB == SwitchMBB);
10479 SwitchMBB->addSuccessor(DefaultMBB);
10480 if (DefaultMBB != NextBlock(SwitchMBB)) {
10481 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10482 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10484 return;
10487 SL->findJumpTables(Clusters, &SI, DefaultMBB);
10488 SL->findBitTestClusters(Clusters, &SI);
10490 LLVM_DEBUG({
10491 dbgs() << "Case clusters: ";
10492 for (const CaseCluster &C : Clusters) {
10493 if (C.Kind == CC_JumpTable)
10494 dbgs() << "JT:";
10495 if (C.Kind == CC_BitTests)
10496 dbgs() << "BT:";
10498 C.Low->getValue().print(dbgs(), true);
10499 if (C.Low != C.High) {
10500 dbgs() << '-';
10501 C.High->getValue().print(dbgs(), true);
10503 dbgs() << ' ';
10505 dbgs() << '\n';
10508 assert(!Clusters.empty());
10509 SwitchWorkList WorkList;
10510 CaseClusterIt First = Clusters.begin();
10511 CaseClusterIt Last = Clusters.end() - 1;
10512 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10513 // Scale the branchprobability for DefaultMBB if the peel occurs and
10514 // DefaultMBB is not replaced.
10515 if (PeeledCaseProb != BranchProbability::getZero() &&
10516 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10517 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10518 WorkList.push_back(
10519 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10521 while (!WorkList.empty()) {
10522 SwitchWorkListItem W = WorkList.back();
10523 WorkList.pop_back();
10524 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10526 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10527 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10528 // For optimized builds, lower large range as a balanced binary tree.
10529 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10530 continue;
10533 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);