Bug Summary

File:build/source/llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1138, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SelectionDAGBuilder.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen/SelectionDAG -I /build/source/llvm/lib/CodeGen/SelectionDAG -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1683717183 -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp

/build/source/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp

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.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SelectionDAGBuilder.h"
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
25#include "llvm/Analysis/ConstantFolding.h"
26#include "llvm/Analysis/Loads.h"
27#include "llvm/Analysis/MemoryLocation.h"
28#include "llvm/Analysis/TargetLibraryInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
30#include "llvm/Analysis/VectorUtils.h"
31#include "llvm/CodeGen/Analysis.h"
32#include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
33#include "llvm/CodeGen/CodeGenCommonISel.h"
34#include "llvm/CodeGen/FunctionLoweringInfo.h"
35#include "llvm/CodeGen/GCMetadata.h"
36#include "llvm/CodeGen/MachineBasicBlock.h"
37#include "llvm/CodeGen/MachineFrameInfo.h"
38#include "llvm/CodeGen/MachineFunction.h"
39#include "llvm/CodeGen/MachineInstrBuilder.h"
40#include "llvm/CodeGen/MachineInstrBundleIterator.h"
41#include "llvm/CodeGen/MachineMemOperand.h"
42#include "llvm/CodeGen/MachineModuleInfo.h"
43#include "llvm/CodeGen/MachineOperand.h"
44#include "llvm/CodeGen/MachineRegisterInfo.h"
45#include "llvm/CodeGen/RuntimeLibcalls.h"
46#include "llvm/CodeGen/SelectionDAG.h"
47#include "llvm/CodeGen/SelectionDAGTargetInfo.h"
48#include "llvm/CodeGen/StackMaps.h"
49#include "llvm/CodeGen/SwiftErrorValueTracking.h"
50#include "llvm/CodeGen/TargetFrameLowering.h"
51#include "llvm/CodeGen/TargetInstrInfo.h"
52#include "llvm/CodeGen/TargetOpcodes.h"
53#include "llvm/CodeGen/TargetRegisterInfo.h"
54#include "llvm/CodeGen/TargetSubtargetInfo.h"
55#include "llvm/CodeGen/WinEHFuncInfo.h"
56#include "llvm/IR/Argument.h"
57#include "llvm/IR/Attributes.h"
58#include "llvm/IR/BasicBlock.h"
59#include "llvm/IR/CFG.h"
60#include "llvm/IR/CallingConv.h"
61#include "llvm/IR/Constant.h"
62#include "llvm/IR/ConstantRange.h"
63#include "llvm/IR/Constants.h"
64#include "llvm/IR/DataLayout.h"
65#include "llvm/IR/DebugInfo.h"
66#include "llvm/IR/DebugInfoMetadata.h"
67#include "llvm/IR/DerivedTypes.h"
68#include "llvm/IR/DiagnosticInfo.h"
69#include "llvm/IR/EHPersonalities.h"
70#include "llvm/IR/Function.h"
71#include "llvm/IR/GetElementPtrTypeIterator.h"
72#include "llvm/IR/InlineAsm.h"
73#include "llvm/IR/InstrTypes.h"
74#include "llvm/IR/Instructions.h"
75#include "llvm/IR/IntrinsicInst.h"
76#include "llvm/IR/Intrinsics.h"
77#include "llvm/IR/IntrinsicsAArch64.h"
78#include "llvm/IR/IntrinsicsWebAssembly.h"
79#include "llvm/IR/LLVMContext.h"
80#include "llvm/IR/Metadata.h"
81#include "llvm/IR/Module.h"
82#include "llvm/IR/Operator.h"
83#include "llvm/IR/PatternMatch.h"
84#include "llvm/IR/Statepoint.h"
85#include "llvm/IR/Type.h"
86#include "llvm/IR/User.h"
87#include "llvm/IR/Value.h"
88#include "llvm/MC/MCContext.h"
89#include "llvm/Support/AtomicOrdering.h"
90#include "llvm/Support/Casting.h"
91#include "llvm/Support/CommandLine.h"
92#include "llvm/Support/Compiler.h"
93#include "llvm/Support/Debug.h"
94#include "llvm/Support/MathExtras.h"
95#include "llvm/Support/raw_ostream.h"
96#include "llvm/Target/TargetIntrinsicInfo.h"
97#include "llvm/Target/TargetMachine.h"
98#include "llvm/Target/TargetOptions.h"
99#include "llvm/TargetParser/Triple.h"
100#include "llvm/Transforms/Utils/Local.h"
101#include <cstddef>
102#include <iterator>
103#include <limits>
104#include <optional>
105#include <tuple>
106
107using namespace llvm;
108using namespace PatternMatch;
109using namespace SwitchCG;
110
111#define DEBUG_TYPE"isel" "isel"
112
113/// LimitFloatPrecision - Generate low-precision inline sequences for
114/// some float libcalls (6, 8 or 12 bits).
115static unsigned LimitFloatPrecision;
116
117static cl::opt<bool>
118 InsertAssertAlign("insert-assert-align", cl::init(true),
119 cl::desc("Insert the experimental `assertalign` node."),
120 cl::ReallyHidden);
121
122static cl::opt<unsigned, true>
123 LimitFPPrecision("limit-float-precision",
124 cl::desc("Generate low-precision inline sequences "
125 "for some float libcalls"),
126 cl::location(LimitFloatPrecision), cl::Hidden,
127 cl::init(0));
128
129static cl::opt<unsigned> SwitchPeelThreshold(
130 "switch-peel-threshold", cl::Hidden, cl::init(66),
131 cl::desc("Set the case probability threshold for peeling the case from a "
132 "switch statement. A value greater than 100 will void this "
133 "optimization"));
134
135// Limit the width of DAG chains. This is important in general to prevent
136// DAG-based analysis from blowing up. For example, alias analysis and
137// load clustering may not complete in reasonable time. It is difficult to
138// recognize and avoid this situation within each individual analysis, and
139// future analyses are likely to have the same behavior. Limiting DAG width is
140// the safe approach and will be especially important with global DAGs.
141//
142// MaxParallelChains default is arbitrarily high to avoid affecting
143// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
144// sequence over this should have been converted to llvm.memcpy by the
145// frontend. It is easy to induce this behavior with .ll code such as:
146// %buffer = alloca [4096 x i8]
147// %data = load [4096 x i8]* %argPtr
148// store [4096 x i8] %data, [4096 x i8]* %buffer
149static const unsigned MaxParallelChains = 64;
150
151static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
152 const SDValue *Parts, unsigned NumParts,
153 MVT PartVT, EVT ValueVT, const Value *V,
154 std::optional<CallingConv::ID> CC);
155
156/// getCopyFromParts - Create a value that contains the specified legal parts
157/// combined into the value they represent. If the parts combine to a type
158/// larger than ValueVT then AssertOp can be used to specify whether the extra
159/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
160/// (ISD::AssertSext).
161static SDValue
162getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
163 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
164 std::optional<CallingConv::ID> CC = std::nullopt,
165 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
166 // Let the target assemble the parts if it wants to
167 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
168 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
169 PartVT, ValueVT, CC))
170 return Val;
171
172 if (ValueVT.isVector())
173 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
174 CC);
175
176 assert(NumParts > 0 && "No parts to assemble!")(static_cast <bool> (NumParts > 0 && "No parts to assemble!"
) ? void (0) : __assert_fail ("NumParts > 0 && \"No parts to assemble!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 176
, __extension__ __PRETTY_FUNCTION__))
;
177 SDValue Val = Parts[0];
178
179 if (NumParts > 1) {
180 // Assemble the value from multiple parts.
181 if (ValueVT.isInteger()) {
182 unsigned PartBits = PartVT.getSizeInBits();
183 unsigned ValueBits = ValueVT.getSizeInBits();
184
185 // Assemble the power of 2 part.
186 unsigned RoundParts = llvm::bit_floor(NumParts);
187 unsigned RoundBits = PartBits * RoundParts;
188 EVT RoundVT = RoundBits == ValueBits ?
189 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
190 SDValue Lo, Hi;
191
192 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
193
194 if (RoundParts > 2) {
195 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
196 PartVT, HalfVT, V);
197 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
198 RoundParts / 2, PartVT, HalfVT, V);
199 } else {
200 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
201 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
202 }
203
204 if (DAG.getDataLayout().isBigEndian())
205 std::swap(Lo, Hi);
206
207 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
208
209 if (RoundParts < NumParts) {
210 // Assemble the trailing non-power-of-2 part.
211 unsigned OddParts = NumParts - RoundParts;
212 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
213 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
214 OddVT, V, CC);
215
216 // Combine the round and odd parts.
217 Lo = Val;
218 if (DAG.getDataLayout().isBigEndian())
219 std::swap(Lo, Hi);
220 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
221 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
222 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
223 DAG.getConstant(Lo.getValueSizeInBits(), DL,
224 TLI.getShiftAmountTy(
225 TotalVT, DAG.getDataLayout())));
226 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
227 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
228 }
229 } else if (PartVT.isFloatingPoint()) {
230 // FP split into multiple FP parts (for ppcf128)
231 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&(static_cast <bool> (ValueVT == EVT(MVT::ppcf128) &&
PartVT == MVT::f64 && "Unexpected split") ? void (0)
: __assert_fail ("ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && \"Unexpected split\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 232
, __extension__ __PRETTY_FUNCTION__))
232 "Unexpected split")(static_cast <bool> (ValueVT == EVT(MVT::ppcf128) &&
PartVT == MVT::f64 && "Unexpected split") ? void (0)
: __assert_fail ("ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 && \"Unexpected split\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 232
, __extension__ __PRETTY_FUNCTION__))
;
233 SDValue Lo, Hi;
234 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
235 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
236 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
237 std::swap(Lo, Hi);
238 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
239 } else {
240 // FP split into integer parts (soft fp)
241 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&(static_cast <bool> (ValueVT.isFloatingPoint() &&
PartVT.isInteger() && !PartVT.isVector() && "Unexpected split"
) ? void (0) : __assert_fail ("ValueVT.isFloatingPoint() && PartVT.isInteger() && !PartVT.isVector() && \"Unexpected split\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 242
, __extension__ __PRETTY_FUNCTION__))
242 !PartVT.isVector() && "Unexpected split")(static_cast <bool> (ValueVT.isFloatingPoint() &&
PartVT.isInteger() && !PartVT.isVector() && "Unexpected split"
) ? void (0) : __assert_fail ("ValueVT.isFloatingPoint() && PartVT.isInteger() && !PartVT.isVector() && \"Unexpected split\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 242
, __extension__ __PRETTY_FUNCTION__))
;
243 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
244 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
245 }
246 }
247
248 // There is now one part, held in Val. Correct it to match ValueVT.
249 // PartEVT is the type of the register class that holds the value.
250 // ValueVT is the type of the inline asm operation.
251 EVT PartEVT = Val.getValueType();
252
253 if (PartEVT == ValueVT)
254 return Val;
255
256 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
257 ValueVT.bitsLT(PartEVT)) {
258 // For an FP value in an integer part, we need to truncate to the right
259 // width first.
260 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
261 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
262 }
263
264 // Handle types that have the same size.
265 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
266 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
267
268 // Handle types with different sizes.
269 if (PartEVT.isInteger() && ValueVT.isInteger()) {
270 if (ValueVT.bitsLT(PartEVT)) {
271 // For a truncate, see if we have any information to
272 // indicate whether the truncated bits will always be
273 // zero or sign-extension.
274 if (AssertOp)
275 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
276 DAG.getValueType(ValueVT));
277 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
278 }
279 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
280 }
281
282 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
283 // FP_ROUND's are always exact here.
284 if (ValueVT.bitsLT(Val.getValueType()))
285 return DAG.getNode(
286 ISD::FP_ROUND, DL, ValueVT, Val,
287 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
288
289 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
290 }
291
292 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
293 // then truncating.
294 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
295 ValueVT.bitsLT(PartEVT)) {
296 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
297 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
298 }
299
300 report_fatal_error("Unknown mismatch in getCopyFromParts!");
301}
302
303static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
304 const Twine &ErrMsg) {
305 const Instruction *I = dyn_cast_or_null<Instruction>(V);
306 if (!V)
307 return Ctx.emitError(ErrMsg);
308
309 const char *AsmError = ", possible invalid constraint for vector type";
310 if (const CallInst *CI = dyn_cast<CallInst>(I))
311 if (CI->isInlineAsm())
312 return Ctx.emitError(I, ErrMsg + AsmError);
313
314 return Ctx.emitError(I, ErrMsg);
315}
316
317/// getCopyFromPartsVector - Create a value that contains the specified legal
318/// parts combined into the value they represent. If the parts combine to a
319/// type larger than ValueVT then AssertOp can be used to specify whether the
320/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
321/// ValueVT (ISD::AssertSext).
322static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
323 const SDValue *Parts, unsigned NumParts,
324 MVT PartVT, EVT ValueVT, const Value *V,
325 std::optional<CallingConv::ID> CallConv) {
326 assert(ValueVT.isVector() && "Not a vector value")(static_cast <bool> (ValueVT.isVector() && "Not a vector value"
) ? void (0) : __assert_fail ("ValueVT.isVector() && \"Not a vector value\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 326
, __extension__ __PRETTY_FUNCTION__))
;
327 assert(NumParts > 0 && "No parts to assemble!")(static_cast <bool> (NumParts > 0 && "No parts to assemble!"
) ? void (0) : __assert_fail ("NumParts > 0 && \"No parts to assemble!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 327
, __extension__ __PRETTY_FUNCTION__))
;
328 const bool IsABIRegCopy = CallConv.has_value();
329
330 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
331 SDValue Val = Parts[0];
332
333 // Handle a multi-element vector.
334 if (NumParts > 1) {
335 EVT IntermediateVT;
336 MVT RegisterVT;
337 unsigned NumIntermediates;
338 unsigned NumRegs;
339
340 if (IsABIRegCopy) {
341 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
342 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
343 NumIntermediates, RegisterVT);
344 } else {
345 NumRegs =
346 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
347 NumIntermediates, RegisterVT);
348 }
349
350 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!")(static_cast <bool> (NumRegs == NumParts && "Part count doesn't match vector breakdown!"
) ? void (0) : __assert_fail ("NumRegs == NumParts && \"Part count doesn't match vector breakdown!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 350
, __extension__ __PRETTY_FUNCTION__))
;
351 NumParts = NumRegs; // Silence a compiler warning.
352 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!")(static_cast <bool> (RegisterVT == PartVT && "Part type doesn't match vector breakdown!"
) ? void (0) : __assert_fail ("RegisterVT == PartVT && \"Part type doesn't match vector breakdown!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 352
, __extension__ __PRETTY_FUNCTION__))
;
353 assert(RegisterVT.getSizeInBits() ==(static_cast <bool> (RegisterVT.getSizeInBits() == Parts
[0].getSimpleValueType().getSizeInBits() && "Part type sizes don't match!"
) ? void (0) : __assert_fail ("RegisterVT.getSizeInBits() == Parts[0].getSimpleValueType().getSizeInBits() && \"Part type sizes don't match!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 355
, __extension__ __PRETTY_FUNCTION__))
354 Parts[0].getSimpleValueType().getSizeInBits() &&(static_cast <bool> (RegisterVT.getSizeInBits() == Parts
[0].getSimpleValueType().getSizeInBits() && "Part type sizes don't match!"
) ? void (0) : __assert_fail ("RegisterVT.getSizeInBits() == Parts[0].getSimpleValueType().getSizeInBits() && \"Part type sizes don't match!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 355
, __extension__ __PRETTY_FUNCTION__))
355 "Part type sizes don't match!")(static_cast <bool> (RegisterVT.getSizeInBits() == Parts
[0].getSimpleValueType().getSizeInBits() && "Part type sizes don't match!"
) ? void (0) : __assert_fail ("RegisterVT.getSizeInBits() == Parts[0].getSimpleValueType().getSizeInBits() && \"Part type sizes don't match!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 355
, __extension__ __PRETTY_FUNCTION__))
;
356
357 // Assemble the parts into intermediate operands.
358 SmallVector<SDValue, 8> Ops(NumIntermediates);
359 if (NumIntermediates == NumParts) {
360 // If the register was not expanded, truncate or copy the value,
361 // as appropriate.
362 for (unsigned i = 0; i != NumParts; ++i)
363 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
364 PartVT, IntermediateVT, V, CallConv);
365 } else if (NumParts > 0) {
366 // If the intermediate type was expanded, build the intermediate
367 // operands from the parts.
368 assert(NumParts % NumIntermediates == 0 &&(static_cast <bool> (NumParts % NumIntermediates == 0 &&
"Must expand into a divisible number of parts!") ? void (0) :
__assert_fail ("NumParts % NumIntermediates == 0 && \"Must expand into a divisible number of parts!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 369
, __extension__ __PRETTY_FUNCTION__))
369 "Must expand into a divisible number of parts!")(static_cast <bool> (NumParts % NumIntermediates == 0 &&
"Must expand into a divisible number of parts!") ? void (0) :
__assert_fail ("NumParts % NumIntermediates == 0 && \"Must expand into a divisible number of parts!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 369
, __extension__ __PRETTY_FUNCTION__))
;
370 unsigned Factor = NumParts / NumIntermediates;
371 for (unsigned i = 0; i != NumIntermediates; ++i)
372 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
373 PartVT, IntermediateVT, V, CallConv);
374 }
375
376 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
377 // intermediate operands.
378 EVT BuiltVectorTy =
379 IntermediateVT.isVector()
380 ? EVT::getVectorVT(
381 *DAG.getContext(), IntermediateVT.getScalarType(),
382 IntermediateVT.getVectorElementCount() * NumParts)
383 : EVT::getVectorVT(*DAG.getContext(),
384 IntermediateVT.getScalarType(),
385 NumIntermediates);
386 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
387 : ISD::BUILD_VECTOR,
388 DL, BuiltVectorTy, Ops);
389 }
390
391 // There is now one part, held in Val. Correct it to match ValueVT.
392 EVT PartEVT = Val.getValueType();
393
394 if (PartEVT == ValueVT)
395 return Val;
396
397 if (PartEVT.isVector()) {
398 // Vector/Vector bitcast.
399 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
400 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
401
402 // If the parts vector has more elements than the value vector, then we
403 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
404 // Extract the elements we want.
405 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
406 assert((PartEVT.getVectorElementCount().getKnownMinValue() >(static_cast <bool> ((PartEVT.getVectorElementCount().getKnownMinValue
() > ValueVT.getVectorElementCount().getKnownMinValue()) &&
(PartEVT.getVectorElementCount().isScalable() == ValueVT.getVectorElementCount
().isScalable()) && "Cannot narrow, it would be a lossy transformation"
) ? void (0) : __assert_fail ("(PartEVT.getVectorElementCount().getKnownMinValue() > ValueVT.getVectorElementCount().getKnownMinValue()) && (PartEVT.getVectorElementCount().isScalable() == ValueVT.getVectorElementCount().isScalable()) && \"Cannot narrow, it would be a lossy transformation\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 410
, __extension__ __PRETTY_FUNCTION__))
407 ValueVT.getVectorElementCount().getKnownMinValue()) &&(static_cast <bool> ((PartEVT.getVectorElementCount().getKnownMinValue
() > ValueVT.getVectorElementCount().getKnownMinValue()) &&
(PartEVT.getVectorElementCount().isScalable() == ValueVT.getVectorElementCount
().isScalable()) && "Cannot narrow, it would be a lossy transformation"
) ? void (0) : __assert_fail ("(PartEVT.getVectorElementCount().getKnownMinValue() > ValueVT.getVectorElementCount().getKnownMinValue()) && (PartEVT.getVectorElementCount().isScalable() == ValueVT.getVectorElementCount().isScalable()) && \"Cannot narrow, it would be a lossy transformation\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 410
, __extension__ __PRETTY_FUNCTION__))
408 (PartEVT.getVectorElementCount().isScalable() ==(static_cast <bool> ((PartEVT.getVectorElementCount().getKnownMinValue
() > ValueVT.getVectorElementCount().getKnownMinValue()) &&
(PartEVT.getVectorElementCount().isScalable() == ValueVT.getVectorElementCount
().isScalable()) && "Cannot narrow, it would be a lossy transformation"
) ? void (0) : __assert_fail ("(PartEVT.getVectorElementCount().getKnownMinValue() > ValueVT.getVectorElementCount().getKnownMinValue()) && (PartEVT.getVectorElementCount().isScalable() == ValueVT.getVectorElementCount().isScalable()) && \"Cannot narrow, it would be a lossy transformation\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 410
, __extension__ __PRETTY_FUNCTION__))
409 ValueVT.getVectorElementCount().isScalable()) &&(static_cast <bool> ((PartEVT.getVectorElementCount().getKnownMinValue
() > ValueVT.getVectorElementCount().getKnownMinValue()) &&
(PartEVT.getVectorElementCount().isScalable() == ValueVT.getVectorElementCount
().isScalable()) && "Cannot narrow, it would be a lossy transformation"
) ? void (0) : __assert_fail ("(PartEVT.getVectorElementCount().getKnownMinValue() > ValueVT.getVectorElementCount().getKnownMinValue()) && (PartEVT.getVectorElementCount().isScalable() == ValueVT.getVectorElementCount().isScalable()) && \"Cannot narrow, it would be a lossy transformation\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 410
, __extension__ __PRETTY_FUNCTION__))
410 "Cannot narrow, it would be a lossy transformation")(static_cast <bool> ((PartEVT.getVectorElementCount().getKnownMinValue
() > ValueVT.getVectorElementCount().getKnownMinValue()) &&
(PartEVT.getVectorElementCount().isScalable() == ValueVT.getVectorElementCount
().isScalable()) && "Cannot narrow, it would be a lossy transformation"
) ? void (0) : __assert_fail ("(PartEVT.getVectorElementCount().getKnownMinValue() > ValueVT.getVectorElementCount().getKnownMinValue()) && (PartEVT.getVectorElementCount().isScalable() == ValueVT.getVectorElementCount().isScalable()) && \"Cannot narrow, it would be a lossy transformation\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 410
, __extension__ __PRETTY_FUNCTION__))
;
411 PartEVT =
412 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
413 ValueVT.getVectorElementCount());
414 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
415 DAG.getVectorIdxConstant(0, DL));
416 if (PartEVT == ValueVT)
417 return Val;
418 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
419 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
420 }
421
422 // Promoted vector extract
423 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
424 }
425
426 // Trivial bitcast if the types are the same size and the destination
427 // vector type is legal.
428 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
429 TLI.isTypeLegal(ValueVT))
430 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
431
432 if (ValueVT.getVectorNumElements() != 1) {
433 // Certain ABIs require that vectors are passed as integers. For vectors
434 // are the same size, this is an obvious bitcast.
435 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
436 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
437 } else if (ValueVT.bitsLT(PartEVT)) {
438 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
439 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
440 // Drop the extra bits.
441 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
442 return DAG.getBitcast(ValueVT, Val);
443 }
444
445 diagnosePossiblyInvalidConstraint(
446 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
447 return DAG.getUNDEF(ValueVT);
448 }
449
450 // Handle cases such as i8 -> <1 x i1>
451 EVT ValueSVT = ValueVT.getVectorElementType();
452 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
453 unsigned ValueSize = ValueSVT.getSizeInBits();
454 if (ValueSize == PartEVT.getSizeInBits()) {
455 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
456 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
457 // It's possible a scalar floating point type gets softened to integer and
458 // then promoted to a larger integer. If PartEVT is the larger integer
459 // we need to truncate it and then bitcast to the FP type.
460 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types")(static_cast <bool> (ValueSVT.bitsLT(PartEVT) &&
"Unexpected types") ? void (0) : __assert_fail ("ValueSVT.bitsLT(PartEVT) && \"Unexpected types\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 460
, __extension__ __PRETTY_FUNCTION__))
;
461 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
462 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
463 Val = DAG.getBitcast(ValueSVT, Val);
464 } else {
465 Val = ValueVT.isFloatingPoint()
466 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
467 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
468 }
469 }
470
471 return DAG.getBuildVector(ValueVT, DL, Val);
472}
473
474static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
475 SDValue Val, SDValue *Parts, unsigned NumParts,
476 MVT PartVT, const Value *V,
477 std::optional<CallingConv::ID> CallConv);
478
479/// getCopyToParts - Create a series of nodes that contain the specified value
480/// split into legal parts. If the parts contain more bits than Val, then, for
481/// integers, ExtendKind can be used to specify how to generate the extra bits.
482static void
483getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
484 unsigned NumParts, MVT PartVT, const Value *V,
485 std::optional<CallingConv::ID> CallConv = std::nullopt,
486 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
487 // Let the target split the parts if it wants to
488 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
489 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
490 CallConv))
491 return;
492 EVT ValueVT = Val.getValueType();
493
494 // Handle the vector case separately.
495 if (ValueVT.isVector())
496 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
497 CallConv);
498
499 unsigned OrigNumParts = NumParts;
500 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&(static_cast <bool> (DAG.getTargetLoweringInfo().isTypeLegal
(PartVT) && "Copying to an illegal type!") ? void (0)
: __assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && \"Copying to an illegal type!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 501
, __extension__ __PRETTY_FUNCTION__))
501 "Copying to an illegal type!")(static_cast <bool> (DAG.getTargetLoweringInfo().isTypeLegal
(PartVT) && "Copying to an illegal type!") ? void (0)
: __assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(PartVT) && \"Copying to an illegal type!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 501
, __extension__ __PRETTY_FUNCTION__))
;
502
503 if (NumParts == 0)
504 return;
505
506 assert(!ValueVT.isVector() && "Vector case handled elsewhere")(static_cast <bool> (!ValueVT.isVector() && "Vector case handled elsewhere"
) ? void (0) : __assert_fail ("!ValueVT.isVector() && \"Vector case handled elsewhere\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 506
, __extension__ __PRETTY_FUNCTION__))
;
507 EVT PartEVT = PartVT;
508 if (PartEVT == ValueVT) {
509 assert(NumParts == 1 && "No-op copy with multiple parts!")(static_cast <bool> (NumParts == 1 && "No-op copy with multiple parts!"
) ? void (0) : __assert_fail ("NumParts == 1 && \"No-op copy with multiple parts!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 509
, __extension__ __PRETTY_FUNCTION__))
;
510 Parts[0] = Val;
511 return;
512 }
513
514 unsigned PartBits = PartVT.getSizeInBits();
515 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
516 // If the parts cover more bits than the value has, promote the value.
517 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
518 assert(NumParts == 1 && "Do not know what to promote to!")(static_cast <bool> (NumParts == 1 && "Do not know what to promote to!"
) ? void (0) : __assert_fail ("NumParts == 1 && \"Do not know what to promote to!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 518
, __extension__ __PRETTY_FUNCTION__))
;
519 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
520 } else {
521 if (ValueVT.isFloatingPoint()) {
522 // FP values need to be bitcast, then extended if they are being put
523 // into a larger container.
524 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
525 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
526 }
527 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&(static_cast <bool> ((PartVT.isInteger() || PartVT == MVT
::x86mmx) && ValueVT.isInteger() && "Unknown mismatch!"
) ? void (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 529
, __extension__ __PRETTY_FUNCTION__))
528 ValueVT.isInteger() &&(static_cast <bool> ((PartVT.isInteger() || PartVT == MVT
::x86mmx) && ValueVT.isInteger() && "Unknown mismatch!"
) ? void (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 529
, __extension__ __PRETTY_FUNCTION__))
529 "Unknown mismatch!")(static_cast <bool> ((PartVT.isInteger() || PartVT == MVT
::x86mmx) && ValueVT.isInteger() && "Unknown mismatch!"
) ? void (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 529
, __extension__ __PRETTY_FUNCTION__))
;
530 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
531 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
532 if (PartVT == MVT::x86mmx)
533 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
534 }
535 } else if (PartBits == ValueVT.getSizeInBits()) {
536 // Different types of the same size.
537 assert(NumParts == 1 && PartEVT != ValueVT)(static_cast <bool> (NumParts == 1 && PartEVT !=
ValueVT) ? void (0) : __assert_fail ("NumParts == 1 && PartEVT != ValueVT"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 537
, __extension__ __PRETTY_FUNCTION__))
;
538 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
540 // If the parts cover less bits than value has, truncate the value.
541 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&(static_cast <bool> ((PartVT.isInteger() || PartVT == MVT
::x86mmx) && ValueVT.isInteger() && "Unknown mismatch!"
) ? void (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 543
, __extension__ __PRETTY_FUNCTION__))
542 ValueVT.isInteger() &&(static_cast <bool> ((PartVT.isInteger() || PartVT == MVT
::x86mmx) && ValueVT.isInteger() && "Unknown mismatch!"
) ? void (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 543
, __extension__ __PRETTY_FUNCTION__))
543 "Unknown mismatch!")(static_cast <bool> ((PartVT.isInteger() || PartVT == MVT
::x86mmx) && ValueVT.isInteger() && "Unknown mismatch!"
) ? void (0) : __assert_fail ("(PartVT.isInteger() || PartVT == MVT::x86mmx) && ValueVT.isInteger() && \"Unknown mismatch!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 543
, __extension__ __PRETTY_FUNCTION__))
;
544 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
545 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
546 if (PartVT == MVT::x86mmx)
547 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
548 }
549
550 // The value may have changed - recompute ValueVT.
551 ValueVT = Val.getValueType();
552 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&(static_cast <bool> (NumParts * PartBits == ValueVT.getSizeInBits
() && "Failed to tile the value with PartVT!") ? void
(0) : __assert_fail ("NumParts * PartBits == ValueVT.getSizeInBits() && \"Failed to tile the value with PartVT!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 553
, __extension__ __PRETTY_FUNCTION__))
553 "Failed to tile the value with PartVT!")(static_cast <bool> (NumParts * PartBits == ValueVT.getSizeInBits
() && "Failed to tile the value with PartVT!") ? void
(0) : __assert_fail ("NumParts * PartBits == ValueVT.getSizeInBits() && \"Failed to tile the value with PartVT!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 553
, __extension__ __PRETTY_FUNCTION__))
;
554
555 if (NumParts == 1) {
556 if (PartEVT != ValueVT) {
557 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
558 "scalar-to-vector conversion failed");
559 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560 }
561
562 Parts[0] = Val;
563 return;
564 }
565
566 // Expand the value into multiple parts.
567 if (NumParts & (NumParts - 1)) {
568 // The number of parts is not a power of 2. Split off and copy the tail.
569 assert(PartVT.isInteger() && ValueVT.isInteger() &&(static_cast <bool> (PartVT.isInteger() && ValueVT
.isInteger() && "Do not know what to expand to!") ? void
(0) : __assert_fail ("PartVT.isInteger() && ValueVT.isInteger() && \"Do not know what to expand to!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 570
, __extension__ __PRETTY_FUNCTION__))
570 "Do not know what to expand to!")(static_cast <bool> (PartVT.isInteger() && ValueVT
.isInteger() && "Do not know what to expand to!") ? void
(0) : __assert_fail ("PartVT.isInteger() && ValueVT.isInteger() && \"Do not know what to expand to!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 570
, __extension__ __PRETTY_FUNCTION__))
;
571 unsigned RoundParts = llvm::bit_floor(NumParts);
572 unsigned RoundBits = RoundParts * PartBits;
573 unsigned OddParts = NumParts - RoundParts;
574 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
575 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
576
577 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
578 CallConv);
579
580 if (DAG.getDataLayout().isBigEndian())
581 // The odd parts were reversed by getCopyToParts - unreverse them.
582 std::reverse(Parts + RoundParts, Parts + NumParts);
583
584 NumParts = RoundParts;
585 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
586 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
587 }
588
589 // The number of parts is a power of 2. Repeatedly bisect the value using
590 // EXTRACT_ELEMENT.
591 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
592 EVT::getIntegerVT(*DAG.getContext(),
593 ValueVT.getSizeInBits()),
594 Val);
595
596 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
597 for (unsigned i = 0; i < NumParts; i += StepSize) {
598 unsigned ThisBits = StepSize * PartBits / 2;
599 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
600 SDValue &Part0 = Parts[i];
601 SDValue &Part1 = Parts[i+StepSize/2];
602
603 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
604 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
605 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
606 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
607
608 if (ThisBits == PartBits && ThisVT != PartVT) {
609 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
610 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
611 }
612 }
613 }
614
615 if (DAG.getDataLayout().isBigEndian())
616 std::reverse(Parts, Parts + OrigNumParts);
617}
618
619static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
620 const SDLoc &DL, EVT PartVT) {
621 if (!PartVT.isVector())
622 return SDValue();
623
624 EVT ValueVT = Val.getValueType();
625 ElementCount PartNumElts = PartVT.getVectorElementCount();
626 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
627
628 // We only support widening vectors with equivalent element types and
629 // fixed/scalable properties. If a target needs to widen a fixed-length type
630 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
631 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
632 PartNumElts.isScalable() != ValueNumElts.isScalable() ||
633 PartVT.getVectorElementType() != ValueVT.getVectorElementType())
634 return SDValue();
635
636 // Widening a scalable vector to another scalable vector is done by inserting
637 // the vector into a larger undef one.
638 if (PartNumElts.isScalable())
639 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
640 Val, DAG.getVectorIdxConstant(0, DL));
641
642 EVT ElementVT = PartVT.getVectorElementType();
643 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
644 // undef elements.
645 SmallVector<SDValue, 16> Ops;
646 DAG.ExtractVectorElements(Val, Ops);
647 SDValue EltUndef = DAG.getUNDEF(ElementVT);
648 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
649
650 // FIXME: Use CONCAT for 2x -> 4x.
651 return DAG.getBuildVector(PartVT, DL, Ops);
652}
653
654/// getCopyToPartsVector - Create a series of nodes that contain the specified
655/// value split into legal parts.
656static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
657 SDValue Val, SDValue *Parts, unsigned NumParts,
658 MVT PartVT, const Value *V,
659 std::optional<CallingConv::ID> CallConv) {
660 EVT ValueVT = Val.getValueType();
661 assert(ValueVT.isVector() && "Not a vector")(static_cast <bool> (ValueVT.isVector() && "Not a vector"
) ? void (0) : __assert_fail ("ValueVT.isVector() && \"Not a vector\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 661
, __extension__ __PRETTY_FUNCTION__))
;
662 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
663 const bool IsABIRegCopy = CallConv.has_value();
664
665 if (NumParts == 1) {
666 EVT PartEVT = PartVT;
667 if (PartEVT == ValueVT) {
668 // Nothing to do.
669 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
670 // Bitconvert vector->vector case.
671 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
672 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
673 Val = Widened;
674 } else if (PartVT.isVector() &&
675 PartEVT.getVectorElementType().bitsGE(
676 ValueVT.getVectorElementType()) &&
677 PartEVT.getVectorElementCount() ==
678 ValueVT.getVectorElementCount()) {
679
680 // Promoted vector extract
681 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
682 } else if (PartEVT.isVector() &&
683 PartEVT.getVectorElementType() !=
684 ValueVT.getVectorElementType() &&
685 TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
686 TargetLowering::TypeWidenVector) {
687 // Combination of widening and promotion.
688 EVT WidenVT =
689 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
690 PartVT.getVectorElementCount());
691 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
692 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
693 } else {
694 // Don't extract an integer from a float vector. This can happen if the
695 // FP type gets softened to integer and then promoted. The promotion
696 // prevents it from being picked up by the earlier bitcast case.
697 if (ValueVT.getVectorElementCount().isScalar() &&
698 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
699 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
700 DAG.getVectorIdxConstant(0, DL));
701 } else {
702 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
703 assert(PartVT.getFixedSizeInBits() > ValueSize &&(static_cast <bool> (PartVT.getFixedSizeInBits() > ValueSize
&& "lossy conversion of vector to scalar type") ? void
(0) : __assert_fail ("PartVT.getFixedSizeInBits() > ValueSize && \"lossy conversion of vector to scalar type\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 704
, __extension__ __PRETTY_FUNCTION__))
704 "lossy conversion of vector to scalar type")(static_cast <bool> (PartVT.getFixedSizeInBits() > ValueSize
&& "lossy conversion of vector to scalar type") ? void
(0) : __assert_fail ("PartVT.getFixedSizeInBits() > ValueSize && \"lossy conversion of vector to scalar type\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 704
, __extension__ __PRETTY_FUNCTION__))
;
705 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
706 Val = DAG.getBitcast(IntermediateType, Val);
707 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
708 }
709 }
710
711 assert(Val.getValueType() == PartVT && "Unexpected vector part value type")(static_cast <bool> (Val.getValueType() == PartVT &&
"Unexpected vector part value type") ? void (0) : __assert_fail
("Val.getValueType() == PartVT && \"Unexpected vector part value type\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 711
, __extension__ __PRETTY_FUNCTION__))
;
712 Parts[0] = Val;
713 return;
714 }
715
716 // Handle a multi-element vector.
717 EVT IntermediateVT;
718 MVT RegisterVT;
719 unsigned NumIntermediates;
720 unsigned NumRegs;
721 if (IsABIRegCopy) {
722 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
723 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
724 RegisterVT);
725 } else {
726 NumRegs =
727 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
728 NumIntermediates, RegisterVT);
729 }
730
731 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!")(static_cast <bool> (NumRegs == NumParts && "Part count doesn't match vector breakdown!"
) ? void (0) : __assert_fail ("NumRegs == NumParts && \"Part count doesn't match vector breakdown!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 731
, __extension__ __PRETTY_FUNCTION__))
;
732 NumParts = NumRegs; // Silence a compiler warning.
733 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!")(static_cast <bool> (RegisterVT == PartVT && "Part type doesn't match vector breakdown!"
) ? void (0) : __assert_fail ("RegisterVT == PartVT && \"Part type doesn't match vector breakdown!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 733
, __extension__ __PRETTY_FUNCTION__))
;
734
735 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&(static_cast <bool> (IntermediateVT.isScalableVector() ==
ValueVT.isScalableVector() && "Mixing scalable and fixed vectors when copying in parts"
) ? void (0) : __assert_fail ("IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && \"Mixing scalable and fixed vectors when copying in parts\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 736
, __extension__ __PRETTY_FUNCTION__))
736 "Mixing scalable and fixed vectors when copying in parts")(static_cast <bool> (IntermediateVT.isScalableVector() ==
ValueVT.isScalableVector() && "Mixing scalable and fixed vectors when copying in parts"
) ? void (0) : __assert_fail ("IntermediateVT.isScalableVector() == ValueVT.isScalableVector() && \"Mixing scalable and fixed vectors when copying in parts\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 736
, __extension__ __PRETTY_FUNCTION__))
;
737
738 std::optional<ElementCount> DestEltCnt;
739
740 if (IntermediateVT.isVector())
741 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
742 else
743 DestEltCnt = ElementCount::getFixed(NumIntermediates);
744
745 EVT BuiltVectorTy = EVT::getVectorVT(
746 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
747
748 if (ValueVT == BuiltVectorTy) {
749 // Nothing to do.
750 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
751 // Bitconvert vector->vector case.
752 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
753 } else {
754 if (BuiltVectorTy.getVectorElementType().bitsGT(
755 ValueVT.getVectorElementType())) {
756 // Integer promotion.
757 ValueVT = EVT::getVectorVT(*DAG.getContext(),
758 BuiltVectorTy.getVectorElementType(),
759 ValueVT.getVectorElementCount());
760 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
761 }
762
763 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
764 Val = Widened;
765 }
766 }
767
768 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type")(static_cast <bool> (Val.getValueType() == BuiltVectorTy
&& "Unexpected vector value type") ? void (0) : __assert_fail
("Val.getValueType() == BuiltVectorTy && \"Unexpected vector value type\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 768
, __extension__ __PRETTY_FUNCTION__))
;
769
770 // Split the vector into intermediate operands.
771 SmallVector<SDValue, 8> Ops(NumIntermediates);
772 for (unsigned i = 0; i != NumIntermediates; ++i) {
773 if (IntermediateVT.isVector()) {
774 // This does something sensible for scalable vectors - see the
775 // definition of EXTRACT_SUBVECTOR for further details.
776 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
777 Ops[i] =
778 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
779 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
780 } else {
781 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
782 DAG.getVectorIdxConstant(i, DL));
783 }
784 }
785
786 // Split the intermediate operands into legal parts.
787 if (NumParts == NumIntermediates) {
788 // If the register was not expanded, promote or copy the value,
789 // as appropriate.
790 for (unsigned i = 0; i != NumParts; ++i)
791 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
792 } else if (NumParts > 0) {
793 // If the intermediate type was expanded, split each the value into
794 // legal parts.
795 assert(NumIntermediates != 0 && "division by zero")(static_cast <bool> (NumIntermediates != 0 && "division by zero"
) ? void (0) : __assert_fail ("NumIntermediates != 0 && \"division by zero\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 795
, __extension__ __PRETTY_FUNCTION__))
;
796 assert(NumParts % NumIntermediates == 0 &&(static_cast <bool> (NumParts % NumIntermediates == 0 &&
"Must expand into a divisible number of parts!") ? void (0) :
__assert_fail ("NumParts % NumIntermediates == 0 && \"Must expand into a divisible number of parts!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 797
, __extension__ __PRETTY_FUNCTION__))
797 "Must expand into a divisible number of parts!")(static_cast <bool> (NumParts % NumIntermediates == 0 &&
"Must expand into a divisible number of parts!") ? void (0) :
__assert_fail ("NumParts % NumIntermediates == 0 && \"Must expand into a divisible number of parts!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 797
, __extension__ __PRETTY_FUNCTION__))
;
798 unsigned Factor = NumParts / NumIntermediates;
799 for (unsigned i = 0; i != NumIntermediates; ++i)
800 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
801 CallConv);
802 }
803}
804
805RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
806 EVT valuevt, std::optional<CallingConv::ID> CC)
807 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
808 RegCount(1, regs.size()), CallConv(CC) {}
809
810RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
811 const DataLayout &DL, unsigned Reg, Type *Ty,
812 std::optional<CallingConv::ID> CC) {
813 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
814
815 CallConv = CC;
816
817 for (EVT ValueVT : ValueVTs) {
818 unsigned NumRegs =
819 isABIMangled()
820 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
821 : TLI.getNumRegisters(Context, ValueVT);
822 MVT RegisterVT =
823 isABIMangled()
824 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
825 : TLI.getRegisterType(Context, ValueVT);
826 for (unsigned i = 0; i != NumRegs; ++i)
827 Regs.push_back(Reg + i);
828 RegVTs.push_back(RegisterVT);
829 RegCount.push_back(NumRegs);
830 Reg += NumRegs;
831 }
832}
833
834SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
835 FunctionLoweringInfo &FuncInfo,
836 const SDLoc &dl, SDValue &Chain,
837 SDValue *Glue, const Value *V) const {
838 // A Value with type {} or [0 x %t] needs no registers.
839 if (ValueVTs.empty())
840 return SDValue();
841
842 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
843
844 // Assemble the legal parts into the final values.
845 SmallVector<SDValue, 4> Values(ValueVTs.size());
846 SmallVector<SDValue, 8> Parts;
847 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
848 // Copy the legal parts from the registers.
849 EVT ValueVT = ValueVTs[Value];
850 unsigned NumRegs = RegCount[Value];
851 MVT RegisterVT = isABIMangled()
852 ? TLI.getRegisterTypeForCallingConv(
853 *DAG.getContext(), *CallConv, RegVTs[Value])
854 : RegVTs[Value];
855
856 Parts.resize(NumRegs);
857 for (unsigned i = 0; i != NumRegs; ++i) {
858 SDValue P;
859 if (!Glue) {
860 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
861 } else {
862 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
863 *Glue = P.getValue(2);
864 }
865
866 Chain = P.getValue(1);
867 Parts[i] = P;
868
869 // If the source register was virtual and if we know something about it,
870 // add an assert node.
871 if (!Register::isVirtualRegister(Regs[Part + i]) ||
872 !RegisterVT.isInteger())
873 continue;
874
875 const FunctionLoweringInfo::LiveOutInfo *LOI =
876 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
877 if (!LOI)
878 continue;
879
880 unsigned RegSize = RegisterVT.getScalarSizeInBits();
881 unsigned NumSignBits = LOI->NumSignBits;
882 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
883
884 if (NumZeroBits == RegSize) {
885 // The current value is a zero.
886 // Explicitly express that as it would be easier for
887 // optimizations to kick in.
888 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
889 continue;
890 }
891
892 // FIXME: We capture more information than the dag can represent. For
893 // now, just use the tightest assertzext/assertsext possible.
894 bool isSExt;
895 EVT FromVT(MVT::Other);
896 if (NumZeroBits) {
897 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
898 isSExt = false;
899 } else if (NumSignBits > 1) {
900 FromVT =
901 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
902 isSExt = true;
903 } else {
904 continue;
905 }
906 // Add an assertion node.
907 assert(FromVT != MVT::Other)(static_cast <bool> (FromVT != MVT::Other) ? void (0) :
__assert_fail ("FromVT != MVT::Other", "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 907, __extension__ __PRETTY_FUNCTION__))
;
908 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
909 RegisterVT, P, DAG.getValueType(FromVT));
910 }
911
912 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
913 RegisterVT, ValueVT, V, CallConv);
914 Part += NumRegs;
915 Parts.clear();
916 }
917
918 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
919}
920
921void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
922 const SDLoc &dl, SDValue &Chain, SDValue *Glue,
923 const Value *V,
924 ISD::NodeType PreferredExtendType) const {
925 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
926 ISD::NodeType ExtendKind = PreferredExtendType;
927
928 // Get the list of the values's legal parts.
929 unsigned NumRegs = Regs.size();
930 SmallVector<SDValue, 8> Parts(NumRegs);
931 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
932 unsigned NumParts = RegCount[Value];
933
934 MVT RegisterVT = isABIMangled()
935 ? TLI.getRegisterTypeForCallingConv(
936 *DAG.getContext(), *CallConv, RegVTs[Value])
937 : RegVTs[Value];
938
939 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
940 ExtendKind = ISD::ZERO_EXTEND;
941
942 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
943 NumParts, RegisterVT, V, CallConv, ExtendKind);
944 Part += NumParts;
945 }
946
947 // Copy the parts into the registers.
948 SmallVector<SDValue, 8> Chains(NumRegs);
949 for (unsigned i = 0; i != NumRegs; ++i) {
950 SDValue Part;
951 if (!Glue) {
952 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
953 } else {
954 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
955 *Glue = Part.getValue(1);
956 }
957
958 Chains[i] = Part.getValue(0);
959 }
960
961 if (NumRegs == 1 || Glue)
962 // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
963 // flagged to it. That is the CopyToReg nodes and the user are considered
964 // a single scheduling unit. If we create a TokenFactor and return it as
965 // chain, then the TokenFactor is both a predecessor (operand) of the
966 // user as well as a successor (the TF operands are flagged to the user).
967 // c1, f1 = CopyToReg
968 // c2, f2 = CopyToReg
969 // c3 = TokenFactor c1, c2
970 // ...
971 // = op c3, ..., f2
972 Chain = Chains[NumRegs-1];
973 else
974 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
975}
976
977void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
978 unsigned MatchingIdx, const SDLoc &dl,
979 SelectionDAG &DAG,
980 std::vector<SDValue> &Ops) const {
981 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
982
983 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
984 if (HasMatching)
985 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
986 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
987 // Put the register class of the virtual registers in the flag word. That
988 // way, later passes can recompute register class constraints for inline
989 // assembly as well as normal instructions.
990 // Don't do this for tied operands that can use the regclass information
991 // from the def.
992 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
993 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
994 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
995 }
996
997 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
998 Ops.push_back(Res);
999
1000 if (Code == InlineAsm::Kind_Clobber) {
1001 // Clobbers should always have a 1:1 mapping with registers, and may
1002 // reference registers that have illegal (e.g. vector) types. Hence, we
1003 // shouldn't try to apply any sort of splitting logic to them.
1004 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&(static_cast <bool> (Regs.size() == RegVTs.size() &&
Regs.size() == ValueVTs.size() && "No 1:1 mapping from clobbers to regs?"
) ? void (0) : __assert_fail ("Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && \"No 1:1 mapping from clobbers to regs?\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1005
, __extension__ __PRETTY_FUNCTION__))
1005 "No 1:1 mapping from clobbers to regs?")(static_cast <bool> (Regs.size() == RegVTs.size() &&
Regs.size() == ValueVTs.size() && "No 1:1 mapping from clobbers to regs?"
) ? void (0) : __assert_fail ("Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() && \"No 1:1 mapping from clobbers to regs?\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1005
, __extension__ __PRETTY_FUNCTION__))
;
1006 Register SP = TLI.getStackPointerRegisterToSaveRestore();
1007 (void)SP;
1008 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1009 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1010 assert((static_cast <bool> ((Regs[I] != SP || DAG.getMachineFunction
().getFrameInfo().hasOpaqueSPAdjustment()) && "If we clobbered the stack pointer, MFI should know about it."
) ? void (0) : __assert_fail ("(Regs[I] != SP || DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && \"If we clobbered the stack pointer, MFI should know about it.\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1013
, __extension__ __PRETTY_FUNCTION__))
1011 (Regs[I] != SP ||(static_cast <bool> ((Regs[I] != SP || DAG.getMachineFunction
().getFrameInfo().hasOpaqueSPAdjustment()) && "If we clobbered the stack pointer, MFI should know about it."
) ? void (0) : __assert_fail ("(Regs[I] != SP || DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && \"If we clobbered the stack pointer, MFI should know about it.\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1013
, __extension__ __PRETTY_FUNCTION__))
1012 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&(static_cast <bool> ((Regs[I] != SP || DAG.getMachineFunction
().getFrameInfo().hasOpaqueSPAdjustment()) && "If we clobbered the stack pointer, MFI should know about it."
) ? void (0) : __assert_fail ("(Regs[I] != SP || DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && \"If we clobbered the stack pointer, MFI should know about it.\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1013
, __extension__ __PRETTY_FUNCTION__))
1013 "If we clobbered the stack pointer, MFI should know about it.")(static_cast <bool> ((Regs[I] != SP || DAG.getMachineFunction
().getFrameInfo().hasOpaqueSPAdjustment()) && "If we clobbered the stack pointer, MFI should know about it."
) ? void (0) : __assert_fail ("(Regs[I] != SP || DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) && \"If we clobbered the stack pointer, MFI should know about it.\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1013
, __extension__ __PRETTY_FUNCTION__))
;
1014 }
1015 return;
1016 }
1017
1018 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1019 MVT RegisterVT = RegVTs[Value];
1020 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1021 RegisterVT);
1022 for (unsigned i = 0; i != NumRegs; ++i) {
1023 assert(Reg < Regs.size() && "Mismatch in # registers expected")(static_cast <bool> (Reg < Regs.size() && "Mismatch in # registers expected"
) ? void (0) : __assert_fail ("Reg < Regs.size() && \"Mismatch in # registers expected\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1023
, __extension__ __PRETTY_FUNCTION__))
;
1024 unsigned TheReg = Regs[Reg++];
1025 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1026 }
1027 }
1028}
1029
1030SmallVector<std::pair<unsigned, TypeSize>, 4>
1031RegsForValue::getRegsAndSizes() const {
1032 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1033 unsigned I = 0;
1034 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1035 unsigned RegCount = std::get<0>(CountAndVT);
1036 MVT RegisterVT = std::get<1>(CountAndVT);
1037 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1038 for (unsigned E = I + RegCount; I != E; ++I)
1039 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1040 }
1041 return OutVec;
1042}
1043
1044void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1045 AssumptionCache *ac,
1046 const TargetLibraryInfo *li) {
1047 AA = aa;
1048 AC = ac;
1049 GFI = gfi;
1050 LibInfo = li;
1051 Context = DAG.getContext();
1052 LPadToCallSiteMap.clear();
1053 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1054 AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1055 *DAG.getMachineFunction().getFunction().getParent());
1056}
1057
1058void SelectionDAGBuilder::clear() {
1059 NodeMap.clear();
1060 UnusedArgNodeMap.clear();
1061 PendingLoads.clear();
1062 PendingExports.clear();
1063 PendingConstrainedFP.clear();
1064 PendingConstrainedFPStrict.clear();
1065 CurInst = nullptr;
1066 HasTailCall = false;
1067 SDNodeOrder = LowestSDNodeOrder;
1068 StatepointLowering.clear();
1069}
1070
1071void SelectionDAGBuilder::clearDanglingDebugInfo() {
1072 DanglingDebugInfoMap.clear();
1073}
1074
1075// Update DAG root to include dependencies on Pending chains.
1076SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1077 SDValue Root = DAG.getRoot();
1078
1079 if (Pending.empty())
1080 return Root;
1081
1082 // Add current root to PendingChains, unless we already indirectly
1083 // depend on it.
1084 if (Root.getOpcode() != ISD::EntryToken) {
1085 unsigned i = 0, e = Pending.size();
1086 for (; i != e; ++i) {
1087 assert(Pending[i].getNode()->getNumOperands() > 1)(static_cast <bool> (Pending[i].getNode()->getNumOperands
() > 1) ? void (0) : __assert_fail ("Pending[i].getNode()->getNumOperands() > 1"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1087
, __extension__ __PRETTY_FUNCTION__))
;
1088 if (Pending[i].getNode()->getOperand(0) == Root)
1089 break; // Don't add the root if we already indirectly depend on it.
1090 }
1091
1092 if (i == e)
1093 Pending.push_back(Root);
1094 }
1095
1096 if (Pending.size() == 1)
1097 Root = Pending[0];
1098 else
1099 Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1100
1101 DAG.setRoot(Root);
1102 Pending.clear();
1103 return Root;
1104}
1105
1106SDValue SelectionDAGBuilder::getMemoryRoot() {
1107 return updateRoot(PendingLoads);
1108}
1109
1110SDValue SelectionDAGBuilder::getRoot() {
1111 // Chain up all pending constrained intrinsics together with all
1112 // pending loads, by simply appending them to PendingLoads and
1113 // then calling getMemoryRoot().
1114 PendingLoads.reserve(PendingLoads.size() +
1115 PendingConstrainedFP.size() +
1116 PendingConstrainedFPStrict.size());
1117 PendingLoads.append(PendingConstrainedFP.begin(),
1118 PendingConstrainedFP.end());
1119 PendingLoads.append(PendingConstrainedFPStrict.begin(),
1120 PendingConstrainedFPStrict.end());
1121 PendingConstrainedFP.clear();
1122 PendingConstrainedFPStrict.clear();
1123 return getMemoryRoot();
1124}
1125
1126SDValue SelectionDAGBuilder::getControlRoot() {
1127 // We need to emit pending fpexcept.strict constrained intrinsics,
1128 // so append them to the PendingExports list.
1129 PendingExports.append(PendingConstrainedFPStrict.begin(),
1130 PendingConstrainedFPStrict.end());
1131 PendingConstrainedFPStrict.clear();
1132 return updateRoot(PendingExports);
1133}
1134
1135void SelectionDAGBuilder::visit(const Instruction &I) {
1136 // Set up outgoing PHI node register values before emitting the terminator.
1137 if (I.isTerminator()) {
1138 HandlePHINodesInSuccessorBlocks(I.getParent());
1139 }
1140
1141 // Add SDDbgValue nodes for any var locs here. Do so before updating
1142 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1143 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1144 // Add SDDbgValue nodes for any var locs here. Do so before updating
1145 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1146 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1147 It != End; ++It) {
1148 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1149 dropDanglingDebugInfo(Var, It->Expr);
1150 SmallVector<Value *> Values(It->Values.location_ops());
1151 if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1152 It->Values.hasArgList()))
1153 addDanglingDebugInfo(It, SDNodeOrder);
1154 }
1155 }
1156
1157 // Increase the SDNodeOrder if dealing with a non-debug instruction.
1158 if (!isa<DbgInfoIntrinsic>(I))
1159 ++SDNodeOrder;
1160
1161 CurInst = &I;
1162
1163 // Set inserted listener only if required.
1164 bool NodeInserted = false;
1165 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1166 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1167 if (PCSectionsMD) {
1168 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1169 DAG, [&](SDNode *) { NodeInserted = true; });
1170 }
1171
1172 visit(I.getOpcode(), I);
1173
1174 if (!I.isTerminator() && !HasTailCall &&
1175 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1176 CopyToExportRegsIfNeeded(&I);
1177
1178 // Handle metadata.
1179 if (PCSectionsMD) {
1180 auto It = NodeMap.find(&I);
1181 if (It != NodeMap.end()) {
1182 DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1183 } else if (NodeInserted) {
1184 // This should not happen; if it does, don't let it go unnoticed so we can
1185 // fix it. Relevant visit*() function is probably missing a setValue().
1186 errs() << "warning: loosing !pcsections metadata ["
1187 << I.getModule()->getName() << "]\n";
1188 LLVM_DEBUG(I.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { I.dump(); } } while (false)
;
1189 assert(false)(static_cast <bool> (false) ? void (0) : __assert_fail (
"false", "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1189, __extension__ __PRETTY_FUNCTION__))
;
1190 }
1191 }
1192
1193 CurInst = nullptr;
1194}
1195
1196void SelectionDAGBuilder::visitPHI(const PHINode &) {
1197 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!")::llvm::llvm_unreachable_internal("SelectionDAGBuilder shouldn't visit PHI nodes!"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1197
)
;
1198}
1199
1200void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1201 // Note: this doesn't use InstVisitor, because it has to work with
1202 // ConstantExpr's in addition to instructions.
1203 switch (Opcode) {
1204 default: llvm_unreachable("Unknown instruction type encountered!")::llvm::llvm_unreachable_internal("Unknown instruction type encountered!"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1204
)
;
1205 // Build the switch statement using the Instruction.def file.
1206#define HANDLE_INST(NUM, OPCODE, CLASS) \
1207 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1208#include "llvm/IR/Instruction.def"
1209 }
1210}
1211
1212static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1213 DILocalVariable *Variable,
1214 DebugLoc DL, unsigned Order,
1215 RawLocationWrapper Values,
1216 DIExpression *Expression) {
1217 if (!Values.hasArgList())
1218 return false;
1219 // For variadic dbg_values we will now insert an undef.
1220 // FIXME: We can potentially recover these!
1221 SmallVector<SDDbgOperand, 2> Locs;
1222 for (const Value *V : Values.location_ops()) {
1223 auto *Undef = UndefValue::get(V->getType());
1224 Locs.push_back(SDDbgOperand::fromConst(Undef));
1225 }
1226 SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1227 /*IsIndirect=*/false, DL, Order,
1228 /*IsVariadic=*/true);
1229 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1230 return true;
1231}
1232
1233void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc,
1234 unsigned Order) {
1235 if (!handleDanglingVariadicDebugInfo(
1236 DAG,
1237 const_cast<DILocalVariable *>(DAG.getFunctionVarLocs()
1238 ->getVariable(VarLoc->VariableID)
1239 .getVariable()),
1240 VarLoc->DL, Order, VarLoc->Values, VarLoc->Expr)) {
1241 DanglingDebugInfoMap[VarLoc->Values.getVariableLocationOp(0)].emplace_back(
1242 VarLoc, Order);
1243 }
1244}
1245
1246void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1247 unsigned Order) {
1248 // We treat variadic dbg_values differently at this stage.
1249 if (!handleDanglingVariadicDebugInfo(
1250 DAG, DI->getVariable(), DI->getDebugLoc(), Order,
1251 DI->getWrappedLocation(), DI->getExpression())) {
1252 // TODO: Dangling debug info will eventually either be resolved or produce
1253 // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1254 // between the original dbg.value location and its resolved DBG_VALUE,
1255 // which we should ideally fill with an extra Undef DBG_VALUE.
1256 assert(DI->getNumVariableLocationOps() == 1 &&(static_cast <bool> (DI->getNumVariableLocationOps()
== 1 && "DbgValueInst without an ArgList should have a single location "
"operand.") ? void (0) : __assert_fail ("DI->getNumVariableLocationOps() == 1 && \"DbgValueInst without an ArgList should have a single location \" \"operand.\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1258
, __extension__ __PRETTY_FUNCTION__))
1257 "DbgValueInst without an ArgList should have a single location "(static_cast <bool> (DI->getNumVariableLocationOps()
== 1 && "DbgValueInst without an ArgList should have a single location "
"operand.") ? void (0) : __assert_fail ("DI->getNumVariableLocationOps() == 1 && \"DbgValueInst without an ArgList should have a single location \" \"operand.\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1258
, __extension__ __PRETTY_FUNCTION__))
1258 "operand.")(static_cast <bool> (DI->getNumVariableLocationOps()
== 1 && "DbgValueInst without an ArgList should have a single location "
"operand.") ? void (0) : __assert_fail ("DI->getNumVariableLocationOps() == 1 && \"DbgValueInst without an ArgList should have a single location \" \"operand.\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1258
, __extension__ __PRETTY_FUNCTION__))
;
1259 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order);
1260 }
1261}
1262
1263void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1264 const DIExpression *Expr) {
1265 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1266 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs());
1267 DIExpression *DanglingExpr = DDI.getExpression();
1268 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1269 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping dangling debug info for "
<< printDDI(DDI) << "\n"; } } while (false)
1270 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping dangling debug info for "
<< printDDI(DDI) << "\n"; } } while (false)
;
1271 return true;
1272 }
1273 return false;
1274 };
1275
1276 for (auto &DDIMI : DanglingDebugInfoMap) {
1277 DanglingDebugInfoVector &DDIV = DDIMI.second;
1278
1279 // If debug info is to be dropped, run it through final checks to see
1280 // whether it can be salvaged.
1281 for (auto &DDI : DDIV)
1282 if (isMatchingDbgValue(DDI))
1283 salvageUnresolvedDbgValue(DDI);
1284
1285 erase_if(DDIV, isMatchingDbgValue);
1286 }
1287}
1288
1289// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1290// generate the debug data structures now that we've seen its definition.
1291void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1292 SDValue Val) {
1293 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1294 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1295 return;
1296
1297 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1298 for (auto &DDI : DDIV) {
1299 DebugLoc DL = DDI.getDebugLoc();
1300 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1301 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1302 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs());
1303 DIExpression *Expr = DDI.getExpression();
1304 assert(Variable->isValidLocationForIntrinsic(DL) &&(static_cast <bool> (Variable->isValidLocationForIntrinsic
(DL) && "Expected inlined-at fields to agree") ? void
(0) : __assert_fail ("Variable->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1305
, __extension__ __PRETTY_FUNCTION__))
1305 "Expected inlined-at fields to agree")(static_cast <bool> (Variable->isValidLocationForIntrinsic
(DL) && "Expected inlined-at fields to agree") ? void
(0) : __assert_fail ("Variable->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1305
, __extension__ __PRETTY_FUNCTION__))
;
1306 SDDbgValue *SDV;
1307 if (Val.getNode()) {
1308 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1309 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1310 // we couldn't resolve it directly when examining the DbgValue intrinsic
1311 // in the first place we should not be more successful here). Unless we
1312 // have some test case that prove this to be correct we should avoid
1313 // calling EmitFuncArgumentDbgValue here.
1314 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1315 FuncArgumentDbgValueKind::Value, Val)) {
1316 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Resolve dangling debug info for "
<< printDDI(DDI) << "\n"; } } while (false)
1317 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Resolve dangling debug info for "
<< printDDI(DDI) << "\n"; } } while (false)
;
1318 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << " By mapping to:\n "; Val.dump
(); } } while (false)
;
1319 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1320 // inserted after the definition of Val when emitting the instructions
1321 // after ISel. An alternative could be to teach
1322 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1323 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() <<
"changing SDNodeOrder from " << DbgSDNodeOrder <<
" to " << ValSDNodeOrder << "\n"; } } while (false
)
1324 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() <<
"changing SDNodeOrder from " << DbgSDNodeOrder <<
" to " << ValSDNodeOrder << "\n"; } } while (false
)
1325 << ValSDNodeOrder << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { if (ValSDNodeOrder > DbgSDNodeOrder) dbgs() <<
"changing SDNodeOrder from " << DbgSDNodeOrder <<
" to " << ValSDNodeOrder << "\n"; } } while (false
)
;
1326 SDV = getDbgValue(Val, Variable, Expr, DL,
1327 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1328 DAG.AddDbgValue(SDV, false);
1329 } else
1330 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Resolved dangling debug info for "
<< printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"
; } } while (false)
1331 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Resolved dangling debug info for "
<< printDDI(DDI) << " in EmitFuncArgumentDbgValue\n"
; } } while (false)
;
1332 } else {
1333 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping debug info for " <<
printDDI(DDI) << "\n"; } } while (false)
;
1334 auto Undef = UndefValue::get(V->getType());
1335 auto SDV =
1336 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1337 DAG.AddDbgValue(SDV, false);
1338 }
1339 }
1340 DDIV.clear();
1341}
1342
1343void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1344 // TODO: For the variadic implementation, instead of only checking the fail
1345 // state of `handleDebugValue`, we need know specifically which values were
1346 // invalid, so that we attempt to salvage only those values when processing
1347 // a DIArgList.
1348 Value *V = DDI.getVariableLocationOp(0);
1349 Value *OrigV = V;
1350 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs());
1351 DIExpression *Expr = DDI.getExpression();
1352 DebugLoc DL = DDI.getDebugLoc();
1353 unsigned SDOrder = DDI.getSDNodeOrder();
1354
1355 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1356 // that DW_OP_stack_value is desired.
1357 bool StackValue = true;
1358
1359 // Can this Value can be encoded without any further work?
1360 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1361 return;
1362
1363 // Attempt to salvage back through as many instructions as possible. Bail if
1364 // a non-instruction is seen, such as a constant expression or global
1365 // variable. FIXME: Further work could recover those too.
1366 while (isa<Instruction>(V)) {
1367 Instruction &VAsInst = *cast<Instruction>(V);
1368 // Temporary "0", awaiting real implementation.
1369 SmallVector<uint64_t, 16> Ops;
1370 SmallVector<Value *, 4> AdditionalValues;
1371 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1372 AdditionalValues);
1373 // If we cannot salvage any further, and haven't yet found a suitable debug
1374 // expression, bail out.
1375 if (!V)
1376 break;
1377
1378 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1379 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1380 // here for variadic dbg_values, remove that condition.
1381 if (!AdditionalValues.empty())
1382 break;
1383
1384 // New value and expr now represent this debuginfo.
1385 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1386
1387 // Some kind of simplification occurred: check whether the operand of the
1388 // salvaged debug expression can be encoded in this DAG.
1389 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1390 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Salvaged debug location info for:\n "
<< *Var << "\n" << *OrigV << "\nBy stripping back to:\n "
<< *V << "\n"; } } while (false)
1391 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Salvaged debug location info for:\n "
<< *Var << "\n" << *OrigV << "\nBy stripping back to:\n "
<< *V << "\n"; } } while (false)
1392 << *OrigV << "\nBy stripping back to:\n " << *V << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Salvaged debug location info for:\n "
<< *Var << "\n" << *OrigV << "\nBy stripping back to:\n "
<< *V << "\n"; } } while (false)
;
1393 return;
1394 }
1395 }
1396
1397 // This was the final opportunity to salvage this debug information, and it
1398 // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1399 // any earlier variable location.
1400 assert(OrigV && "V shouldn't be null")(static_cast <bool> (OrigV && "V shouldn't be null"
) ? void (0) : __assert_fail ("OrigV && \"V shouldn't be null\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1400
, __extension__ __PRETTY_FUNCTION__))
;
1401 auto *Undef = UndefValue::get(OrigV->getType());
1402 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1403 DAG.AddDbgValue(SDV, false);
1404 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping debug value info for:\n "
<< printDDI(DDI) << "\n"; } } while (false)
1405 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("isel")) { dbgs() << "Dropping debug value info for:\n "
<< printDDI(DDI) << "\n"; } } while (false)
;
1406}
1407
1408void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1409 DIExpression *Expr,
1410 DebugLoc DbgLoc,
1411 unsigned Order) {
1412 Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1413 DIExpression *NewExpr =
1414 const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1415 handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1416 /*IsVariadic*/ false);
1417}
1418
1419bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1420 DILocalVariable *Var,
1421 DIExpression *Expr, DebugLoc DbgLoc,
1422 unsigned Order, bool IsVariadic) {
1423 if (Values.empty())
1424 return true;
1425 SmallVector<SDDbgOperand> LocationOps;
1426 SmallVector<SDNode *> Dependencies;
1427 for (const Value *V : Values) {
1428 // Constant value.
1429 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1430 isa<ConstantPointerNull>(V)) {
1431 LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1432 continue;
1433 }
1434
1435 // Look through IntToPtr constants.
1436 if (auto *CE = dyn_cast<ConstantExpr>(V))
1437 if (CE->getOpcode() == Instruction::IntToPtr) {
1438 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1439 continue;
1440 }
1441
1442 // If the Value is a frame index, we can create a FrameIndex debug value
1443 // without relying on the DAG at all.
1444 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1445 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1446 if (SI != FuncInfo.StaticAllocaMap.end()) {
1447 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1448 continue;
1449 }
1450 }
1451
1452 // Do not use getValue() in here; we don't want to generate code at
1453 // this point if it hasn't been done yet.
1454 SDValue N = NodeMap[V];
1455 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1456 N = UnusedArgNodeMap[V];
1457 if (N.getNode()) {
1458 // Only emit func arg dbg value for non-variadic dbg.values for now.
1459 if (!IsVariadic &&
1460 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1461 FuncArgumentDbgValueKind::Value, N))
1462 return true;
1463 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1464 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1465 // describe stack slot locations.
1466 //
1467 // Consider "int x = 0; int *px = &x;". There are two kinds of
1468 // interesting debug values here after optimization:
1469 //
1470 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1471 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1472 //
1473 // Both describe the direct values of their associated variables.
1474 Dependencies.push_back(N.getNode());
1475 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1476 continue;
1477 }
1478 LocationOps.emplace_back(
1479 SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1480 continue;
1481 }
1482
1483 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1484 // Special rules apply for the first dbg.values of parameter variables in a
1485 // function. Identify them by the fact they reference Argument Values, that
1486 // they're parameters, and they are parameters of the current function. We
1487 // need to let them dangle until they get an SDNode.
1488 bool IsParamOfFunc =
1489 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1490 if (IsParamOfFunc)
1491 return false;
1492
1493 // The value is not used in this block yet (or it would have an SDNode).
1494 // We still want the value to appear for the user if possible -- if it has
1495 // an associated VReg, we can refer to that instead.
1496 auto VMI = FuncInfo.ValueMap.find(V);
1497 if (VMI != FuncInfo.ValueMap.end()) {
1498 unsigned Reg = VMI->second;
1499 // If this is a PHI node, it may be split up into several MI PHI nodes
1500 // (in FunctionLoweringInfo::set).
1501 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1502 V->getType(), std::nullopt);
1503 if (RFV.occupiesMultipleRegs()) {
1504 // FIXME: We could potentially support variadic dbg_values here.
1505 if (IsVariadic)
1506 return false;
1507 unsigned Offset = 0;
1508 unsigned BitsToDescribe = 0;
1509 if (auto VarSize = Var->getSizeInBits())
1510 BitsToDescribe = *VarSize;
1511 if (auto Fragment = Expr->getFragmentInfo())
1512 BitsToDescribe = Fragment->SizeInBits;
1513 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1514 // Bail out if all bits are described already.
1515 if (Offset >= BitsToDescribe)
1516 break;
1517 // TODO: handle scalable vectors.
1518 unsigned RegisterSize = RegAndSize.second;
1519 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1520 ? BitsToDescribe - Offset
1521 : RegisterSize;
1522 auto FragmentExpr = DIExpression::createFragmentExpression(
1523 Expr, Offset, FragmentSize);
1524 if (!FragmentExpr)
1525 continue;
1526 SDDbgValue *SDV = DAG.getVRegDbgValue(
1527 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1528 DAG.AddDbgValue(SDV, false);
1529 Offset += RegisterSize;
1530 }
1531 return true;
1532 }
1533 // We can use simple vreg locations for variadic dbg_values as well.
1534 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1535 continue;
1536 }
1537 // We failed to create a SDDbgOperand for V.
1538 return false;
1539 }
1540
1541 // We have created a SDDbgOperand for each Value in Values.
1542 // Should use Order instead of SDNodeOrder?
1543 assert(!LocationOps.empty())(static_cast <bool> (!LocationOps.empty()) ? void (0) :
__assert_fail ("!LocationOps.empty()", "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1543, __extension__ __PRETTY_FUNCTION__))
;
1544 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1545 /*IsIndirect=*/false, DbgLoc,
1546 SDNodeOrder, IsVariadic);
1547 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1548 return true;
1549}
1550
1551void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1552 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1553 for (auto &Pair : DanglingDebugInfoMap)
1554 for (auto &DDI : Pair.second)
1555 salvageUnresolvedDbgValue(DDI);
1556 clearDanglingDebugInfo();
1557}
1558
1559/// getCopyFromRegs - If there was virtual register allocated for the value V
1560/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1561SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1562 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1563 SDValue Result;
1564
1565 if (It != FuncInfo.ValueMap.end()) {
1566 Register InReg = It->second;
1567
1568 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1569 DAG.getDataLayout(), InReg, Ty,
1570 std::nullopt); // This is not an ABI copy.
1571 SDValue Chain = DAG.getEntryNode();
1572 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1573 V);
1574 resolveDanglingDebugInfo(V, Result);
1575 }
1576
1577 return Result;
1578}
1579
1580/// getValue - Return an SDValue for the given Value.
1581SDValue SelectionDAGBuilder::getValue(const Value *V) {
1582 // If we already have an SDValue for this value, use it. It's important
1583 // to do this first, so that we don't create a CopyFromReg if we already
1584 // have a regular SDValue.
1585 SDValue &N = NodeMap[V];
1586 if (N.getNode()) return N;
1587
1588 // If there's a virtual register allocated and initialized for this
1589 // value, use it.
1590 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1591 return copyFromReg;
1592
1593 // Otherwise create a new SDValue and remember it.
1594 SDValue Val = getValueImpl(V);
1595 NodeMap[V] = Val;
1596 resolveDanglingDebugInfo(V, Val);
1597 return Val;
1598}
1599
1600/// getNonRegisterValue - Return an SDValue for the given Value, but
1601/// don't look in FuncInfo.ValueMap for a virtual register.
1602SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1603 // If we already have an SDValue for this value, use it.
1604 SDValue &N = NodeMap[V];
1605 if (N.getNode()) {
1606 if (isIntOrFPConstant(N)) {
1607 // Remove the debug location from the node as the node is about to be used
1608 // in a location which may differ from the original debug location. This
1609 // is relevant to Constant and ConstantFP nodes because they can appear
1610 // as constant expressions inside PHI nodes.
1611 N->setDebugLoc(DebugLoc());
1612 }
1613 return N;
1614 }
1615
1616 // Otherwise create a new SDValue and remember it.
1617 SDValue Val = getValueImpl(V);
1618 NodeMap[V] = Val;
1619 resolveDanglingDebugInfo(V, Val);
1620 return Val;
1621}
1622
1623/// getValueImpl - Helper function for getValue and getNonRegisterValue.
1624/// Create an SDValue for the given value.
1625SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1626 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1627
1628 if (const Constant *C = dyn_cast<Constant>(V)) {
1629 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1630
1631 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1632 return DAG.getConstant(*CI, getCurSDLoc(), VT);
1633
1634 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1635 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1636
1637 if (isa<ConstantPointerNull>(C)) {
1638 unsigned AS = V->getType()->getPointerAddressSpace();
1639 return DAG.getConstant(0, getCurSDLoc(),
1640 TLI.getPointerTy(DAG.getDataLayout(), AS));
1641 }
1642
1643 if (match(C, m_VScale()))
1644 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1645
1646 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1647 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1648
1649 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1650 return DAG.getUNDEF(VT);
1651
1652 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1653 visit(CE->getOpcode(), *CE);
1654 SDValue N1 = NodeMap[V];
1655 assert(N1.getNode() && "visit didn't populate the NodeMap!")(static_cast <bool> (N1.getNode() && "visit didn't populate the NodeMap!"
) ? void (0) : __assert_fail ("N1.getNode() && \"visit didn't populate the NodeMap!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1655
, __extension__ __PRETTY_FUNCTION__))
;
1656 return N1;
1657 }
1658
1659 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1660 SmallVector<SDValue, 4> Constants;
1661 for (const Use &U : C->operands()) {
1662 SDNode *Val = getValue(U).getNode();
1663 // If the operand is an empty aggregate, there are no values.
1664 if (!Val) continue;
1665 // Add each leaf value from the operand to the Constants list
1666 // to form a flattened list of all the values.
1667 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1668 Constants.push_back(SDValue(Val, i));
1669 }
1670
1671 return DAG.getMergeValues(Constants, getCurSDLoc());
1672 }
1673
1674 if (const ConstantDataSequential *CDS =
1675 dyn_cast<ConstantDataSequential>(C)) {
1676 SmallVector<SDValue, 4> Ops;
1677 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1678 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1679 // Add each leaf value from the operand to the Constants list
1680 // to form a flattened list of all the values.
1681 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1682 Ops.push_back(SDValue(Val, i));
1683 }
1684
1685 if (isa<ArrayType>(CDS->getType()))
1686 return DAG.getMergeValues(Ops, getCurSDLoc());
1687 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1688 }
1689
1690 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1691 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&(static_cast <bool> ((isa<ConstantAggregateZero>(
C) || isa<UndefValue>(C)) && "Unknown struct or array constant!"
) ? void (0) : __assert_fail ("(isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && \"Unknown struct or array constant!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1692
, __extension__ __PRETTY_FUNCTION__))
1692 "Unknown struct or array constant!")(static_cast <bool> ((isa<ConstantAggregateZero>(
C) || isa<UndefValue>(C)) && "Unknown struct or array constant!"
) ? void (0) : __assert_fail ("(isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) && \"Unknown struct or array constant!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1692
, __extension__ __PRETTY_FUNCTION__))
;
1693
1694 SmallVector<EVT, 4> ValueVTs;
1695 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1696 unsigned NumElts = ValueVTs.size();
1697 if (NumElts == 0)
1698 return SDValue(); // empty struct
1699 SmallVector<SDValue, 4> Constants(NumElts);
1700 for (unsigned i = 0; i != NumElts; ++i) {
1701 EVT EltVT = ValueVTs[i];
1702 if (isa<UndefValue>(C))
1703 Constants[i] = DAG.getUNDEF(EltVT);
1704 else if (EltVT.isFloatingPoint())
1705 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1706 else
1707 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1708 }
1709
1710 return DAG.getMergeValues(Constants, getCurSDLoc());
1711 }
1712
1713 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1714 return DAG.getBlockAddress(BA, VT);
1715
1716 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1717 return getValue(Equiv->getGlobalValue());
1718
1719 if (const auto *NC = dyn_cast<NoCFIValue>(C))
1720 return getValue(NC->getGlobalValue());
1721
1722 VectorType *VecTy = cast<VectorType>(V->getType());
1723
1724 // Now that we know the number and type of the elements, get that number of
1725 // elements into the Ops array based on what kind of constant it is.
1726 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1727 SmallVector<SDValue, 16> Ops;
1728 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1729 for (unsigned i = 0; i != NumElements; ++i)
1730 Ops.push_back(getValue(CV->getOperand(i)));
1731
1732 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1733 }
1734
1735 if (isa<ConstantAggregateZero>(C)) {
1736 EVT EltVT =
1737 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1738
1739 SDValue Op;
1740 if (EltVT.isFloatingPoint())
1741 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1742 else
1743 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1744
1745 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1746 }
1747
1748 llvm_unreachable("Unknown vector constant")::llvm::llvm_unreachable_internal("Unknown vector constant", "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 1748)
;
1749 }
1750
1751 // If this is a static alloca, generate it as the frameindex instead of
1752 // computation.
1753 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1754 DenseMap<const AllocaInst*, int>::iterator SI =
1755 FuncInfo.StaticAllocaMap.find(AI);
1756 if (SI != FuncInfo.StaticAllocaMap.end())
1757 return DAG.getFrameIndex(
1758 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1759 }
1760
1761 // If this is an instruction which fast-isel has deferred, select it now.
1762 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1763 Register InReg = FuncInfo.InitializeRegForValue(Inst);
1764
1765 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1766 Inst->getType(), std::nullopt);
1767 SDValue Chain = DAG.getEntryNode();
1768 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1769 }
1770
1771 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1772 return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1773
1774 if (const auto *BB = dyn_cast<BasicBlock>(V))
1775 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1776
1777 llvm_unreachable("Can't get register for value!")::llvm::llvm_unreachable_internal("Can't get register for value!"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1777
)
;
1778}
1779
1780void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1781 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1782 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1783 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1784 bool IsSEH = isAsynchronousEHPersonality(Pers);
1785 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1786 if (!IsSEH)
1787 CatchPadMBB->setIsEHScopeEntry();
1788 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1789 if (IsMSVCCXX || IsCoreCLR)
1790 CatchPadMBB->setIsEHFuncletEntry();
1791}
1792
1793void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1794 // Update machine-CFG edge.
1795 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1796 FuncInfo.MBB->addSuccessor(TargetMBB);
1797 TargetMBB->setIsEHCatchretTarget(true);
1798 DAG.getMachineFunction().setHasEHCatchret(true);
1799
1800 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1801 bool IsSEH = isAsynchronousEHPersonality(Pers);
1802 if (IsSEH) {
1803 // If this is not a fall-through branch or optimizations are switched off,
1804 // emit the branch.
1805 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1806 TM.getOptLevel() == CodeGenOpt::None)
1807 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1808 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1809 return;
1810 }
1811
1812 // Figure out the funclet membership for the catchret's successor.
1813 // This will be used by the FuncletLayout pass to determine how to order the
1814 // BB's.
1815 // A 'catchret' returns to the outer scope's color.
1816 Value *ParentPad = I.getCatchSwitchParentPad();
1817 const BasicBlock *SuccessorColor;
1818 if (isa<ConstantTokenNone>(ParentPad))
1819 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1820 else
1821 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1822 assert(SuccessorColor && "No parent funclet for catchret!")(static_cast <bool> (SuccessorColor && "No parent funclet for catchret!"
) ? void (0) : __assert_fail ("SuccessorColor && \"No parent funclet for catchret!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1822
, __extension__ __PRETTY_FUNCTION__))
;
1823 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1824 assert(SuccessorColorMBB && "No MBB for SuccessorColor!")(static_cast <bool> (SuccessorColorMBB && "No MBB for SuccessorColor!"
) ? void (0) : __assert_fail ("SuccessorColorMBB && \"No MBB for SuccessorColor!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1824
, __extension__ __PRETTY_FUNCTION__))
;
1825
1826 // Create the terminator node.
1827 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1828 getControlRoot(), DAG.getBasicBlock(TargetMBB),
1829 DAG.getBasicBlock(SuccessorColorMBB));
1830 DAG.setRoot(Ret);
1831}
1832
1833void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1834 // Don't emit any special code for the cleanuppad instruction. It just marks
1835 // the start of an EH scope/funclet.
1836 FuncInfo.MBB->setIsEHScopeEntry();
1837 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1838 if (Pers != EHPersonality::Wasm_CXX) {
1839 FuncInfo.MBB->setIsEHFuncletEntry();
1840 FuncInfo.MBB->setIsCleanupFuncletEntry();
1841 }
1842}
1843
1844// In wasm EH, even though a catchpad may not catch an exception if a tag does
1845// not match, it is OK to add only the first unwind destination catchpad to the
1846// successors, because there will be at least one invoke instruction within the
1847// catch scope that points to the next unwind destination, if one exists, so
1848// CFGSort cannot mess up with BB sorting order.
1849// (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1850// call within them, and catchpads only consisting of 'catch (...)' have a
1851// '__cxa_end_catch' call within them, both of which generate invokes in case
1852// the next unwind destination exists, i.e., the next unwind destination is not
1853// the caller.)
1854//
1855// Having at most one EH pad successor is also simpler and helps later
1856// transformations.
1857//
1858// For example,
1859// current:
1860// invoke void @foo to ... unwind label %catch.dispatch
1861// catch.dispatch:
1862// %0 = catchswitch within ... [label %catch.start] unwind label %next
1863// catch.start:
1864// ...
1865// ... in this BB or some other child BB dominated by this BB there will be an
1866// invoke that points to 'next' BB as an unwind destination
1867//
1868// next: ; We don't need to add this to 'current' BB's successor
1869// ...
1870static void findWasmUnwindDestinations(
1871 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1872 BranchProbability Prob,
1873 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1874 &UnwindDests) {
1875 while (EHPadBB) {
1876 const Instruction *Pad = EHPadBB->getFirstNonPHI();
1877 if (isa<CleanupPadInst>(Pad)) {
1878 // Stop on cleanup pads.
1879 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1880 UnwindDests.back().first->setIsEHScopeEntry();
1881 break;
1882 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1883 // Add the catchpad handlers to the possible destinations. We don't
1884 // continue to the unwind destination of the catchswitch for wasm.
1885 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1886 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1887 UnwindDests.back().first->setIsEHScopeEntry();
1888 }
1889 break;
1890 } else {
1891 continue;
1892 }
1893 }
1894}
1895
1896/// When an invoke or a cleanupret unwinds to the next EH pad, there are
1897/// many places it could ultimately go. In the IR, we have a single unwind
1898/// destination, but in the machine CFG, we enumerate all the possible blocks.
1899/// This function skips over imaginary basic blocks that hold catchswitch
1900/// instructions, and finds all the "real" machine
1901/// basic block destinations. As those destinations may not be successors of
1902/// EHPadBB, here we also calculate the edge probability to those destinations.
1903/// The passed-in Prob is the edge probability to EHPadBB.
1904static void findUnwindDestinations(
1905 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1906 BranchProbability Prob,
1907 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1908 &UnwindDests) {
1909 EHPersonality Personality =
1910 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1911 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1912 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1913 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1914 bool IsSEH = isAsynchronousEHPersonality(Personality);
1915
1916 if (IsWasmCXX) {
1917 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1918 assert(UnwindDests.size() <= 1 &&(static_cast <bool> (UnwindDests.size() <= 1 &&
"There should be at most one unwind destination for wasm") ?
void (0) : __assert_fail ("UnwindDests.size() <= 1 && \"There should be at most one unwind destination for wasm\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1919
, __extension__ __PRETTY_FUNCTION__))
1919 "There should be at most one unwind destination for wasm")(static_cast <bool> (UnwindDests.size() <= 1 &&
"There should be at most one unwind destination for wasm") ?
void (0) : __assert_fail ("UnwindDests.size() <= 1 && \"There should be at most one unwind destination for wasm\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 1919
, __extension__ __PRETTY_FUNCTION__))
;
1920 return;
1921 }
1922
1923 while (EHPadBB) {
1924 const Instruction *Pad = EHPadBB->getFirstNonPHI();
1925 BasicBlock *NewEHPadBB = nullptr;
1926 if (isa<LandingPadInst>(Pad)) {
1927 // Stop on landingpads. They are not funclets.
1928 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1929 break;
1930 } else if (isa<CleanupPadInst>(Pad)) {
1931 // Stop on cleanup pads. Cleanups are always funclet entries for all known
1932 // personalities.
1933 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1934 UnwindDests.back().first->setIsEHScopeEntry();
1935 UnwindDests.back().first->setIsEHFuncletEntry();
1936 break;
1937 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1938 // Add the catchpad handlers to the possible destinations.
1939 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1940 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1941 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1942 if (IsMSVCCXX || IsCoreCLR)
1943 UnwindDests.back().first->setIsEHFuncletEntry();
1944 if (!IsSEH)
1945 UnwindDests.back().first->setIsEHScopeEntry();
1946 }
1947 NewEHPadBB = CatchSwitch->getUnwindDest();
1948 } else {
1949 continue;
1950 }
1951
1952 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1953 if (BPI && NewEHPadBB)
1954 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1955 EHPadBB = NewEHPadBB;
1956 }
1957}
1958
1959void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1960 // Update successor info.
1961 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1962 auto UnwindDest = I.getUnwindDest();
1963 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1964 BranchProbability UnwindDestProb =
1965 (BPI && UnwindDest)
1966 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1967 : BranchProbability::getZero();
1968 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1969 for (auto &UnwindDest : UnwindDests) {
1970 UnwindDest.first->setIsEHPad();
1971 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1972 }
1973 FuncInfo.MBB->normalizeSuccProbs();
1974
1975 // Create the terminator node.
1976 SDValue Ret =
1977 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1978 DAG.setRoot(Ret);
1979}
1980
1981void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1982 report_fatal_error("visitCatchSwitch not yet implemented!");
1983}
1984
1985void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1986 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1987 auto &DL = DAG.getDataLayout();
1988 SDValue Chain = getControlRoot();
1989 SmallVector<ISD::OutputArg, 8> Outs;
1990 SmallVector<SDValue, 8> OutVals;
1991
1992 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1993 // lower
1994 //
1995 // %val = call <ty> @llvm.experimental.deoptimize()
1996 // ret <ty> %val
1997 //
1998 // differently.
1999 if (I.getParent()->getTerminatingDeoptimizeCall()) {
2000 LowerDeoptimizingReturn();
2001 return;
2002 }
2003
2004 if (!FuncInfo.CanLowerReturn) {
2005 unsigned DemoteReg = FuncInfo.DemoteRegister;
2006 const Function *F = I.getParent()->getParent();
2007
2008 // Emit a store of the return value through the virtual register.
2009 // Leave Outs empty so that LowerReturn won't try to load return
2010 // registers the usual way.
2011 SmallVector<EVT, 1> PtrValueVTs;
2012 ComputeValueVTs(TLI, DL,
2013 F->getReturnType()->getPointerTo(
2014 DAG.getDataLayout().getAllocaAddrSpace()),
2015 PtrValueVTs);
2016
2017 SDValue RetPtr =
2018 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2019 SDValue RetOp = getValue(I.getOperand(0));
2020
2021 SmallVector<EVT, 4> ValueVTs, MemVTs;
2022 SmallVector<uint64_t, 4> Offsets;
2023 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2024 &Offsets);
2025 unsigned NumValues = ValueVTs.size();
2026
2027 SmallVector<SDValue, 4> Chains(NumValues);
2028 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2029 for (unsigned i = 0; i != NumValues; ++i) {
2030 // An aggregate return value cannot wrap around the address space, so
2031 // offsets to its parts don't wrap either.
2032 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2033 TypeSize::Fixed(Offsets[i]));
2034
2035 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2036 if (MemVTs[i] != ValueVTs[i])
2037 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2038 Chains[i] = DAG.getStore(
2039 Chain, getCurSDLoc(), Val,
2040 // FIXME: better loc info would be nice.
2041 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2042 commonAlignment(BaseAlign, Offsets[i]));
2043 }
2044
2045 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2046 MVT::Other, Chains);
2047 } else if (I.getNumOperands() != 0) {
2048 SmallVector<EVT, 4> ValueVTs;
2049 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2050 unsigned NumValues = ValueVTs.size();
2051 if (NumValues) {
2052 SDValue RetOp = getValue(I.getOperand(0));
2053
2054 const Function *F = I.getParent()->getParent();
2055
2056 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2057 I.getOperand(0)->getType(), F->getCallingConv(),
2058 /*IsVarArg*/ false, DL);
2059
2060 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2061 if (F->getAttributes().hasRetAttr(Attribute::SExt))
2062 ExtendKind = ISD::SIGN_EXTEND;
2063 else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2064 ExtendKind = ISD::ZERO_EXTEND;
2065
2066 LLVMContext &Context = F->getContext();
2067 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2068
2069 for (unsigned j = 0; j != NumValues; ++j) {
2070 EVT VT = ValueVTs[j];
2071
2072 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2073 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2074
2075 CallingConv::ID CC = F->getCallingConv();
2076
2077 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2078 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2079 SmallVector<SDValue, 4> Parts(NumParts);
2080 getCopyToParts(DAG, getCurSDLoc(),
2081 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2082 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2083
2084 // 'inreg' on function refers to return value
2085 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2086 if (RetInReg)
2087 Flags.setInReg();
2088
2089 if (I.getOperand(0)->getType()->isPointerTy()) {
2090 Flags.setPointer();
2091 Flags.setPointerAddrSpace(
2092 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2093 }
2094
2095 if (NeedsRegBlock) {
2096 Flags.setInConsecutiveRegs();
2097 if (j == NumValues - 1)
2098 Flags.setInConsecutiveRegsLast();
2099 }
2100
2101 // Propagate extension type if any
2102 if (ExtendKind == ISD::SIGN_EXTEND)
2103 Flags.setSExt();
2104 else if (ExtendKind == ISD::ZERO_EXTEND)
2105 Flags.setZExt();
2106
2107 for (unsigned i = 0; i < NumParts; ++i) {
2108 Outs.push_back(ISD::OutputArg(Flags,
2109 Parts[i].getValueType().getSimpleVT(),
2110 VT, /*isfixed=*/true, 0, 0));
2111 OutVals.push_back(Parts[i]);
2112 }
2113 }
2114 }
2115 }
2116
2117 // Push in swifterror virtual register as the last element of Outs. This makes
2118 // sure swifterror virtual register will be returned in the swifterror
2119 // physical register.
2120 const Function *F = I.getParent()->getParent();
2121 if (TLI.supportSwiftError() &&
2122 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2123 assert(SwiftError.getFunctionArg() && "Need a swift error argument")(static_cast <bool> (SwiftError.getFunctionArg() &&
"Need a swift error argument") ? void (0) : __assert_fail ("SwiftError.getFunctionArg() && \"Need a swift error argument\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2123
, __extension__ __PRETTY_FUNCTION__))
;
2124 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2125 Flags.setSwiftError();
2126 Outs.push_back(ISD::OutputArg(
2127 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2128 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2129 // Create SDNode for the swifterror virtual register.
2130 OutVals.push_back(
2131 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2132 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2133 EVT(TLI.getPointerTy(DL))));
2134 }
2135
2136 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2137 CallingConv::ID CallConv =
2138 DAG.getMachineFunction().getFunction().getCallingConv();
2139 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2140 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2141
2142 // Verify that the target's LowerReturn behaved as expected.
2143 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&(static_cast <bool> (Chain.getNode() && Chain.getValueType
() == MVT::Other && "LowerReturn didn't return a valid chain!"
) ? void (0) : __assert_fail ("Chain.getNode() && Chain.getValueType() == MVT::Other && \"LowerReturn didn't return a valid chain!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2144
, __extension__ __PRETTY_FUNCTION__))
2144 "LowerReturn didn't return a valid chain!")(static_cast <bool> (Chain.getNode() && Chain.getValueType
() == MVT::Other && "LowerReturn didn't return a valid chain!"
) ? void (0) : __assert_fail ("Chain.getNode() && Chain.getValueType() == MVT::Other && \"LowerReturn didn't return a valid chain!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2144
, __extension__ __PRETTY_FUNCTION__))
;
2145
2146 // Update the DAG with the new chain value resulting from return lowering.
2147 DAG.setRoot(Chain);
2148}
2149
2150/// CopyToExportRegsIfNeeded - If the given value has virtual registers
2151/// created for it, emit nodes to copy the value into the virtual
2152/// registers.
2153void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2154 // Skip empty types
2155 if (V->getType()->isEmptyTy())
2156 return;
2157
2158 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2159 if (VMI != FuncInfo.ValueMap.end()) {
2160 assert((!V->use_empty() || isa<CallBrInst>(V)) &&(static_cast <bool> ((!V->use_empty() || isa<CallBrInst
>(V)) && "Unused value assigned virtual registers!"
) ? void (0) : __assert_fail ("(!V->use_empty() || isa<CallBrInst>(V)) && \"Unused value assigned virtual registers!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2161
, __extension__ __PRETTY_FUNCTION__))
2161 "Unused value assigned virtual registers!")(static_cast <bool> ((!V->use_empty() || isa<CallBrInst
>(V)) && "Unused value assigned virtual registers!"
) ? void (0) : __assert_fail ("(!V->use_empty() || isa<CallBrInst>(V)) && \"Unused value assigned virtual registers!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2161
, __extension__ __PRETTY_FUNCTION__))
;
2162 CopyValueToVirtualRegister(V, VMI->second);
2163 }
2164}
2165
2166/// ExportFromCurrentBlock - If this condition isn't known to be exported from
2167/// the current basic block, add it to ValueMap now so that we'll get a
2168/// CopyTo/FromReg.
2169void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2170 // No need to export constants.
2171 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2172
2173 // Already exported?
2174 if (FuncInfo.isExportedInst(V)) return;
2175
2176 Register Reg = FuncInfo.InitializeRegForValue(V);
2177 CopyValueToVirtualRegister(V, Reg);
2178}
2179
2180bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2181 const BasicBlock *FromBB) {
2182 // The operands of the setcc have to be in this block. We don't know
2183 // how to export them from some other block.
2184 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2185 // Can export from current BB.
2186 if (VI->getParent() == FromBB)
2187 return true;
2188
2189 // Is already exported, noop.
2190 return FuncInfo.isExportedInst(V);
2191 }
2192
2193 // If this is an argument, we can export it if the BB is the entry block or
2194 // if it is already exported.
2195 if (isa<Argument>(V)) {
2196 if (FromBB->isEntryBlock())
2197 return true;
2198
2199 // Otherwise, can only export this if it is already exported.
2200 return FuncInfo.isExportedInst(V);
2201 }
2202
2203 // Otherwise, constants can always be exported.
2204 return true;
2205}
2206
2207/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2208BranchProbability
2209SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2210 const MachineBasicBlock *Dst) const {
2211 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2212 const BasicBlock *SrcBB = Src->getBasicBlock();
2213 const BasicBlock *DstBB = Dst->getBasicBlock();
2214 if (!BPI) {
2215 // If BPI is not available, set the default probability as 1 / N, where N is
2216 // the number of successors.
2217 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2218 return BranchProbability(1, SuccSize);
2219 }
2220 return BPI->getEdgeProbability(SrcBB, DstBB);
2221}
2222
2223void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2224 MachineBasicBlock *Dst,
2225 BranchProbability Prob) {
2226 if (!FuncInfo.BPI)
2227 Src->addSuccessorWithoutProb(Dst);
2228 else {
2229 if (Prob.isUnknown())
2230 Prob = getEdgeProbability(Src, Dst);
2231 Src->addSuccessor(Dst, Prob);
2232 }
2233}
2234
2235static bool InBlock(const Value *V, const BasicBlock *BB) {
2236 if (const Instruction *I = dyn_cast<Instruction>(V))
2237 return I->getParent() == BB;
2238 return true;
2239}
2240
2241/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2242/// This function emits a branch and is used at the leaves of an OR or an
2243/// AND operator tree.
2244void
2245SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2246 MachineBasicBlock *TBB,
2247 MachineBasicBlock *FBB,
2248 MachineBasicBlock *CurBB,
2249 MachineBasicBlock *SwitchBB,
2250 BranchProbability TProb,
2251 BranchProbability FProb,
2252 bool InvertCond) {
2253 const BasicBlock *BB = CurBB->getBasicBlock();
2254
2255 // If the leaf of the tree is a comparison, merge the condition into
2256 // the caseblock.
2257 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2258 // The operands of the cmp have to be in this block. We don't know
2259 // how to export them from some other block. If this is the first block
2260 // of the sequence, no exporting is needed.
2261 if (CurBB == SwitchBB ||
2262 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2263 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2264 ISD::CondCode Condition;
2265 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2266 ICmpInst::Predicate Pred =
2267 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2268 Condition = getICmpCondCode(Pred);
2269 } else {
2270 const FCmpInst *FC = cast<FCmpInst>(Cond);
2271 FCmpInst::Predicate Pred =
2272 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2273 Condition = getFCmpCondCode(Pred);
2274 if (TM.Options.NoNaNsFPMath)
2275 Condition = getFCmpCodeWithoutNaN(Condition);
2276 }
2277
2278 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2279 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2280 SL->SwitchCases.push_back(CB);
2281 return;
2282 }
2283 }
2284
2285 // Create a CaseBlock record representing this branch.
2286 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2287 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2288 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2289 SL->SwitchCases.push_back(CB);
2290}
2291
2292void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2293 MachineBasicBlock *TBB,
2294 MachineBasicBlock *FBB,
2295 MachineBasicBlock *CurBB,
2296 MachineBasicBlock *SwitchBB,
2297 Instruction::BinaryOps Opc,
2298 BranchProbability TProb,
2299 BranchProbability FProb,
2300 bool InvertCond) {
2301 // Skip over not part of the tree and remember to invert op and operands at
2302 // next level.
2303 Value *NotCond;
2304 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2305 InBlock(NotCond, CurBB->getBasicBlock())) {
2306 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2307 !InvertCond);
2308 return;
2309 }
2310
2311 const Instruction *BOp = dyn_cast<Instruction>(Cond);
2312 const Value *BOpOp0, *BOpOp1;
2313 // Compute the effective opcode for Cond, taking into account whether it needs
2314 // to be inverted, e.g.
2315 // and (not (or A, B)), C
2316 // gets lowered as
2317 // and (and (not A, not B), C)
2318 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2319 if (BOp) {
2320 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2321 ? Instruction::And
2322 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2323 ? Instruction::Or
2324 : (Instruction::BinaryOps)0);
2325 if (InvertCond) {
2326 if (BOpc == Instruction::And)
2327 BOpc = Instruction::Or;
2328 else if (BOpc == Instruction::Or)
2329 BOpc = Instruction::And;
2330 }
2331 }
2332
2333 // If this node is not part of the or/and tree, emit it as a branch.
2334 // Note that all nodes in the tree should have same opcode.
2335 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2336 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2337 !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2338 !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2339 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2340 TProb, FProb, InvertCond);
2341 return;
2342 }
2343
2344 // Create TmpBB after CurBB.
2345 MachineFunction::iterator BBI(CurBB);
2346 MachineFunction &MF = DAG.getMachineFunction();
2347 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2348 CurBB->getParent()->insert(++BBI, TmpBB);
2349
2350 if (Opc == Instruction::Or) {
2351 // Codegen X | Y as:
2352 // BB1:
2353 // jmp_if_X TBB
2354 // jmp TmpBB
2355 // TmpBB:
2356 // jmp_if_Y TBB
2357 // jmp FBB
2358 //
2359
2360 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2361 // The requirement is that
2362 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2363 // = TrueProb for original BB.
2364 // Assuming the original probabilities are A and B, one choice is to set
2365 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2366 // A/(1+B) and 2B/(1+B). This choice assumes that
2367 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2368 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2369 // TmpBB, but the math is more complicated.
2370
2371 auto NewTrueProb = TProb / 2;
2372 auto NewFalseProb = TProb / 2 + FProb;
2373 // Emit the LHS condition.
2374 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2375 NewFalseProb, InvertCond);
2376
2377 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2378 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2379 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2380 // Emit the RHS condition into TmpBB.
2381 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2382 Probs[1], InvertCond);
2383 } else {
2384 assert(Opc == Instruction::And && "Unknown merge op!")(static_cast <bool> (Opc == Instruction::And &&
"Unknown merge op!") ? void (0) : __assert_fail ("Opc == Instruction::And && \"Unknown merge op!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2384
, __extension__ __PRETTY_FUNCTION__))
;
2385 // Codegen X & Y as:
2386 // BB1:
2387 // jmp_if_X TmpBB
2388 // jmp FBB
2389 // TmpBB:
2390 // jmp_if_Y TBB
2391 // jmp FBB
2392 //
2393 // This requires creation of TmpBB after CurBB.
2394
2395 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2396 // The requirement is that
2397 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2398 // = FalseProb for original BB.
2399 // Assuming the original probabilities are A and B, one choice is to set
2400 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2401 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2402 // TrueProb for BB1 * FalseProb for TmpBB.
2403
2404 auto NewTrueProb = TProb + FProb / 2;
2405 auto NewFalseProb = FProb / 2;
2406 // Emit the LHS condition.
2407 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2408 NewFalseProb, InvertCond);
2409
2410 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2411 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2412 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2413 // Emit the RHS condition into TmpBB.
2414 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2415 Probs[1], InvertCond);
2416 }
2417}
2418
2419/// If the set of cases should be emitted as a series of branches, return true.
2420/// If we should emit this as a bunch of and/or'd together conditions, return
2421/// false.
2422bool
2423SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2424 if (Cases.size() != 2) return true;
2425
2426 // If this is two comparisons of the same values or'd or and'd together, they
2427 // will get folded into a single comparison, so don't emit two blocks.
2428 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2429 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2430 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2431 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2432 return false;
2433 }
2434
2435 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2436 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2437 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2438 Cases[0].CC == Cases[1].CC &&
2439 isa<Constant>(Cases[0].CmpRHS) &&
2440 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2441 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2442 return false;
2443 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2444 return false;
2445 }
2446
2447 return true;
2448}
2449
2450void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2451 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2452
2453 // Update machine-CFG edges.
2454 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2455
2456 if (I.isUnconditional()) {
2457 // Update machine-CFG edges.
2458 BrMBB->addSuccessor(Succ0MBB);
2459
2460 // If this is not a fall-through branch or optimizations are switched off,
2461 // emit the branch.
2462 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2463 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2464 MVT::Other, getControlRoot(),
2465 DAG.getBasicBlock(Succ0MBB)));
2466
2467 return;
2468 }
2469
2470 // If this condition is one of the special cases we handle, do special stuff
2471 // now.
2472 const Value *CondVal = I.getCondition();
2473 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2474
2475 // If this is a series of conditions that are or'd or and'd together, emit
2476 // this as a sequence of branches instead of setcc's with and/or operations.
2477 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2478 // unpredictable branches, and vector extracts because those jumps are likely
2479 // expensive for any target), this should improve performance.
2480 // For example, instead of something like:
2481 // cmp A, B
2482 // C = seteq
2483 // cmp D, E
2484 // F = setle
2485 // or C, F
2486 // jnz foo
2487 // Emit:
2488 // cmp A, B
2489 // je foo
2490 // cmp D, E
2491 // jle foo
2492 const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2493 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2494 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2495 Value *Vec;
2496 const Value *BOp0, *BOp1;
2497 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2498 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2499 Opcode = Instruction::And;
2500 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2501 Opcode = Instruction::Or;
2502
2503 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2504 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2505 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2506 getEdgeProbability(BrMBB, Succ0MBB),
2507 getEdgeProbability(BrMBB, Succ1MBB),
2508 /*InvertCond=*/false);
2509 // If the compares in later blocks need to use values not currently
2510 // exported from this block, export them now. This block should always
2511 // be the first entry.
2512 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!")(static_cast <bool> (SL->SwitchCases[0].ThisBB == BrMBB
&& "Unexpected lowering!") ? void (0) : __assert_fail
("SL->SwitchCases[0].ThisBB == BrMBB && \"Unexpected lowering!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2512
, __extension__ __PRETTY_FUNCTION__))
;
2513
2514 // Allow some cases to be rejected.
2515 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2516 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2517 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2518 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2519 }
2520
2521 // Emit the branch for this block.
2522 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2523 SL->SwitchCases.erase(SL->SwitchCases.begin());
2524 return;
2525 }
2526
2527 // Okay, we decided not to do this, remove any inserted MBB's and clear
2528 // SwitchCases.
2529 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2530 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2531
2532 SL->SwitchCases.clear();
2533 }
2534 }
2535
2536 // Create a CaseBlock record representing this branch.
2537 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2538 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2539
2540 // Use visitSwitchCase to actually insert the fast branch sequence for this
2541 // cond branch.
2542 visitSwitchCase(CB, BrMBB);
2543}
2544
2545/// visitSwitchCase - Emits the necessary code to represent a single node in
2546/// the binary search tree resulting from lowering a switch instruction.
2547void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2548 MachineBasicBlock *SwitchBB) {
2549 SDValue Cond;
2550 SDValue CondLHS = getValue(CB.CmpLHS);
2551 SDLoc dl = CB.DL;
2552
2553 if (CB.CC == ISD::SETTRUE) {
2554 // Branch or fall through to TrueBB.
2555 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2556 SwitchBB->normalizeSuccProbs();
2557 if (CB.TrueBB != NextBlock(SwitchBB)) {
2558 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2559 DAG.getBasicBlock(CB.TrueBB)));
2560 }
2561 return;
2562 }
2563
2564 auto &TLI = DAG.getTargetLoweringInfo();
2565 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2566
2567 // Build the setcc now.
2568 if (!CB.CmpMHS) {
2569 // Fold "(X == true)" to X and "(X == false)" to !X to
2570 // handle common cases produced by branch lowering.
2571 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2572 CB.CC == ISD::SETEQ)
2573 Cond = CondLHS;
2574 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2575 CB.CC == ISD::SETEQ) {
2576 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2577 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2578 } else {
2579 SDValue CondRHS = getValue(CB.CmpRHS);
2580
2581 // If a pointer's DAG type is larger than its memory type then the DAG
2582 // values are zero-extended. This breaks signed comparisons so truncate
2583 // back to the underlying type before doing the compare.
2584 if (CondLHS.getValueType() != MemVT) {
2585 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2586 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2587 }
2588 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2589 }
2590 } else {
2591 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now")(static_cast <bool> (CB.CC == ISD::SETLE && "Can handle only LE ranges now"
) ? void (0) : __assert_fail ("CB.CC == ISD::SETLE && \"Can handle only LE ranges now\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2591
, __extension__ __PRETTY_FUNCTION__))
;
2592
2593 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2594 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2595
2596 SDValue CmpOp = getValue(CB.CmpMHS);
2597 EVT VT = CmpOp.getValueType();
2598
2599 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2600 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2601 ISD::SETLE);
2602 } else {
2603 SDValue SUB = DAG.getNode(ISD::SUB, dl,
2604 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2605 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2606 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2607 }
2608 }
2609
2610 // Update successor info
2611 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2612 // TrueBB and FalseBB are always different unless the incoming IR is
2613 // degenerate. This only happens when running llc on weird IR.
2614 if (CB.TrueBB != CB.FalseBB)
2615 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2616 SwitchBB->normalizeSuccProbs();
2617
2618 // If the lhs block is the next block, invert the condition so that we can
2619 // fall through to the lhs instead of the rhs block.
2620 if (CB.TrueBB == NextBlock(SwitchBB)) {
2621 std::swap(CB.TrueBB, CB.FalseBB);
2622 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2623 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2624 }
2625
2626 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2627 MVT::Other, getControlRoot(), Cond,
2628 DAG.getBasicBlock(CB.TrueBB));
2629
2630 setValue(CurInst, BrCond);
2631
2632 // Insert the false branch. Do this even if it's a fall through branch,
2633 // this makes it easier to do DAG optimizations which require inverting
2634 // the branch condition.
2635 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2636 DAG.getBasicBlock(CB.FalseBB));
2637
2638 DAG.setRoot(BrCond);
2639}
2640
2641/// visitJumpTable - Emit JumpTable node in the current MBB
2642void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2643 // Emit the code for the jump table
2644 assert(JT.Reg != -1U && "Should lower JT Header first!")(static_cast <bool> (JT.Reg != -1U && "Should lower JT Header first!"
) ? void (0) : __assert_fail ("JT.Reg != -1U && \"Should lower JT Header first!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2644
, __extension__ __PRETTY_FUNCTION__))
;
2645 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2646 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2647 JT.Reg, PTy);
2648 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2649 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2650 MVT::Other, Index.getValue(1),
2651 Table, Index);
2652 DAG.setRoot(BrJumpTable);
2653}
2654
2655/// visitJumpTableHeader - This function emits necessary code to produce index
2656/// in the JumpTable from switch case.
2657void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2658 JumpTableHeader &JTH,
2659 MachineBasicBlock *SwitchBB) {
2660 SDLoc dl = getCurSDLoc();
2661
2662 // Subtract the lowest switch case value from the value being switched on.
2663 SDValue SwitchOp = getValue(JTH.SValue);
2664 EVT VT = SwitchOp.getValueType();
2665 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2666 DAG.getConstant(JTH.First, dl, VT));
2667
2668 // The SDNode we just created, which holds the value being switched on minus
2669 // the smallest case value, needs to be copied to a virtual register so it
2670 // can be used as an index into the jump table in a subsequent basic block.
2671 // This value may be smaller or larger than the target's pointer type, and
2672 // therefore require extension or truncating.
2673 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2674 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2675
2676 unsigned JumpTableReg =
2677 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2678 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2679 JumpTableReg, SwitchOp);
2680 JT.Reg = JumpTableReg;
2681
2682 if (!JTH.FallthroughUnreachable) {
2683 // Emit the range check for the jump table, and branch to the default block
2684 // for the switch statement if the value being switched on exceeds the
2685 // largest case in the switch.
2686 SDValue CMP = DAG.getSetCC(
2687 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2688 Sub.getValueType()),
2689 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2690
2691 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2692 MVT::Other, CopyTo, CMP,
2693 DAG.getBasicBlock(JT.Default));
2694
2695 // Avoid emitting unnecessary branches to the next block.
2696 if (JT.MBB != NextBlock(SwitchBB))
2697 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2698 DAG.getBasicBlock(JT.MBB));
2699
2700 DAG.setRoot(BrCond);
2701 } else {
2702 // Avoid emitting unnecessary branches to the next block.
2703 if (JT.MBB != NextBlock(SwitchBB))
2704 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2705 DAG.getBasicBlock(JT.MBB)));
2706 else
2707 DAG.setRoot(CopyTo);
2708 }
2709}
2710
2711/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2712/// variable if there exists one.
2713static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2714 SDValue &Chain) {
2715 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2716 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2717 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2718 MachineFunction &MF = DAG.getMachineFunction();
2719 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2720 MachineSDNode *Node =
2721 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2722 if (Global) {
2723 MachinePointerInfo MPInfo(Global);
2724 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2725 MachineMemOperand::MODereferenceable;
2726 MachineMemOperand *MemRef = MF.getMachineMemOperand(
2727 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2728 DAG.setNodeMemRefs(Node, {MemRef});
2729 }
2730 if (PtrTy != PtrMemTy)
2731 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2732 return SDValue(Node, 0);
2733}
2734
2735/// Codegen a new tail for a stack protector check ParentMBB which has had its
2736/// tail spliced into a stack protector check success bb.
2737///
2738/// For a high level explanation of how this fits into the stack protector
2739/// generation see the comment on the declaration of class
2740/// StackProtectorDescriptor.
2741void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2742 MachineBasicBlock *ParentBB) {
2743
2744 // First create the loads to the guard/stack slot for the comparison.
2745 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2746 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2747 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2748
2749 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2750 int FI = MFI.getStackProtectorIndex();
2751
2752 SDValue Guard;
2753 SDLoc dl = getCurSDLoc();
2754 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2755 const Module &M = *ParentBB->getParent()->getFunction().getParent();
2756 Align Align =
2757 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2758
2759 // Generate code to load the content of the guard slot.
2760 SDValue GuardVal = DAG.getLoad(
2761 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2762 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2763 MachineMemOperand::MOVolatile);
2764
2765 if (TLI.useStackGuardXorFP())
2766 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2767
2768 // Retrieve guard check function, nullptr if instrumentation is inlined.
2769 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2770 // The target provides a guard check function to validate the guard value.
2771 // Generate a call to that function with the content of the guard slot as
2772 // argument.
2773 FunctionType *FnTy = GuardCheckFn->getFunctionType();
2774 assert(FnTy->getNumParams() == 1 && "Invalid function signature")(static_cast <bool> (FnTy->getNumParams() == 1 &&
"Invalid function signature") ? void (0) : __assert_fail ("FnTy->getNumParams() == 1 && \"Invalid function signature\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2774
, __extension__ __PRETTY_FUNCTION__))
;
2775
2776 TargetLowering::ArgListTy Args;
2777 TargetLowering::ArgListEntry Entry;
2778 Entry.Node = GuardVal;
2779 Entry.Ty = FnTy->getParamType(0);
2780 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2781 Entry.IsInReg = true;
2782 Args.push_back(Entry);
2783
2784 TargetLowering::CallLoweringInfo CLI(DAG);
2785 CLI.setDebugLoc(getCurSDLoc())
2786 .setChain(DAG.getEntryNode())
2787 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2788 getValue(GuardCheckFn), std::move(Args));
2789
2790 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2791 DAG.setRoot(Result.second);
2792 return;
2793 }
2794
2795 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2796 // Otherwise, emit a volatile load to retrieve the stack guard value.
2797 SDValue Chain = DAG.getEntryNode();
2798 if (TLI.useLoadStackGuardNode()) {
2799 Guard = getLoadStackGuard(DAG, dl, Chain);
2800 } else {
2801 const Value *IRGuard = TLI.getSDagStackGuard(M);
2802 SDValue GuardPtr = getValue(IRGuard);
2803
2804 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2805 MachinePointerInfo(IRGuard, 0), Align,
2806 MachineMemOperand::MOVolatile);
2807 }
2808
2809 // Perform the comparison via a getsetcc.
2810 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2811 *DAG.getContext(),
2812 Guard.getValueType()),
2813 Guard, GuardVal, ISD::SETNE);
2814
2815 // If the guard/stackslot do not equal, branch to failure MBB.
2816 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2817 MVT::Other, GuardVal.getOperand(0),
2818 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2819 // Otherwise branch to success MBB.
2820 SDValue Br = DAG.getNode(ISD::BR, dl,
2821 MVT::Other, BrCond,
2822 DAG.getBasicBlock(SPD.getSuccessMBB()));
2823
2824 DAG.setRoot(Br);
2825}
2826
2827/// Codegen the failure basic block for a stack protector check.
2828///
2829/// A failure stack protector machine basic block consists simply of a call to
2830/// __stack_chk_fail().
2831///
2832/// For a high level explanation of how this fits into the stack protector
2833/// generation see the comment on the declaration of class
2834/// StackProtectorDescriptor.
2835void
2836SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2837 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2838 TargetLowering::MakeLibCallOptions CallOptions;
2839 CallOptions.setDiscardResult(true);
2840 SDValue Chain =
2841 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2842 std::nullopt, CallOptions, getCurSDLoc())
2843 .second;
2844 // On PS4/PS5, the "return address" must still be within the calling
2845 // function, even if it's at the very end, so emit an explicit TRAP here.
2846 // Passing 'true' for doesNotReturn above won't generate the trap for us.
2847 if (TM.getTargetTriple().isPS())
2848 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2849 // WebAssembly needs an unreachable instruction after a non-returning call,
2850 // because the function return type can be different from __stack_chk_fail's
2851 // return type (void).
2852 if (TM.getTargetTriple().isWasm())
2853 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2854
2855 DAG.setRoot(Chain);
2856}
2857
2858/// visitBitTestHeader - This function emits necessary code to produce value
2859/// suitable for "bit tests"
2860void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2861 MachineBasicBlock *SwitchBB) {
2862 SDLoc dl = getCurSDLoc();
2863
2864 // Subtract the minimum value.
2865 SDValue SwitchOp = getValue(B.SValue);
2866 EVT VT = SwitchOp.getValueType();
2867 SDValue RangeSub =
2868 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2869
2870 // Determine the type of the test operands.
2871 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2872 bool UsePtrType = false;
2873 if (!TLI.isTypeLegal(VT)) {
2874 UsePtrType = true;
2875 } else {
2876 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2877 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2878 // Switch table case range are encoded into series of masks.
2879 // Just use pointer type, it's guaranteed to fit.
2880 UsePtrType = true;
2881 break;
2882 }
2883 }
2884 SDValue Sub = RangeSub;
2885 if (UsePtrType) {
2886 VT = TLI.getPointerTy(DAG.getDataLayout());
2887 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2888 }
2889
2890 B.RegVT = VT.getSimpleVT();
2891 B.Reg = FuncInfo.CreateReg(B.RegVT);
2892 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2893
2894 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2895
2896 if (!B.FallthroughUnreachable)
2897 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2898 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2899 SwitchBB->normalizeSuccProbs();
2900
2901 SDValue Root = CopyTo;
2902 if (!B.FallthroughUnreachable) {
2903 // Conditional branch to the default block.
2904 SDValue RangeCmp = DAG.getSetCC(dl,
2905 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2906 RangeSub.getValueType()),
2907 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2908 ISD::SETUGT);
2909
2910 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2911 DAG.getBasicBlock(B.Default));
2912 }
2913
2914 // Avoid emitting unnecessary branches to the next block.
2915 if (MBB != NextBlock(SwitchBB))
2916 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2917
2918 DAG.setRoot(Root);
2919}
2920
2921/// visitBitTestCase - this function produces one "bit test"
2922void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2923 MachineBasicBlock* NextMBB,
2924 BranchProbability BranchProbToNext,
2925 unsigned Reg,
2926 BitTestCase &B,
2927 MachineBasicBlock *SwitchBB) {
2928 SDLoc dl = getCurSDLoc();
2929 MVT VT = BB.RegVT;
2930 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2931 SDValue Cmp;
2932 unsigned PopCount = llvm::popcount(B.Mask);
2933 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2934 if (PopCount == 1) {
2935 // Testing for a single bit; just compare the shift count with what it
2936 // would need to be to shift a 1 bit in that position.
2937 Cmp = DAG.getSetCC(
2938 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2939 ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
2940 ISD::SETEQ);
2941 } else if (PopCount == BB.Range) {
2942 // There is only one zero bit in the range, test for it directly.
2943 Cmp = DAG.getSetCC(
2944 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2945 ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
2946 } else {
2947 // Make desired shift
2948 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2949 DAG.getConstant(1, dl, VT), ShiftOp);
2950
2951 // Emit bit tests and jumps
2952 SDValue AndOp = DAG.getNode(ISD::AND, dl,
2953 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2954 Cmp = DAG.getSetCC(
2955 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2956 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2957 }
2958
2959 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2960 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2961 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2962 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2963 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2964 // one as they are relative probabilities (and thus work more like weights),
2965 // and hence we need to normalize them to let the sum of them become one.
2966 SwitchBB->normalizeSuccProbs();
2967
2968 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2969 MVT::Other, getControlRoot(),
2970 Cmp, DAG.getBasicBlock(B.TargetBB));
2971
2972 // Avoid emitting unnecessary branches to the next block.
2973 if (NextMBB != NextBlock(SwitchBB))
2974 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2975 DAG.getBasicBlock(NextMBB));
2976
2977 DAG.setRoot(BrAnd);
2978}
2979
2980void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2981 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2982
2983 // Retrieve successors. Look through artificial IR level blocks like
2984 // catchswitch for successors.
2985 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2986 const BasicBlock *EHPadBB = I.getSuccessor(1);
2987 MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
2988
2989 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2990 // have to do anything here to lower funclet bundles.
2991 assert(!I.hasOperandBundlesOtherThan((static_cast <bool> (!I.hasOperandBundlesOtherThan( {LLVMContext
::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live
, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext
::OB_clang_arc_attachedcall}) && "Cannot lower invokes with arbitrary operand bundles yet!"
) ? void (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext::OB_clang_arc_attachedcall}) && \"Cannot lower invokes with arbitrary operand bundles yet!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2996
, __extension__ __PRETTY_FUNCTION__))
2992 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,(static_cast <bool> (!I.hasOperandBundlesOtherThan( {LLVMContext
::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live
, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext
::OB_clang_arc_attachedcall}) && "Cannot lower invokes with arbitrary operand bundles yet!"
) ? void (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext::OB_clang_arc_attachedcall}) && \"Cannot lower invokes with arbitrary operand bundles yet!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2996
, __extension__ __PRETTY_FUNCTION__))
2993 LLVMContext::OB_gc_live, LLVMContext::OB_funclet,(static_cast <bool> (!I.hasOperandBundlesOtherThan( {LLVMContext
::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live
, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext
::OB_clang_arc_attachedcall}) && "Cannot lower invokes with arbitrary operand bundles yet!"
) ? void (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext::OB_clang_arc_attachedcall}) && \"Cannot lower invokes with arbitrary operand bundles yet!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2996
, __extension__ __PRETTY_FUNCTION__))
2994 LLVMContext::OB_cfguardtarget,(static_cast <bool> (!I.hasOperandBundlesOtherThan( {LLVMContext
::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live
, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext
::OB_clang_arc_attachedcall}) && "Cannot lower invokes with arbitrary operand bundles yet!"
) ? void (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext::OB_clang_arc_attachedcall}) && \"Cannot lower invokes with arbitrary operand bundles yet!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2996
, __extension__ __PRETTY_FUNCTION__))
2995 LLVMContext::OB_clang_arc_attachedcall}) &&(static_cast <bool> (!I.hasOperandBundlesOtherThan( {LLVMContext
::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live
, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext
::OB_clang_arc_attachedcall}) && "Cannot lower invokes with arbitrary operand bundles yet!"
) ? void (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext::OB_clang_arc_attachedcall}) && \"Cannot lower invokes with arbitrary operand bundles yet!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2996
, __extension__ __PRETTY_FUNCTION__))
2996 "Cannot lower invokes with arbitrary operand bundles yet!")(static_cast <bool> (!I.hasOperandBundlesOtherThan( {LLVMContext
::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live
, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext
::OB_clang_arc_attachedcall}) && "Cannot lower invokes with arbitrary operand bundles yet!"
) ? void (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition, LLVMContext::OB_gc_live, LLVMContext::OB_funclet, LLVMContext::OB_cfguardtarget, LLVMContext::OB_clang_arc_attachedcall}) && \"Cannot lower invokes with arbitrary operand bundles yet!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 2996
, __extension__ __PRETTY_FUNCTION__))
;
2997
2998 const Value *Callee(I.getCalledOperand());
2999 const Function *Fn = dyn_cast<Function>(Callee);
3000 if (isa<InlineAsm>(Callee))
3001 visitInlineAsm(I, EHPadBB);
3002 else if (Fn && Fn->isIntrinsic()) {
3003 switch (Fn->getIntrinsicID()) {
3004 default:
3005 llvm_unreachable("Cannot invoke this intrinsic")::llvm::llvm_unreachable_internal("Cannot invoke this intrinsic"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3005
)
;
3006 case Intrinsic::donothing:
3007 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3008 case Intrinsic::seh_try_begin:
3009 case Intrinsic::seh_scope_begin:
3010 case Intrinsic::seh_try_end:
3011 case Intrinsic::seh_scope_end:
3012 if (EHPadMBB)
3013 // a block referenced by EH table
3014 // so dtor-funclet not removed by opts
3015 EHPadMBB->setMachineBlockAddressTaken();
3016 break;
3017 case Intrinsic::experimental_patchpoint_void:
3018 case Intrinsic::experimental_patchpoint_i64:
3019 visitPatchpoint(I, EHPadBB);
3020 break;
3021 case Intrinsic::experimental_gc_statepoint:
3022 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3023 break;
3024 case Intrinsic::wasm_rethrow: {
3025 // This is usually done in visitTargetIntrinsic, but this intrinsic is
3026 // special because it can be invoked, so we manually lower it to a DAG
3027 // node here.
3028 SmallVector<SDValue, 8> Ops;
3029 Ops.push_back(getRoot()); // inchain
3030 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3031 Ops.push_back(
3032 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3033 TLI.getPointerTy(DAG.getDataLayout())));
3034 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3035 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3036 break;
3037 }
3038 }
3039 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3040 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3041 // Eventually we will support lowering the @llvm.experimental.deoptimize
3042 // intrinsic, and right now there are no plans to support other intrinsics
3043 // with deopt state.
3044 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3045 } else {
3046 LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3047 }
3048
3049 // If the value of the invoke is used outside of its defining block, make it
3050 // available as a virtual register.
3051 // We already took care of the exported value for the statepoint instruction
3052 // during call to the LowerStatepoint.
3053 if (!isa<GCStatepointInst>(I)) {
3054 CopyToExportRegsIfNeeded(&I);
3055 }
3056
3057 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3058 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3059 BranchProbability EHPadBBProb =
3060 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3061 : BranchProbability::getZero();
3062 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3063
3064 // Update successor info.
3065 addSuccessorWithProb(InvokeMBB, Return);
3066 for (auto &UnwindDest : UnwindDests) {
3067 UnwindDest.first->setIsEHPad();
3068 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3069 }
3070 InvokeMBB->normalizeSuccProbs();
3071
3072 // Drop into normal successor.
3073 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3074 DAG.getBasicBlock(Return)));
3075}
3076
3077void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3078 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3079
3080 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3081 // have to do anything here to lower funclet bundles.
3082 assert(!I.hasOperandBundlesOtherThan((static_cast <bool> (!I.hasOperandBundlesOtherThan( {LLVMContext
::OB_deopt, LLVMContext::OB_funclet}) && "Cannot lower callbrs with arbitrary operand bundles yet!"
) ? void (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && \"Cannot lower callbrs with arbitrary operand bundles yet!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3084
, __extension__ __PRETTY_FUNCTION__))
3083 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&(static_cast <bool> (!I.hasOperandBundlesOtherThan( {LLVMContext
::OB_deopt, LLVMContext::OB_funclet}) && "Cannot lower callbrs with arbitrary operand bundles yet!"
) ? void (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && \"Cannot lower callbrs with arbitrary operand bundles yet!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3084
, __extension__ __PRETTY_FUNCTION__))
3084 "Cannot lower callbrs with arbitrary operand bundles yet!")(static_cast <bool> (!I.hasOperandBundlesOtherThan( {LLVMContext
::OB_deopt, LLVMContext::OB_funclet}) && "Cannot lower callbrs with arbitrary operand bundles yet!"
) ? void (0) : __assert_fail ("!I.hasOperandBundlesOtherThan( {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) && \"Cannot lower callbrs with arbitrary operand bundles yet!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3084
, __extension__ __PRETTY_FUNCTION__))
;
3085
3086 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr")(static_cast <bool> (I.isInlineAsm() && "Only know how to handle inlineasm callbr"
) ? void (0) : __assert_fail ("I.isInlineAsm() && \"Only know how to handle inlineasm callbr\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3086
, __extension__ __PRETTY_FUNCTION__))
;
3087 visitInlineAsm(I);
3088 CopyToExportRegsIfNeeded(&I);
3089
3090 // Retrieve successors.
3091 SmallPtrSet<BasicBlock *, 8> Dests;
3092 Dests.insert(I.getDefaultDest());
3093 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3094
3095 // Update successor info.
3096 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3097 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3098 BasicBlock *Dest = I.getIndirectDest(i);
3099 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3100 Target->setIsInlineAsmBrIndirectTarget();
3101 Target->setMachineBlockAddressTaken();
3102 Target->setLabelMustBeEmitted();
3103 // Don't add duplicate machine successors.
3104 if (Dests.insert(Dest).second)
3105 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3106 }
3107 CallBrMBB->normalizeSuccProbs();
3108
3109 // Drop into default successor.
3110 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3111 MVT::Other, getControlRoot(),
3112 DAG.getBasicBlock(Return)));
3113}
3114
3115void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3116 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!")::llvm::llvm_unreachable_internal("SelectionDAGBuilder shouldn't visit resume instructions!"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3116
)
;
3117}
3118
3119void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3120 assert(FuncInfo.MBB->isEHPad() &&(static_cast <bool> (FuncInfo.MBB->isEHPad() &&
"Call to landingpad not in landing pad!") ? void (0) : __assert_fail
("FuncInfo.MBB->isEHPad() && \"Call to landingpad not in landing pad!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3121
, __extension__ __PRETTY_FUNCTION__))
3121 "Call to landingpad not in landing pad!")(static_cast <bool> (FuncInfo.MBB->isEHPad() &&
"Call to landingpad not in landing pad!") ? void (0) : __assert_fail
("FuncInfo.MBB->isEHPad() && \"Call to landingpad not in landing pad!\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3121
, __extension__ __PRETTY_FUNCTION__))
;
3122
3123 // If there aren't registers to copy the values into (e.g., during SjLj
3124 // exceptions), then don't bother to create these DAG nodes.
3125 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3126 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3127 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3128 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3129 return;
3130
3131 // If landingpad's return type is token type, we don't create DAG nodes
3132 // for its exception pointer and selector value. The extraction of exception
3133 // pointer or selector value from token type landingpads is not currently
3134 // supported.
3135 if (LP.getType()->isTokenTy())
3136 return;
3137
3138 SmallVector<EVT, 2> ValueVTs;
3139 SDLoc dl = getCurSDLoc();
3140 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3141 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported")(static_cast <bool> (ValueVTs.size() == 2 && "Only two-valued landingpads are supported"
) ? void (0) : __assert_fail ("ValueVTs.size() == 2 && \"Only two-valued landingpads are supported\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3141
, __extension__ __PRETTY_FUNCTION__))
;
3142
3143 // Get the two live-in registers as SDValues. The physregs have already been
3144 // copied into virtual registers.
3145 SDValue Ops[2];
3146 if (FuncInfo.ExceptionPointerVirtReg) {
3147 Ops[0] = DAG.getZExtOrTrunc(
3148 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3149 FuncInfo.ExceptionPointerVirtReg,
3150 TLI.getPointerTy(DAG.getDataLayout())),
3151 dl, ValueVTs[0]);
3152 } else {
3153 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3154 }
3155 Ops[1] = DAG.getZExtOrTrunc(
3156 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3157 FuncInfo.ExceptionSelectorVirtReg,
3158 TLI.getPointerTy(DAG.getDataLayout())),
3159 dl, ValueVTs[1]);
3160
3161 // Merge into one.
3162 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3163 DAG.getVTList(ValueVTs), Ops);
3164 setValue(&LP, Res);
3165}
3166
3167void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3168 MachineBasicBlock *Last) {
3169 // Update JTCases.
3170 for (JumpTableBlock &JTB : SL->JTCases)
3171 if (JTB.first.HeaderBB == First)
3172 JTB.first.HeaderBB = Last;
3173
3174 // Update BitTestCases.
3175 for (BitTestBlock &BTB : SL->BitTestCases)
3176 if (BTB.Parent == First)
3177 BTB.Parent = Last;
3178}
3179
3180void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3181 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3182
3183 // Update machine-CFG edges with unique successors.
3184 SmallSet<BasicBlock*, 32> Done;
3185 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3186 BasicBlock *BB = I.getSuccessor(i);
3187 bool Inserted = Done.insert(BB).second;
3188 if (!Inserted)
3189 continue;
3190
3191 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3192 addSuccessorWithProb(IndirectBrMBB, Succ);
3193 }
3194 IndirectBrMBB->normalizeSuccProbs();
3195
3196 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3197 MVT::Other, getControlRoot(),
3198 getValue(I.getAddress())));
3199}
3200
3201void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3202 if (!DAG.getTarget().Options.TrapUnreachable)
3203 return;
3204
3205 // We may be able to ignore unreachable behind a noreturn call.
3206 if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3207 const BasicBlock &BB = *I.getParent();
3208 if (&I != &BB.front()) {
3209 BasicBlock::const_iterator PredI =
3210 std::prev(BasicBlock::const_iterator(&I));
3211 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3212 if (Call->doesNotReturn())
3213 return;
3214 }
3215 }
3216 }
3217
3218 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3219}
3220
3221void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3222 SDNodeFlags Flags;
3223 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3224 Flags.copyFMF(*FPOp);
3225
3226 SDValue Op = getValue(I.getOperand(0));
3227 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3228 Op, Flags);
3229 setValue(&I, UnNodeValue);
3230}
3231
3232void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3233 SDNodeFlags Flags;
3234 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3235 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3236 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3237 }
3238 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3239 Flags.setExact(ExactOp->isExact());
3240 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3241 Flags.copyFMF(*FPOp);
3242
3243 SDValue Op1 = getValue(I.getOperand(0));
3244 SDValue Op2 = getValue(I.getOperand(1));
3245 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3246 Op1, Op2, Flags);
3247 setValue(&I, BinNodeValue);
3248}
3249
3250void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3251 SDValue Op1 = getValue(I.getOperand(0));
3252 SDValue Op2 = getValue(I.getOperand(1));
3253
3254 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3255 Op1.getValueType(), DAG.getDataLayout());
3256
3257 // Coerce the shift amount to the right type if we can. This exposes the
3258 // truncate or zext to optimization early.
3259 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3260 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&(static_cast <bool> (ShiftTy.getSizeInBits() >= Log2_32_Ceil
(Op1.getValueSizeInBits()) && "Unexpected shift type"
) ? void (0) : __assert_fail ("ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && \"Unexpected shift type\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3261
, __extension__ __PRETTY_FUNCTION__))
3261 "Unexpected shift type")(static_cast <bool> (ShiftTy.getSizeInBits() >= Log2_32_Ceil
(Op1.getValueSizeInBits()) && "Unexpected shift type"
) ? void (0) : __assert_fail ("ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) && \"Unexpected shift type\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3261
, __extension__ __PRETTY_FUNCTION__))
;
3262 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3263 }
3264
3265 bool nuw = false;
3266 bool nsw = false;
3267 bool exact = false;
3268
3269 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3270
3271 if (const OverflowingBinaryOperator *OFBinOp =
3272 dyn_cast<const OverflowingBinaryOperator>(&I)) {
3273 nuw = OFBinOp->hasNoUnsignedWrap();
3274 nsw = OFBinOp->hasNoSignedWrap();
3275 }
3276 if (const PossiblyExactOperator *ExactOp =
3277 dyn_cast<const PossiblyExactOperator>(&I))
3278 exact = ExactOp->isExact();
3279 }
3280 SDNodeFlags Flags;
3281 Flags.setExact(exact);
3282 Flags.setNoSignedWrap(nsw);
3283 Flags.setNoUnsignedWrap(nuw);
3284 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3285 Flags);
3286 setValue(&I, Res);
3287}
3288
3289void SelectionDAGBuilder::visitSDiv(const User &I) {
3290 SDValue Op1 = getValue(I.getOperand(0));
3291 SDValue Op2 = getValue(I.getOperand(1));
3292
3293 SDNodeFlags Flags;
3294 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3295 cast<PossiblyExactOperator>(&I)->isExact());
3296 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3297 Op2, Flags));
3298}
3299
3300void SelectionDAGBuilder::visitICmp(const User &I) {
3301 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3302 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3303 predicate = IC->getPredicate();
3304 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3305 predicate = ICmpInst::Predicate(IC->getPredicate());
3306 SDValue Op1 = getValue(I.getOperand(0));
3307 SDValue Op2 = getValue(I.getOperand(1));
3308 ISD::CondCode Opcode = getICmpCondCode(predicate);
3309
3310 auto &TLI = DAG.getTargetLoweringInfo();
3311 EVT MemVT =
3312 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3313
3314 // If a pointer's DAG type is larger than its memory type then the DAG values
3315 // are zero-extended. This breaks signed comparisons so truncate back to the
3316 // underlying type before doing the compare.
3317 if (Op1.getValueType() != MemVT) {
3318 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3319 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3320 }
3321
3322 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3323 I.getType());
3324 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3325}
3326
3327void SelectionDAGBuilder::visitFCmp(const User &I) {
3328 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3329 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3330 predicate = FC->getPredicate();
3331 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3332 predicate = FCmpInst::Predicate(FC->getPredicate());
3333 SDValue Op1 = getValue(I.getOperand(0));
3334 SDValue Op2 = getValue(I.getOperand(1));
3335
3336 ISD::CondCode Condition = getFCmpCondCode(predicate);
3337 auto *FPMO = cast<FPMathOperator>(&I);
3338 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3339 Condition = getFCmpCodeWithoutNaN(Condition);
3340
3341 SDNodeFlags Flags;
3342 Flags.copyFMF(*FPMO);
3343 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3344
3345 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3346 I.getType());
3347 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3348}
3349
3350// Check if the condition of the select has one use or two users that are both
3351// selects with the same condition.
3352static bool hasOnlySelectUsers(const Value *Cond) {
3353 return llvm::all_of(Cond->users(), [](const Value *V) {
3354 return isa<SelectInst>(V);
3355 });
3356}
3357
3358void SelectionDAGBuilder::visitSelect(const User &I) {
3359 SmallVector<EVT, 4> ValueVTs;
3360 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3361 ValueVTs);
3362 unsigned NumValues = ValueVTs.size();
3363 if (NumValues == 0) return;
3364
3365 SmallVector<SDValue, 4> Values(NumValues);
3366 SDValue Cond = getValue(I.getOperand(0));
3367 SDValue LHSVal = getValue(I.getOperand(1));
3368 SDValue RHSVal = getValue(I.getOperand(2));
3369 SmallVector<SDValue, 1> BaseOps(1, Cond);
3370 ISD::NodeType OpCode =
3371 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3372
3373 bool IsUnaryAbs = false;
3374 bool Negate = false;
3375
3376 SDNodeFlags Flags;
3377 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3378 Flags.copyFMF(*FPOp);
3379
3380 // Min/max matching is only viable if all output VTs are the same.
3381 if (all_equal(ValueVTs)) {
3382 EVT VT = ValueVTs[0];
3383 LLVMContext &Ctx = *DAG.getContext();
3384 auto &TLI = DAG.getTargetLoweringInfo();
3385
3386 // We care about the legality of the operation after it has been type
3387 // legalized.
3388 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3389 VT = TLI.getTypeToTransformTo(Ctx, VT);
3390
3391 // If the vselect is legal, assume we want to leave this as a vector setcc +
3392 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3393 // min/max is legal on the scalar type.
3394 bool UseScalarMinMax = VT.isVector() &&
3395 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3396
3397 // ValueTracking's select pattern matching does not account for -0.0,
3398 // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3399 // -0.0 is less than +0.0.
3400 Value *LHS, *RHS;
3401 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3402 ISD::NodeType Opc = ISD::DELETED_NODE;
3403 switch (SPR.Flavor) {
3404 case SPF_UMAX: Opc = ISD::UMAX; break;
3405 case SPF_UMIN: Opc = ISD::UMIN; break;
3406 case SPF_SMAX: Opc = ISD::SMAX; break;
3407 case SPF_SMIN: Opc = ISD::SMIN; break;
3408 case SPF_FMINNUM:
3409 switch (SPR.NaNBehavior) {
3410 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?")::llvm::llvm_unreachable_internal("No NaN behavior for FP op?"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3410
)
;
3411 case SPNB_RETURNS_NAN: break;
3412 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3413 case SPNB_RETURNS_ANY:
3414 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3415 (UseScalarMinMax &&
3416 TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3417 Opc = ISD::FMINNUM;
3418 break;
3419 }
3420 break;
3421 case SPF_FMAXNUM:
3422 switch (SPR.NaNBehavior) {
3423 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?")::llvm::llvm_unreachable_internal("No NaN behavior for FP op?"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3423
)
;
3424 case SPNB_RETURNS_NAN: break;
3425 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3426 case SPNB_RETURNS_ANY:
3427 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3428 (UseScalarMinMax &&
3429 TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3430 Opc = ISD::FMAXNUM;
3431 break;
3432 }
3433 break;
3434 case SPF_NABS:
3435 Negate = true;
3436 [[fallthrough]];
3437 case SPF_ABS:
3438 IsUnaryAbs = true;
3439 Opc = ISD::ABS;
3440 break;
3441 default: break;
3442 }
3443
3444 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3445 (TLI.isOperationLegalOrCustom(Opc, VT) ||
3446 (UseScalarMinMax &&
3447 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3448 // If the underlying comparison instruction is used by any other
3449 // instruction, the consumed instructions won't be destroyed, so it is
3450 // not profitable to convert to a min/max.
3451 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3452 OpCode = Opc;
3453 LHSVal = getValue(LHS);
3454 RHSVal = getValue(RHS);
3455 BaseOps.clear();
3456 }
3457
3458 if (IsUnaryAbs) {
3459 OpCode = Opc;
3460 LHSVal = getValue(LHS);
3461 BaseOps.clear();
3462 }
3463 }
3464
3465 if (IsUnaryAbs) {
3466 for (unsigned i = 0; i != NumValues; ++i) {
3467 SDLoc dl = getCurSDLoc();
3468 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3469 Values[i] =
3470 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3471 if (Negate)
3472 Values[i] = DAG.getNegative(Values[i], dl, VT);
3473 }
3474 } else {
3475 for (unsigned i = 0; i != NumValues; ++i) {
3476 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3477 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3478 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3479 Values[i] = DAG.getNode(
3480 OpCode, getCurSDLoc(),
3481 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3482 }
3483 }
3484
3485 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3486 DAG.getVTList(ValueVTs), Values));
3487}
3488
3489void SelectionDAGBuilder::visitTrunc(const User &I) {
3490 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3491 SDValue N = getValue(I.getOperand(0));
3492 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3493 I.getType());
3494 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3495}
3496
3497void SelectionDAGBuilder::visitZExt(const User &I) {
3498 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3499 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3500 SDValue N = getValue(I.getOperand(0));
3501 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3502 I.getType());
3503 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3504}
3505
3506void SelectionDAGBuilder::visitSExt(const User &I) {
3507 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3508 // SExt also can't be a cast to bool for same reason. So, nothing much to do
3509 SDValue N = getValue(I.getOperand(0));
3510 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3511 I.getType());
3512 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3513}
3514
3515void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3516 // FPTrunc is never a no-op cast, no need to check
3517 SDValue N = getValue(I.getOperand(0));
3518 SDLoc dl = getCurSDLoc();
3519 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3520 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3521 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3522 DAG.getTargetConstant(
3523 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3524}
3525
3526void SelectionDAGBuilder::visitFPExt(const User &I) {
3527 // FPExt is never a no-op cast, no need to check
3528 SDValue N = getValue(I.getOperand(0));
3529 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3530 I.getType());
3531 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3532}
3533
3534void SelectionDAGBuilder::visitFPToUI(const User &I) {
3535 // FPToUI is never a no-op cast, no need to check
3536 SDValue N = getValue(I.getOperand(0));
3537 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3538 I.getType());
3539 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3540}
3541
3542void SelectionDAGBuilder::visitFPToSI(const User &I) {
3543 // FPToSI is never a no-op cast, no need to check
3544 SDValue N = getValue(I.getOperand(0));
3545 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3546 I.getType());
3547 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3548}
3549
3550void SelectionDAGBuilder::visitUIToFP(const User &I) {
3551 // UIToFP is never a no-op cast, no need to check
3552 SDValue N = getValue(I.getOperand(0));
3553 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3554 I.getType());
3555 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3556}
3557
3558void SelectionDAGBuilder::visitSIToFP(const User &I) {
3559 // SIToFP is never a no-op cast, no need to check
3560 SDValue N = getValue(I.getOperand(0));
3561 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3562 I.getType());
3563 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3564}
3565
3566void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3567 // What to do depends on the size of the integer and the size of the pointer.
3568 // We can either truncate, zero extend, or no-op, accordingly.
3569 SDValue N = getValue(I.getOperand(0));
3570 auto &TLI = DAG.getTargetLoweringInfo();
3571 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3572 I.getType());
3573 EVT PtrMemVT =
3574 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3575 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3576 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3577 setValue(&I, N);
3578}
3579
3580void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3581 // What to do depends on the size of the integer and the size of the pointer.
3582 // We can either truncate, zero extend, or no-op, accordingly.
3583 SDValue N = getValue(I.getOperand(0));
3584 auto &TLI = DAG.getTargetLoweringInfo();
3585 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3586 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3587 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3588 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3589 setValue(&I, N);
3590}
3591
3592void SelectionDAGBuilder::visitBitCast(const User &I) {
3593 SDValue N = getValue(I.getOperand(0));
3594 SDLoc dl = getCurSDLoc();
3595 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3596 I.getType());
3597
3598 // BitCast assures us that source and destination are the same size so this is
3599 // either a BITCAST or a no-op.
3600 if (DestVT != N.getValueType())
3601 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3602 DestVT, N)); // convert types.
3603 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3604 // might fold any kind of constant expression to an integer constant and that
3605 // is not what we are looking for. Only recognize a bitcast of a genuine
3606 // constant integer as an opaque constant.
3607 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3608 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3609 /*isOpaque*/true));
3610 else
3611 setValue(&I, N); // noop cast.
3612}
3613
3614void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3615 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3616 const Value *SV = I.getOperand(0);
3617 SDValue N = getValue(SV);
3618 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3619
3620 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3621 unsigned DestAS = I.getType()->getPointerAddressSpace();
3622
3623 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3624 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3625
3626 setValue(&I, N);
3627}
3628
3629void SelectionDAGBuilder::visitInsertElement(const User &I) {
3630 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3631 SDValue InVec = getValue(I.getOperand(0));
3632 SDValue InVal = getValue(I.getOperand(1));
3633 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3634 TLI.getVectorIdxTy(DAG.getDataLayout()));
3635 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3636 TLI.getValueType(DAG.getDataLayout(), I.getType()),
3637 InVec, InVal, InIdx));
3638}
3639
3640void SelectionDAGBuilder::visitExtractElement(const User &I) {
3641 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3642 SDValue InVec = getValue(I.getOperand(0));
3643 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3644 TLI.getVectorIdxTy(DAG.getDataLayout()));
3645 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3646 TLI.getValueType(DAG.getDataLayout(), I.getType()),
3647 InVec, InIdx));
3648}
3649
3650void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3651 SDValue Src1 = getValue(I.getOperand(0));
3652 SDValue Src2 = getValue(I.getOperand(1));
3653 ArrayRef<int> Mask;
3654 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3655 Mask = SVI->getShuffleMask();
3656 else
3657 Mask = cast<ConstantExpr>(I).getShuffleMask();
3658 SDLoc DL = getCurSDLoc();
3659 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3660 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3661 EVT SrcVT = Src1.getValueType();
3662
3663 if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3664 VT.isScalableVector()) {
3665 // Canonical splat form of first element of first input vector.
3666 SDValue FirstElt =
3667 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3668 DAG.getVectorIdxConstant(0, DL));
3669 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3670 return;
3671 }
3672
3673 // For now, we only handle splats for scalable vectors.
3674 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3675 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3676 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle")(static_cast <bool> (!VT.isScalableVector() && "Unsupported scalable vector shuffle"
) ? void (0) : __assert_fail ("!VT.isScalableVector() && \"Unsupported scalable vector shuffle\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 3676
, __extension__ __PRETTY_FUNCTION__))
;
3677
3678 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3679 unsigned MaskNumElts = Mask.size();
3680
3681 if (SrcNumElts == MaskNumElts) {
3682 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3683 return;
3684 }
3685
3686 // Normalize the shuffle vector since mask and vector length don't match.
3687 if (SrcNumElts < MaskNumElts) {
3688 // Mask is longer than the source vectors. We can use concatenate vector to
3689 // make the mask and vectors lengths match.
3690
3691 if (MaskNumElts % SrcNumElts == 0) {
3692 // Mask length is a multiple of the source vector length.
3693 // Check if the shuffle is some kind of concatenation of the input
3694 // vectors.
3695 unsigned NumConcat = MaskNumElts / SrcNumElts;
3696 bool IsConcat = true;
3697 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3698 for (unsigned i = 0; i != MaskNumElts; ++i) {
3699 int Idx = Mask[i];
3700 if (Idx < 0)
3701 continue;
3702 // Ensure the indices in each SrcVT sized piece are sequential and that
3703 // the same source is used for the whole piece.
3704 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3705 (ConcatSrcs[i / SrcNumElts] >= 0 &&
3706 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3707 IsConcat = false;
3708 break;
3709 }
3710 // Remember which source this index came from.
3711 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3712 }
3713
3714 // The shuffle is concatenating multiple vectors together. Just emit
3715 // a CONCAT_VECTORS operation.
3716 if (IsConcat) {
3717 SmallVector<SDValue, 8> ConcatOps;
3718 for (auto Src : ConcatSrcs) {
3719 if (Src < 0)
3720 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3721 else if (Src == 0)
3722 ConcatOps.push_back(Src1);
3723 else
3724 ConcatOps.push_back(Src2);
3725 }
3726 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3727 return;
3728 }
3729 }
3730
3731 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3732 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3733 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3734 PaddedMaskNumElts);
3735
3736 // Pad both vectors with undefs to make them the same length as the mask.
3737 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3738
3739 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3740 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3741 MOps1[0] = Src1;
3742 MOps2[0] = Src2;
3743
3744 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3745 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3746
3747 // Readjust mask for new input vector length.
3748 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3749 for (unsigned i = 0; i != MaskNumElts; ++i) {
3750 int Idx = Mask[i];
3751 if (Idx >= (int)SrcNumElts)
3752 Idx -= SrcNumElts - PaddedMaskNumElts;
3753 MappedOps[i] = Idx;
3754 }
3755
3756 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3757
3758 // If the concatenated vector was padded, extract a subvector with the
3759 // correct number of elements.
3760 if (MaskNumElts != PaddedMaskNumElts)
3761 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3762 DAG.getVectorIdxConstant(0, DL));
3763
3764 setValue(&I, Result);
3765 return;
3766 }
3767
3768 if (SrcNumElts > MaskNumElts) {
3769 // Analyze the access pattern of the vector to see if we can extract
3770 // two subvectors and do the shuffle.
3771 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
3772 bool CanExtract = true;
3773 for (int Idx : Mask) {
3774 unsigned Input = 0;
3775 if (Idx < 0)
3776 continue;
3777
3778 if (Idx >= (int)SrcNumElts) {
3779 Input = 1;
3780 Idx -= SrcNumElts;
3781 }
3782
3783 // If all the indices come from the same MaskNumElts sized portion of
3784 // the sources we can use extract. Also make sure the extract wouldn't
3785 // extract past the end of the source.
3786 int NewStartIdx = alignDown(Idx, MaskNumElts);
3787 if (NewStartIdx + MaskNumElts > SrcNumElts ||
3788 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3789 CanExtract = false;
3790 // Make sure we always update StartIdx as we use it to track if all
3791 // elements are undef.
3792 StartIdx[Input] = NewStartIdx;
3793 }
3794
3795 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3796 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3797 return;
3798 }
3799 if (CanExtract) {
3800 // Extract appropriate subvector and generate a vector shuffle
3801 for (unsigned Input = 0; Input < 2; ++Input) {
3802 SDValue &Src = Input == 0 ? Src1 : Src2;
3803 if (StartIdx[Input] < 0)
3804 Src = DAG.getUNDEF(VT);
3805 else {
3806 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3807 DAG.getVectorIdxConstant(StartIdx[Input], DL));
3808 }
3809 }
3810
3811 // Calculate new mask.
3812 SmallVector<int, 8> MappedOps(Mask);
3813 for (int &Idx : MappedOps) {
3814 if (Idx >= (int)SrcNumElts)
3815 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3816 else if (Idx >= 0)
3817 Idx -= StartIdx[0];
3818 }
3819
3820 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3821 return;
3822 }
3823 }
3824
3825 // We can't use either concat vectors or extract subvectors so fall back to
3826 // replacing the shuffle with extract and build vector.
3827 // to insert and build vector.
3828 EVT EltVT = VT.getVectorElementType();
3829 SmallVector<SDValue,8> Ops;
3830 for (int Idx : Mask) {
3831 SDValue Res;
3832
3833 if (Idx < 0) {
3834 Res = DAG.getUNDEF(EltVT);
3835 } else {
3836 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3837 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3838
3839 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3840 DAG.getVectorIdxConstant(Idx, DL));
3841 }
3842
3843 Ops.push_back(Res);
3844 }
3845
3846 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3847}
3848
3849void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3850 ArrayRef<unsigned> Indices = I.getIndices();
3851 const Value *Op0 = I.getOperand(0);
3852 const Value *Op1 = I.getOperand(1);
3853 Type *AggTy = I.getType();
3854 Type *ValTy = Op1->getType();
3855 bool IntoUndef = isa<UndefValue>(Op0);
3856 bool FromUndef = isa<UndefValue>(Op1);
3857
3858 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3859
3860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3861 SmallVector<EVT, 4> AggValueVTs;
3862 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3863 SmallVector<EVT, 4> ValValueVTs;
3864 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3865
3866 unsigned NumAggValues = AggValueVTs.size();
3867 unsigned NumValValues = ValValueVTs.size();
3868 SmallVector<SDValue, 4> Values(NumAggValues);
3869
3870 // Ignore an insertvalue that produces an empty object
3871 if (!NumAggValues) {
3872 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3873 return;
3874 }
3875
3876 SDValue Agg = getValue(Op0);
3877 unsigned i = 0;
3878 // Copy the beginning value(s) from the original aggregate.
3879 for (; i != LinearIndex; ++i)
3880 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3881 SDValue(Agg.getNode(), Agg.getResNo() + i);
3882 // Copy values from the inserted value(s).
3883 if (NumValValues) {
3884 SDValue Val = getValue(Op1);
3885 for (; i != LinearIndex + NumValValues; ++i)
3886 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3887 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3888 }
3889 // Copy remaining value(s) from the original aggregate.
3890 for (; i != NumAggValues; ++i)
3891 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3892 SDValue(Agg.getNode(), Agg.getResNo() + i);
3893
3894 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3895 DAG.getVTList(AggValueVTs), Values));
3896}
3897
3898void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3899 ArrayRef<unsigned> Indices = I.getIndices();
3900 const Value *Op0 = I.getOperand(0);
3901 Type *AggTy = Op0->getType();
3902 Type *ValTy = I.getType();
3903 bool OutOfUndef = isa<UndefValue>(Op0);
3904
3905 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3906
3907 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3908 SmallVector<EVT, 4> ValValueVTs;
3909 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3910
3911 unsigned NumValValues = ValValueVTs.size();
3912
3913 // Ignore a extractvalue that produces an empty object
3914 if (!NumValValues) {
3915 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3916 return;
3917 }
3918
3919 SmallVector<SDValue, 4> Values(NumValValues);
3920
3921 SDValue Agg = getValue(Op0);
3922 // Copy out the selected value(s).
3923 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3924 Values[i - LinearIndex] =
3925 OutOfUndef ?
3926 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3927 SDValue(Agg.getNode(), Agg.getResNo() + i);
3928
3929 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3930 DAG.getVTList(ValValueVTs), Values));
3931}
3932
3933void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3934 Value *Op0 = I.getOperand(0);
3935 // Note that the pointer operand may be a vector of pointers. Take the scalar
3936 // element which holds a pointer.
3937 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3938 SDValue N = getValue(Op0);
3939 SDLoc dl = getCurSDLoc();
3940 auto &TLI = DAG.getTargetLoweringInfo();
3941
3942 // Normalize Vector GEP - all scalar operands should be converted to the
3943 // splat vector.
3944 bool IsVectorGEP = I.getType()->isVectorTy();
3945 ElementCount VectorElementCount =
3946 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3947 : ElementCount::getFixed(0);
3948
3949 if (IsVectorGEP && !N.getValueType().isVector()) {
3950 LLVMContext &Context = *DAG.getContext();
3951 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3952 N = DAG.getSplat(VT, dl, N);
3953 }
3954
3955 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3956 GTI != E; ++GTI) {
3957 const Value *Idx = GTI.getOperand();
3958 if (StructType *StTy = GTI.getStructTypeOrNull()) {
3959 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3960 if (Field) {
3961 // N = N + Offset
3962 uint64_t Offset =
3963 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3964
3965 // In an inbounds GEP with an offset that is nonnegative even when
3966 // interpreted as signed, assume there is no unsigned overflow.
3967 SDNodeFlags Flags;
3968 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3969 Flags.setNoUnsignedWrap(true);
3970
3971 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3972 DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3973 }
3974 } else {
3975 // IdxSize is the width of the arithmetic according to IR semantics.
3976 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3977 // (and fix up the result later).
3978 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3979 MVT IdxTy = MVT::getIntegerVT(IdxSize);
3980 TypeSize ElementSize =
3981 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3982 // We intentionally mask away the high bits here; ElementSize may not
3983 // fit in IdxTy.
3984 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
3985 bool ElementScalable = ElementSize.isScalable();
3986
3987 // If this is a scalar constant or a splat vector of constants,
3988 // handle it quickly.
3989 const auto *C = dyn_cast<Constant>(Idx);
3990 if (C && isa<VectorType>(C->getType()))
3991 C = C->getSplatValue();
3992
3993 const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3994 if (CI && CI->isZero())
3995 continue;
3996 if (CI && !ElementScalable) {
3997 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3998 LLVMContext &Context = *DAG.getContext();
3999 SDValue OffsVal;
4000 if (IsVectorGEP)
4001 OffsVal = DAG.getConstant(
4002 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4003 else
4004 OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4005
4006 // In an inbounds GEP with an offset that is nonnegative even when
4007 // interpreted as signed, assume there is no unsigned overflow.
4008 SDNodeFlags Flags;
4009 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4010 Flags.setNoUnsignedWrap(true);
4011
4012 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4013
4014 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4015 continue;
4016 }
4017
4018 // N = N + Idx * ElementMul;
4019 SDValue IdxN = getValue(Idx);
4020
4021 if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4022 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4023 VectorElementCount);
4024 IdxN = DAG.getSplat(VT, dl, IdxN);
4025 }
4026
4027 // If the index is smaller or larger than intptr_t, truncate or extend
4028 // it.
4029 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4030
4031 if (ElementScalable) {
4032 EVT VScaleTy = N.getValueType().getScalarType();
4033 SDValue VScale = DAG.getNode(
4034 ISD::VSCALE, dl, VScaleTy,
4035 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4036 if (IsVectorGEP)
4037 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4038 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4039 } else {
4040 // If this is a multiply by a power of two, turn it into a shl
4041 // immediately. This is a very common case.
4042 if (ElementMul != 1) {
4043 if (ElementMul.isPowerOf2()) {
4044 unsigned Amt = ElementMul.logBase2();
4045 IdxN = DAG.getNode(ISD::SHL, dl,
4046 N.getValueType(), IdxN,
4047 DAG.getConstant(Amt, dl, IdxN.getValueType()));
4048 } else {
4049 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4050 IdxN.getValueType());
4051 IdxN = DAG.getNode(ISD::MUL, dl,
4052 N.getValueType(), IdxN, Scale);
4053 }
4054 }
4055 }
4056
4057 N = DAG.getNode(ISD::ADD, dl,
4058 N.getValueType(), N, IdxN);
4059 }
4060 }
4061
4062 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4063 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4064 if (IsVectorGEP) {
4065 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4066 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4067 }
4068
4069 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4070 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4071
4072 setValue(&I, N);
4073}
4074
4075void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4076 // If this is a fixed sized alloca in the entry block of the function,
4077 // allocate it statically on the stack.
4078 if (FuncInfo.StaticAllocaMap.count(&I))
4079 return; // getValue will auto-populate this.
4080
4081 SDLoc dl = getCurSDLoc();
4082 Type *Ty = I.getAllocatedType();
4083 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4084 auto &DL = DAG.getDataLayout();
4085 TypeSize TySize = DL.getTypeAllocSize(Ty);
4086 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4087
4088 SDValue AllocSize = getValue(I.getArraySize());
4089
4090 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace());
4091 if (AllocSize.getValueType() != IntPtr)
4092 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4093
4094 if (TySize.isScalable())
4095 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4096 DAG.getVScale(dl, IntPtr,
4097 APInt(IntPtr.getScalarSizeInBits(),
4098 TySize.getKnownMinValue())));
4099 else
4100 AllocSize =
4101 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4102 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4103
4104 // Handle alignment. If the requested alignment is less than or equal to
4105 // the stack alignment, ignore it. If the size is greater than or equal to
4106 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4107 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4108 if (*Alignment <= StackAlign)
4109 Alignment = std::nullopt;
4110
4111 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4112 // Round the size of the allocation up to the stack alignment size
4113 // by add SA-1 to the size. This doesn't overflow because we're computing
4114 // an address inside an alloca.
4115 SDNodeFlags Flags;
4116 Flags.setNoUnsignedWrap(true);
4117 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4118 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4119
4120 // Mask out the low bits for alignment purposes.
4121 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4122 DAG.getConstant(~StackAlignMask, dl, IntPtr));
4123
4124 SDValue Ops[] = {
4125 getRoot(), AllocSize,
4126 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4127 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4128 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4129 setValue(&I, DSA);
4130 DAG.setRoot(DSA.getValue(1));
4131
4132 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects())(static_cast <bool> (FuncInfo.MF->getFrameInfo().hasVarSizedObjects
()) ? void (0) : __assert_fail ("FuncInfo.MF->getFrameInfo().hasVarSizedObjects()"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4132
, __extension__ __PRETTY_FUNCTION__))
;
4133}
4134
4135void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4136 if (I.isAtomic())
4137 return visitAtomicLoad(I);
4138
4139 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4140 const Value *SV = I.getOperand(0);
4141 if (TLI.supportSwiftError()) {
4142 // Swifterror values can come from either a function parameter with
4143 // swifterror attribute or an alloca with swifterror attribute.
4144 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4145 if (Arg->hasSwiftErrorAttr())
4146 return visitLoadFromSwiftError(I);
4147 }
4148
4149 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4150 if (Alloca->isSwiftError())
4151 return visitLoadFromSwiftError(I);
4152 }
4153 }
4154
4155 SDValue Ptr = getValue(SV);
4156
4157 Type *Ty = I.getType();
4158 SmallVector<EVT, 4> ValueVTs, MemVTs;
4159 SmallVector<uint64_t, 4> Offsets;
4160 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4161 unsigned NumValues = ValueVTs.size();
4162 if (NumValues == 0)
4163 return;
4164
4165 Align Alignment = I.getAlign();
4166 AAMDNodes AAInfo = I.getAAMetadata();
4167 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4168 bool isVolatile = I.isVolatile();
4169 MachineMemOperand::Flags MMOFlags =
4170 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4171
4172 SDValue Root;
4173 bool ConstantMemory = false;
4174 if (isVolatile)
4175 // Serialize volatile loads with other side effects.
4176 Root = getRoot();
4177 else if (NumValues > MaxParallelChains)
4178 Root = getMemoryRoot();
4179 else if (AA &&
4180 AA->pointsToConstantMemory(MemoryLocation(
4181 SV,
4182 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4183 AAInfo))) {
4184 // Do not serialize (non-volatile) loads of constant memory with anything.
4185 Root = DAG.getEntryNode();
4186 ConstantMemory = true;
4187 MMOFlags |= MachineMemOperand::MOInvariant;
4188 } else {
4189 // Do not serialize non-volatile loads against each other.
4190 Root = DAG.getRoot();
4191 }
4192
4193 SDLoc dl = getCurSDLoc();
4194
4195 if (isVolatile)
4196 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4197
4198 // An aggregate load cannot wrap around the address space, so offsets to its
4199 // parts don't wrap either.
4200 SDNodeFlags Flags;
4201 Flags.setNoUnsignedWrap(true);
4202
4203 SmallVector<SDValue, 4> Values(NumValues);
4204 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4205 EVT PtrVT = Ptr.getValueType();
4206
4207 unsigned ChainI = 0;
4208 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4209 // Serializing loads here may result in excessive register pressure, and
4210 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4211 // could recover a bit by hoisting nodes upward in the chain by recognizing
4212 // they are side-effect free or do not alias. The optimizer should really
4213 // avoid this case by converting large object/array copies to llvm.memcpy
4214 // (MaxParallelChains should always remain as failsafe).
4215 if (ChainI == MaxParallelChains) {
4216 assert(PendingLoads.empty() && "PendingLoads must be serialized first")(static_cast <bool> (PendingLoads.empty() && "PendingLoads must be serialized first"
) ? void (0) : __assert_fail ("PendingLoads.empty() && \"PendingLoads must be serialized first\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4216
, __extension__ __PRETTY_FUNCTION__))
;
4217 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4218 ArrayRef(Chains.data(), ChainI));
4219 Root = Chain;
4220 ChainI = 0;
4221 }
4222 SDValue A = DAG.getNode(ISD::ADD, dl,
4223 PtrVT, Ptr,
4224 DAG.getConstant(Offsets[i], dl, PtrVT),
4225 Flags);
4226
4227 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4228 MachinePointerInfo(SV, Offsets[i]), Alignment,
4229 MMOFlags, AAInfo, Ranges);
4230 Chains[ChainI] = L.getValue(1);
4231
4232 if (MemVTs[i] != ValueVTs[i])
4233 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4234
4235 Values[i] = L;
4236 }
4237
4238 if (!ConstantMemory) {
4239 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4240 ArrayRef(Chains.data(), ChainI));
4241 if (isVolatile)
4242 DAG.setRoot(Chain);
4243 else
4244 PendingLoads.push_back(Chain);
4245 }
4246
4247 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4248 DAG.getVTList(ValueVTs), Values));
4249}
4250
4251void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4252 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&(static_cast <bool> (DAG.getTargetLoweringInfo().supportSwiftError
() && "call visitStoreToSwiftError when backend supports swifterror"
) ? void (0) : __assert_fail ("DAG.getTargetLoweringInfo().supportSwiftError() && \"call visitStoreToSwiftError when backend supports swifterror\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4253
, __extension__ __PRETTY_FUNCTION__))
4253 "call visitStoreToSwiftError when backend supports swifterror")(static_cast <bool> (DAG.getTargetLoweringInfo().supportSwiftError
() && "call visitStoreToSwiftError when backend supports swifterror"
) ? void (0) : __assert_fail ("DAG.getTargetLoweringInfo().supportSwiftError() && \"call visitStoreToSwiftError when backend supports swifterror\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4253
, __extension__ __PRETTY_FUNCTION__))
;
4254
4255 SmallVector<EVT, 4> ValueVTs;
4256 SmallVector<uint64_t, 4> Offsets;
4257 const Value *SrcV = I.getOperand(0);
4258 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4259 SrcV->getType(), ValueVTs, &Offsets);
4260 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&(static_cast <bool> (ValueVTs.size() == 1 && Offsets
[0] == 0 && "expect a single EVT for swifterror") ? void
(0) : __assert_fail ("ValueVTs.size() == 1 && Offsets[0] == 0 && \"expect a single EVT for swifterror\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4261
, __extension__ __PRETTY_FUNCTION__))
4261 "expect a single EVT for swifterror")(static_cast <bool> (ValueVTs.size() == 1 && Offsets
[0] == 0 && "expect a single EVT for swifterror") ? void
(0) : __assert_fail ("ValueVTs.size() == 1 && Offsets[0] == 0 && \"expect a single EVT for swifterror\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4261
, __extension__ __PRETTY_FUNCTION__))
;
4262
4263 SDValue Src = getValue(SrcV);
4264 // Create a virtual register, then update the virtual register.
4265 Register VReg =
4266 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4267 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4268 // Chain can be getRoot or getControlRoot.
4269 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4270 SDValue(Src.getNode(), Src.getResNo()));
4271 DAG.setRoot(CopyNode);
4272}
4273
4274void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4275 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&(static_cast <bool> (DAG.getTargetLoweringInfo().supportSwiftError
() && "call visitLoadFromSwiftError when backend supports swifterror"
) ? void (0) : __assert_fail ("DAG.getTargetLoweringInfo().supportSwiftError() && \"call visitLoadFromSwiftError when backend supports swifterror\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4276
, __extension__ __PRETTY_FUNCTION__))
4276 "call visitLoadFromSwiftError when backend supports swifterror")(static_cast <bool> (DAG.getTargetLoweringInfo().supportSwiftError
() && "call visitLoadFromSwiftError when backend supports swifterror"
) ? void (0) : __assert_fail ("DAG.getTargetLoweringInfo().supportSwiftError() && \"call visitLoadFromSwiftError when backend supports swifterror\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4276
, __extension__ __PRETTY_FUNCTION__))
;
4277
4278 assert(!I.isVolatile() &&(static_cast <bool> (!I.isVolatile() && !I.hasMetadata
(LLVMContext::MD_nontemporal) && !I.hasMetadata(LLVMContext
::MD_invariant_load) && "Support volatile, non temporal, invariant for load_from_swift_error"
) ? void (0) : __assert_fail ("!I.isVolatile() && !I.hasMetadata(LLVMContext::MD_nontemporal) && !I.hasMetadata(LLVMContext::MD_invariant_load) && \"Support volatile, non temporal, invariant for load_from_swift_error\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4281
, __extension__ __PRETTY_FUNCTION__))
4279 !I.hasMetadata(LLVMContext::MD_nontemporal) &&(static_cast <bool> (!I.isVolatile() && !I.hasMetadata
(LLVMContext::MD_nontemporal) && !I.hasMetadata(LLVMContext
::MD_invariant_load) && "Support volatile, non temporal, invariant for load_from_swift_error"
) ? void (0) : __assert_fail ("!I.isVolatile() && !I.hasMetadata(LLVMContext::MD_nontemporal) && !I.hasMetadata(LLVMContext::MD_invariant_load) && \"Support volatile, non temporal, invariant for load_from_swift_error\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4281
, __extension__ __PRETTY_FUNCTION__))
4280 !I.hasMetadata(LLVMContext::MD_invariant_load) &&(static_cast <bool> (!I.isVolatile() && !I.hasMetadata
(LLVMContext::MD_nontemporal) && !I.hasMetadata(LLVMContext
::MD_invariant_load) && "Support volatile, non temporal, invariant for load_from_swift_error"
) ? void (0) : __assert_fail ("!I.isVolatile() && !I.hasMetadata(LLVMContext::MD_nontemporal) && !I.hasMetadata(LLVMContext::MD_invariant_load) && \"Support volatile, non temporal, invariant for load_from_swift_error\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4281
, __extension__ __PRETTY_FUNCTION__))
4281 "Support volatile, non temporal, invariant for load_from_swift_error")(static_cast <bool> (!I.isVolatile() && !I.hasMetadata
(LLVMContext::MD_nontemporal) && !I.hasMetadata(LLVMContext
::MD_invariant_load) && "Support volatile, non temporal, invariant for load_from_swift_error"
) ? void (0) : __assert_fail ("!I.isVolatile() && !I.hasMetadata(LLVMContext::MD_nontemporal) && !I.hasMetadata(LLVMContext::MD_invariant_load) && \"Support volatile, non temporal, invariant for load_from_swift_error\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4281
, __extension__ __PRETTY_FUNCTION__))
;
4282
4283 const Value *SV = I.getOperand(0);
4284 Type *Ty = I.getType();
4285 assert((static_cast <bool> ((!AA || !AA->pointsToConstantMemory
(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout(
).getTypeStoreSize(Ty)), I.getAAMetadata()))) && "load_from_swift_error should not be constant memory"
) ? void (0) : __assert_fail ("(!AA || !AA->pointsToConstantMemory(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), I.getAAMetadata()))) && \"load_from_swift_error should not be constant memory\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4290
, __extension__ __PRETTY_FUNCTION__))
4286 (!AA ||(static_cast <bool> ((!AA || !AA->pointsToConstantMemory
(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout(
).getTypeStoreSize(Ty)), I.getAAMetadata()))) && "load_from_swift_error should not be constant memory"
) ? void (0) : __assert_fail ("(!AA || !AA->pointsToConstantMemory(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), I.getAAMetadata()))) && \"load_from_swift_error should not be constant memory\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4290
, __extension__ __PRETTY_FUNCTION__))
4287 !AA->pointsToConstantMemory(MemoryLocation((static_cast <bool> ((!AA || !AA->pointsToConstantMemory
(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout(
).getTypeStoreSize(Ty)), I.getAAMetadata()))) && "load_from_swift_error should not be constant memory"
) ? void (0) : __assert_fail ("(!AA || !AA->pointsToConstantMemory(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), I.getAAMetadata()))) && \"load_from_swift_error should not be constant memory\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4290
, __extension__ __PRETTY_FUNCTION__))
4288 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),(static_cast <bool> ((!AA || !AA->pointsToConstantMemory
(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout(
).getTypeStoreSize(Ty)), I.getAAMetadata()))) && "load_from_swift_error should not be constant memory"
) ? void (0) : __assert_fail ("(!AA || !AA->pointsToConstantMemory(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), I.getAAMetadata()))) && \"load_from_swift_error should not be constant memory\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4290
, __extension__ __PRETTY_FUNCTION__))
4289 I.getAAMetadata()))) &&(static_cast <bool> ((!AA || !AA->pointsToConstantMemory
(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout(
).getTypeStoreSize(Ty)), I.getAAMetadata()))) && "load_from_swift_error should not be constant memory"
) ? void (0) : __assert_fail ("(!AA || !AA->pointsToConstantMemory(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), I.getAAMetadata()))) && \"load_from_swift_error should not be constant memory\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4290
, __extension__ __PRETTY_FUNCTION__))
4290 "load_from_swift_error should not be constant memory")(static_cast <bool> ((!AA || !AA->pointsToConstantMemory
(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout(
).getTypeStoreSize(Ty)), I.getAAMetadata()))) && "load_from_swift_error should not be constant memory"
) ? void (0) : __assert_fail ("(!AA || !AA->pointsToConstantMemory(MemoryLocation( SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)), I.getAAMetadata()))) && \"load_from_swift_error should not be constant memory\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4290
, __extension__ __PRETTY_FUNCTION__))
;
4291
4292 SmallVector<EVT, 4> ValueVTs;
4293 SmallVector<uint64_t, 4> Offsets;
4294 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4295 ValueVTs, &Offsets);
4296 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&(static_cast <bool> (ValueVTs.size() == 1 && Offsets
[0] == 0 && "expect a single EVT for swifterror") ? void
(0) : __assert_fail ("ValueVTs.size() == 1 && Offsets[0] == 0 && \"expect a single EVT for swifterror\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4297
, __extension__ __PRETTY_FUNCTION__))
4297 "expect a single EVT for swifterror")(static_cast <bool> (ValueVTs.size() == 1 && Offsets
[0] == 0 && "expect a single EVT for swifterror") ? void
(0) : __assert_fail ("ValueVTs.size() == 1 && Offsets[0] == 0 && \"expect a single EVT for swifterror\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4297
, __extension__ __PRETTY_FUNCTION__))
;
4298
4299 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4300 SDValue L = DAG.getCopyFromReg(
4301 getRoot(), getCurSDLoc(),
4302 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4303
4304 setValue(&I, L);
4305}
4306
4307void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4308 if (I.isAtomic())
4309 return visitAtomicStore(I);
4310
4311 const Value *SrcV = I.getOperand(0);
4312 const Value *PtrV = I.getOperand(1);
4313
4314 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4315 if (TLI.supportSwiftError()) {
4316 // Swifterror values can come from either a function parameter with
4317 // swifterror attribute or an alloca with swifterror attribute.
4318 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4319 if (Arg->hasSwiftErrorAttr())
4320 return visitStoreToSwiftError(I);
4321 }
4322
4323 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4324 if (Alloca->isSwiftError())
4325 return visitStoreToSwiftError(I);
4326 }
4327 }
4328
4329 SmallVector<EVT, 4> ValueVTs, MemVTs;
4330 SmallVector<uint64_t, 4> Offsets;
4331 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4332 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4333 unsigned NumValues = ValueVTs.size();
4334 if (NumValues == 0)
4335 return;
4336
4337 // Get the lowered operands. Note that we do this after
4338 // checking if NumResults is zero, because with zero results
4339 // the operands won't have values in the map.
4340 SDValue Src = getValue(SrcV);
4341 SDValue Ptr = getValue(PtrV);
4342
4343 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4344 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4345 SDLoc dl = getCurSDLoc();
4346 Align Alignment = I.getAlign();
4347 AAMDNodes AAInfo = I.getAAMetadata();
4348
4349 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4350
4351 // An aggregate load cannot wrap around the address space, so offsets to its
4352 // parts don't wrap either.
4353 SDNodeFlags Flags;
4354 Flags.setNoUnsignedWrap(true);
4355
4356 unsigned ChainI = 0;
4357 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4358 // See visitLoad comments.
4359 if (ChainI == MaxParallelChains) {
4360 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4361 ArrayRef(Chains.data(), ChainI));
4362 Root = Chain;
4363 ChainI = 0;
4364 }
4365 SDValue Add =
4366 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4367 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4368 if (MemVTs[i] != ValueVTs[i])
4369 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4370 SDValue St =
4371 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4372 Alignment, MMOFlags, AAInfo);
4373 Chains[ChainI] = St;
4374 }
4375
4376 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4377 ArrayRef(Chains.data(), ChainI));
4378 setValue(&I, StoreNode);
4379 DAG.setRoot(StoreNode);
4380}
4381
4382void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4383 bool IsCompressing) {
4384 SDLoc sdl = getCurSDLoc();
4385
4386 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4387 MaybeAlign &Alignment) {
4388 // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4389 Src0 = I.getArgOperand(0);
4390 Ptr = I.getArgOperand(1);
4391 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4392 Mask = I.getArgOperand(3);
4393 };
4394 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4395 MaybeAlign &Alignment) {
4396 // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4397 Src0 = I.getArgOperand(0);
4398 Ptr = I.getArgOperand(1);
4399 Mask = I.getArgOperand(2);
4400 Alignment = std::nullopt;
4401 };
4402
4403 Value *PtrOperand, *MaskOperand, *Src0Operand;
4404 MaybeAlign Alignment;
4405 if (IsCompressing)
4406 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4407 else
4408 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4409
4410 SDValue Ptr = getValue(PtrOperand);
4411 SDValue Src0 = getValue(Src0Operand);
4412 SDValue Mask = getValue(MaskOperand);
4413 SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4414
4415 EVT VT = Src0.getValueType();
4416 if (!Alignment)
4417 Alignment = DAG.getEVTAlign(VT);
4418
4419 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4420 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4421 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4422 SDValue StoreNode =
4423 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4424 ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4425 DAG.setRoot(StoreNode);
4426 setValue(&I, StoreNode);
4427}
4428
4429// Get a uniform base for the Gather/Scatter intrinsic.
4430// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4431// We try to represent it as a base pointer + vector of indices.
4432// Usually, the vector of pointers comes from a 'getelementptr' instruction.
4433// The first operand of the GEP may be a single pointer or a vector of pointers
4434// Example:
4435// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4436// or
4437// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
4438// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4439//
4440// When the first GEP operand is a single pointer - it is the uniform base we
4441// are looking for. If first operand of the GEP is a splat vector - we
4442// extract the splat value and use it as a uniform base.
4443// In all other cases the function returns 'false'.
4444static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4445 ISD::MemIndexType &IndexType, SDValue &Scale,
4446 SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4447 uint64_t ElemSize) {
4448 SelectionDAG& DAG = SDB->DAG;
4449 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4450 const DataLayout &DL = DAG.getDataLayout();
4451
4452 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type")(static_cast <bool> (Ptr->getType()->isVectorTy()
&& "Unexpected pointer type") ? void (0) : __assert_fail
("Ptr->getType()->isVectorTy() && \"Unexpected pointer type\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4452
, __extension__ __PRETTY_FUNCTION__))
;
4453
4454 // Handle splat constant pointer.
4455 if (auto *C = dyn_cast<Constant>(Ptr)) {
4456 C = C->getSplatValue();
4457 if (!C)
4458 return false;
4459
4460 Base = SDB->getValue(C);
4461
4462 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4463 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4464 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4465 IndexType = ISD::SIGNED_SCALED;
4466 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4467 return true;
4468 }
4469
4470 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4471 if (!GEP || GEP->getParent() != CurBB)
4472 return false;
4473
4474 if (GEP->getNumOperands() != 2)
4475 return false;
4476
4477 const Value *BasePtr = GEP->getPointerOperand();
4478 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4479
4480 // Make sure the base is scalar and the index is a vector.
4481 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4482 return false;
4483
4484 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4485
4486 // Target may not support the required addressing mode.
4487 if (ScaleVal != 1 &&
4488 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4489 return false;
4490
4491 Base = SDB->getValue(BasePtr);
4492 Index = SDB->getValue(IndexVal);
4493 IndexType = ISD::SIGNED_SCALED;
4494
4495 Scale =
4496 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4497 return true;
4498}
4499
4500void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4501 SDLoc sdl = getCurSDLoc();
4502
4503 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4504 const Value *Ptr = I.getArgOperand(1);
4505 SDValue Src0 = getValue(I.getArgOperand(0));
4506 SDValue Mask = getValue(I.getArgOperand(3));
4507 EVT VT = Src0.getValueType();
4508 Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4509 ->getMaybeAlignValue()
4510 .value_or(DAG.getEVTAlign(VT.getScalarType()));
4511 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4512
4513 SDValue Base;
4514 SDValue Index;
4515 ISD::MemIndexType IndexType;
4516 SDValue Scale;
4517 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4518 I.getParent(), VT.getScalarStoreSize());
4519
4520 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4521 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4522 MachinePointerInfo(AS), MachineMemOperand::MOStore,
4523 // TODO: Make MachineMemOperands aware of scalable
4524 // vectors.
4525 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4526 if (!UniformBase) {
4527 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4528 Index = getValue(Ptr);
4529 IndexType = ISD::SIGNED_SCALED;
4530 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4531 }
4532
4533 EVT IdxVT = Index.getValueType();
4534 EVT EltTy = IdxVT.getVectorElementType();
4535 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4536 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4537 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4538 }
4539
4540 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4541 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4542 Ops, MMO, IndexType, false);
4543 DAG.setRoot(Scatter);
4544 setValue(&I, Scatter);
4545}
4546
4547void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4548 SDLoc sdl = getCurSDLoc();
4549
4550 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4551 MaybeAlign &Alignment) {
4552 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4553 Ptr = I.getArgOperand(0);
4554 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4555 Mask = I.getArgOperand(2);
4556 Src0 = I.getArgOperand(3);
4557 };
4558 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4559 MaybeAlign &Alignment) {
4560 // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4561 Ptr = I.getArgOperand(0);
4562 Alignment = std::nullopt;
4563 Mask = I.getArgOperand(1);
4564 Src0 = I.getArgOperand(2);
4565 };
4566
4567 Value *PtrOperand, *MaskOperand, *Src0Operand;
4568 MaybeAlign Alignment;
4569 if (IsExpanding)
4570 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4571 else
4572 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4573
4574 SDValue Ptr = getValue(PtrOperand);
4575 SDValue Src0 = getValue(Src0Operand);
4576 SDValue Mask = getValue(MaskOperand);
4577 SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4578
4579 EVT VT = Src0.getValueType();
4580 if (!Alignment)
4581 Alignment = DAG.getEVTAlign(VT);
4582
4583 AAMDNodes AAInfo = I.getAAMetadata();
4584 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4585
4586 // Do not serialize masked loads of constant memory with anything.
4587 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4588 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4589
4590 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4591
4592 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4593 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4594 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4595
4596 SDValue Load =
4597 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4598 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4599 if (AddToChain)
4600 PendingLoads.push_back(Load.getValue(1));
4601 setValue(&I, Load);
4602}
4603
4604void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4605 SDLoc sdl = getCurSDLoc();
4606
4607 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4608 const Value *Ptr = I.getArgOperand(0);
4609 SDValue Src0 = getValue(I.getArgOperand(3));
4610 SDValue Mask = getValue(I.getArgOperand(2));
4611
4612 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4613 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4614 Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4615 ->getMaybeAlignValue()
4616 .value_or(DAG.getEVTAlign(VT.getScalarType()));
4617
4618 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4619
4620 SDValue Root = DAG.getRoot();
4621 SDValue Base;
4622 SDValue Index;
4623 ISD::MemIndexType IndexType;
4624 SDValue Scale;
4625 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4626 I.getParent(), VT.getScalarStoreSize());
4627 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4628 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4629 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4630 // TODO: Make MachineMemOperands aware of scalable
4631 // vectors.
4632 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4633
4634 if (!UniformBase) {
4635 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4636 Index = getValue(Ptr);
4637 IndexType = ISD::SIGNED_SCALED;
4638 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4639 }
4640
4641 EVT IdxVT = Index.getValueType();
4642 EVT EltTy = IdxVT.getVectorElementType();
4643 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4644 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4645 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4646 }
4647
4648 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4649 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4650 Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4651
4652 PendingLoads.push_back(Gather.getValue(1));
4653 setValue(&I, Gather);
4654}
4655
4656void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4657 SDLoc dl = getCurSDLoc();
4658 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4659 AtomicOrdering FailureOrdering = I.getFailureOrdering();
4660 SyncScope::ID SSID = I.getSyncScopeID();
4661
4662 SDValue InChain = getRoot();
4663
4664 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4665 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4666
4667 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4668 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4669
4670 MachineFunction &MF = DAG.getMachineFunction();
4671 MachineMemOperand *MMO = MF.getMachineMemOperand(
4672 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4673 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4674 FailureOrdering);
4675
4676 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4677 dl, MemVT, VTs, InChain,
4678 getValue(I.getPointerOperand()),
4679 getValue(I.getCompareOperand()),
4680 getValue(I.getNewValOperand()), MMO);
4681
4682 SDValue OutChain = L.getValue(2);
4683
4684 setValue(&I, L);
4685 DAG.setRoot(OutChain);
4686}
4687
4688void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4689 SDLoc dl = getCurSDLoc();
4690 ISD::NodeType NT;
4691 switch (I.getOperation()) {
4692 default: llvm_unreachable("Unknown atomicrmw operation")::llvm::llvm_unreachable_internal("Unknown atomicrmw operation"
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4692
)
;
4693 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4694 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
4695 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
4696 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
4697 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4698 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
4699 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
4700 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
4701 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
4702 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4703 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4704 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4705 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4706 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4707 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4708 case AtomicRMWInst::UIncWrap:
4709 NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4710 break;
4711 case AtomicRMWInst::UDecWrap:
4712 NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4713 break;
4714 }
4715 AtomicOrdering Ordering = I.getOrdering();
4716 SyncScope::ID SSID = I.getSyncScopeID();
4717
4718 SDValue InChain = getRoot();
4719
4720 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4721 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4722 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4723
4724 MachineFunction &MF = DAG.getMachineFunction();
4725 MachineMemOperand *MMO = MF.getMachineMemOperand(
4726 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4727 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4728
4729 SDValue L =
4730 DAG.getAtomic(NT, dl, MemVT, InChain,
4731 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4732 MMO);
4733
4734 SDValue OutChain = L.getValue(1);
4735
4736 setValue(&I, L);
4737 DAG.setRoot(OutChain);
4738}
4739
4740void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4741 SDLoc dl = getCurSDLoc();
4742 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4743 SDValue Ops[3];
4744 Ops[0] = getRoot();
4745 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4746 TLI.getFenceOperandTy(DAG.getDataLayout()));
4747 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4748 TLI.getFenceOperandTy(DAG.getDataLayout()));
4749 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4750 setValue(&I, N);
4751 DAG.setRoot(N);
4752}
4753
4754void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4755 SDLoc dl = getCurSDLoc();
4756 AtomicOrdering Order = I.getOrdering();
4757 SyncScope::ID SSID = I.getSyncScopeID();
4758
4759 SDValue InChain = getRoot();
4760
4761 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4762 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4763 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4764
4765 if (!TLI.supportsUnalignedAtomics() &&
4766 I.getAlign().value() < MemVT.getSizeInBits() / 8)
4767 report_fatal_error("Cannot generate unaligned atomic load");
4768
4769 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4770
4771 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4772 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4773 I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4774
4775 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4776
4777 SDValue Ptr = getValue(I.getPointerOperand());
4778
4779 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4780 // TODO: Once this is better exercised by tests, it should be merged with
4781 // the normal path for loads to prevent future divergence.
4782 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4783 if (MemVT != VT)
4784 L = DAG.getPtrExtOrTrunc(L, dl, VT);
4785
4786 setValue(&I, L);
4787 SDValue OutChain = L.getValue(1);
4788 if (!I.isUnordered())
4789 DAG.setRoot(OutChain);
4790 else
4791 PendingLoads.push_back(OutChain);
4792 return;
4793 }
4794
4795 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4796 Ptr, MMO);
4797
4798 SDValue OutChain = L.getValue(1);
4799 if (MemVT != VT)
4800 L = DAG.getPtrExtOrTrunc(L, dl, VT);
4801
4802 setValue(&I, L);
4803 DAG.setRoot(OutChain);
4804}
4805
4806void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4807 SDLoc dl = getCurSDLoc();
4808
4809 AtomicOrdering Ordering = I.getOrdering();
4810 SyncScope::ID SSID = I.getSyncScopeID();
4811
4812 SDValue InChain = getRoot();
4813
4814 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4815 EVT MemVT =
4816 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4817
4818 if (!TLI.supportsUnalignedAtomics() &&
4819 I.getAlign().value() < MemVT.getSizeInBits() / 8)
4820 report_fatal_error("Cannot generate unaligned atomic store");
4821
4822 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4823
4824 MachineFunction &MF = DAG.getMachineFunction();
4825 MachineMemOperand *MMO = MF.getMachineMemOperand(
4826 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4827 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4828
4829 SDValue Val = getValue(I.getValueOperand());
4830 if (Val.getValueType() != MemVT)
4831 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4832 SDValue Ptr = getValue(I.getPointerOperand());
4833
4834 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4835 // TODO: Once this is better exercised by tests, it should be merged with
4836 // the normal path for stores to prevent future divergence.
4837 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4838 setValue(&I, S);
4839 DAG.setRoot(S);
4840 return;
4841 }
4842 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4843 Ptr, Val, MMO);
4844
4845 setValue(&I, OutChain);
4846 DAG.setRoot(OutChain);
4847}
4848
4849/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4850/// node.
4851void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4852 unsigned Intrinsic) {
4853 // Ignore the callsite's attributes. A specific call site may be marked with
4854 // readnone, but the lowering code will expect the chain based on the
4855 // definition.
4856 const Function *F = I.getCalledFunction();
4857 bool HasChain = !F->doesNotAccessMemory();
4858 bool OnlyLoad = HasChain && F->onlyReadsMemory();
4859
4860 // Build the operand list.
4861 SmallVector<SDValue, 8> Ops;
4862 if (HasChain) { // If this intrinsic has side-effects, chainify it.
4863 if (OnlyLoad) {
4864 // We don't need to serialize loads against other loads.
4865 Ops.push_back(DAG.getRoot());
4866 } else {
4867 Ops.push_back(getRoot());
4868 }
4869 }
4870
4871 // Info is set by getTgtMemIntrinsic
4872 TargetLowering::IntrinsicInfo Info;
4873 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4874 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4875 DAG.getMachineFunction(),
4876 Intrinsic);
4877
4878 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4879 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4880 Info.opc == ISD::INTRINSIC_W_CHAIN)
4881 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4882 TLI.getPointerTy(DAG.getDataLayout())));
4883
4884 // Add all operands of the call to the operand list.
4885 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4886 const Value *Arg = I.getArgOperand(i);
4887 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4888 Ops.push_back(getValue(Arg));
4889 continue;
4890 }
4891
4892 // Use TargetConstant instead of a regular constant for immarg.
4893 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4894 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4895 assert(CI->getBitWidth() <= 64 &&(static_cast <bool> (CI->getBitWidth() <= 64 &&
"large intrinsic immediates not handled") ? void (0) : __assert_fail
("CI->getBitWidth() <= 64 && \"large intrinsic immediates not handled\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4896
, __extension__ __PRETTY_FUNCTION__))
4896 "large intrinsic immediates not handled")(static_cast <bool> (CI->getBitWidth() <= 64 &&
"large intrinsic immediates not handled") ? void (0) : __assert_fail
("CI->getBitWidth() <= 64 && \"large intrinsic immediates not handled\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 4896
, __extension__ __PRETTY_FUNCTION__))
;
4897 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4898 } else {
4899 Ops.push_back(
4900 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4901 }
4902 }
4903
4904 SmallVector<EVT, 4> ValueVTs;
4905 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4906
4907 if (HasChain)
4908 ValueVTs.push_back(MVT::Other);
4909
4910 SDVTList VTs = DAG.getVTList(ValueVTs);
4911
4912 // Propagate fast-math-flags from IR to node(s).
4913 SDNodeFlags Flags;
4914 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4915 Flags.copyFMF(*FPMO);
4916 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4917
4918 // Create the node.
4919 SDValue Result;
4920 // In some cases, custom collection of operands from CallInst I may be needed.
4921 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4922 if (IsTgtIntrinsic) {
4923 // This is target intrinsic that touches memory
4924 //
4925 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4926 // didn't yield anything useful.
4927 MachinePointerInfo MPI;
4928 if (Info.ptrVal)
4929 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4930 else if (Info.fallbackAddressSpace)
4931 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4932 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4933 Info.memVT, MPI, Info.align, Info.flags,
4934 Info.size, I.getAAMetadata());
4935 } else if (!HasChain) {
4936 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4937 } else if (!I.getType()->isVoidTy()) {
4938 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4939 } else {
4940 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4941 }
4942
4943 if (HasChain) {
4944 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4945 if (OnlyLoad)
4946 PendingLoads.push_back(Chain);
4947 else
4948 DAG.setRoot(Chain);
4949 }
4950
4951 if (!I.getType()->isVoidTy()) {
4952 if (!isa<VectorType>(I.getType()))
4953 Result = lowerRangeToAssertZExt(DAG, I, Result);
4954
4955 MaybeAlign Alignment = I.getRetAlign();
4956
4957 // Insert `assertalign` node if there's an alignment.
4958 if (InsertAssertAlign && Alignment) {
4959 Result =
4960 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4961 }
4962
4963 setValue(&I, Result);
4964 }
4965}
4966
4967/// GetSignificand - Get the significand and build it into a floating-point
4968/// number with exponent of 1:
4969///
4970/// Op = (Op & 0x007fffff) | 0x3f800000;
4971///
4972/// where Op is the hexadecimal representation of floating point value.
4973static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4974 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4975 DAG.getConstant(0x007fffff, dl, MVT::i32));
4976 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4977 DAG.getConstant(0x3f800000, dl, MVT::i32));
4978 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4979}
4980
4981/// GetExponent - Get the exponent:
4982///
4983/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4984///
4985/// where Op is the hexadecimal representation of floating point value.
4986static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4987 const TargetLowering &TLI, const SDLoc &dl) {
4988 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4989 DAG.getConstant(0x7f800000, dl, MVT::i32));
4990 SDValue t1 = DAG.getNode(
4991 ISD::SRL, dl, MVT::i32, t0,
4992 DAG.getConstant(23, dl,
4993 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4994 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4995 DAG.getConstant(127, dl, MVT::i32));
4996 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4997}
4998
4999/// getF32Constant - Get 32-bit floating point constant.
5000static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5001 const SDLoc &dl) {
5002 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5003 MVT::f32);
5004}
5005
5006static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5007 SelectionDAG &DAG) {
5008 // TODO: What fast-math-flags should be set on the floating-point nodes?
5009
5010 // IntegerPartOfX = ((int32_t)(t0);
5011 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5012
5013 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
5014 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5015 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5016
5017 // IntegerPartOfX <<= 23;
5018 IntegerPartOfX =
5019 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5020 DAG.getConstant(23, dl,
5021 DAG.getTargetLoweringInfo().getShiftAmountTy(
5022 MVT::i32, DAG.getDataLayout())));
5023
5024 SDValue TwoToFractionalPartOfX;
5025 if (LimitFloatPrecision <= 6) {
5026 // For floating-point precision of 6:
5027 //
5028 // TwoToFractionalPartOfX =
5029 // 0.997535578f +
5030 // (0.735607626f + 0.252464424f * x) * x;
5031 //
5032 // error 0.0144103317, which is 6 bits
5033 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5034 getF32Constant(DAG, 0x3e814304, dl));
5035 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5036 getF32Constant(DAG, 0x3f3c50c8, dl));
5037 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5038 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5039 getF32Constant(DAG, 0x3f7f5e7e, dl));
5040 } else if (LimitFloatPrecision <= 12) {
5041 // For floating-point precision of 12:
5042 //
5043 // TwoToFractionalPartOfX =
5044 // 0.999892986f +
5045 // (0.696457318f +
5046 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5047 //
5048 // error 0.000107046256, which is 13 to 14 bits
5049 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5050 getF32Constant(DAG, 0x3da235e3, dl));
5051 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5052 getF32Constant(DAG, 0x3e65b8f3, dl));
5053 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5054 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5055 getF32Constant(DAG, 0x3f324b07, dl));
5056 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5057 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5058 getF32Constant(DAG, 0x3f7ff8fd, dl));
5059 } else { // LimitFloatPrecision <= 18
5060 // For floating-point precision of 18:
5061 //
5062 // TwoToFractionalPartOfX =
5063 // 0.999999982f +
5064 // (0.693148872f +
5065 // (0.240227044f +
5066 // (0.554906021e-1f +
5067 // (0.961591928e-2f +
5068 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5069 // error 2.47208000*10^(-7), which is better than 18 bits
5070 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5071 getF32Constant(DAG, 0x3924b03e, dl));
5072 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5073 getF32Constant(DAG, 0x3ab24b87, dl));
5074 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5075 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5076 getF32Constant(DAG, 0x3c1d8c17, dl));
5077 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5078 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5079 getF32Constant(DAG, 0x3d634a1d, dl));
5080 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5081 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5082 getF32Constant(DAG, 0x3e75fe14, dl));
5083 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5084 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5085 getF32Constant(DAG, 0x3f317234, dl));
5086 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5087 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5088 getF32Constant(DAG, 0x3f800000, dl));
5089 }
5090
5091 // Add the exponent into the result in integer domain.
5092 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5093 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5094 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5095}
5096
5097/// expandExp - Lower an exp intrinsic. Handles the special sequences for
5098/// limited-precision mode.
5099static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5100 const TargetLowering &TLI, SDNodeFlags Flags) {
5101 if (Op.getValueType() == MVT::f32 &&
5102 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5103
5104 // Put the exponent in the right bit position for later addition to the
5105 // final result:
5106 //
5107 // t0 = Op * log2(e)
5108
5109 // TODO: What fast-math-flags should be set here?
5110 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5111 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5112 return getLimitedPrecisionExp2(t0, dl, DAG);
5113 }
5114
5115 // No special expansion.
5116 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5117}
5118
5119/// expandLog - Lower a log intrinsic. Handles the special sequences for
5120/// limited-precision mode.
5121static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5122 const TargetLowering &TLI, SDNodeFlags Flags) {
5123 // TODO: What fast-math-flags should be set on the floating-point nodes?
5124
5125 if (Op.getValueType() == MVT::f32 &&
5126 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5127 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5128
5129 // Scale the exponent by log(2).
5130 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5131 SDValue LogOfExponent =
5132 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5133 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5134
5135 // Get the significand and build it into a floating-point number with
5136 // exponent of 1.
5137 SDValue X = GetSignificand(DAG, Op1, dl);
5138
5139 SDValue LogOfMantissa;
5140 if (LimitFloatPrecision <= 6) {
5141 // For floating-point precision of 6:
5142 //
5143 // LogofMantissa =
5144 // -1.1609546f +
5145 // (1.4034025f - 0.23903021f * x) * x;
5146 //
5147 // error 0.0034276066, which is better than 8 bits
5148 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5149 getF32Constant(DAG, 0xbe74c456, dl));
5150 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5151 getF32Constant(DAG, 0x3fb3a2b1, dl));
5152 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5153 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5154 getF32Constant(DAG, 0x3f949a29, dl));
5155 } else if (LimitFloatPrecision <= 12) {
5156 // For floating-point precision of 12:
5157 //
5158 // LogOfMantissa =
5159 // -1.7417939f +
5160 // (2.8212026f +
5161 // (-1.4699568f +
5162 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5163 //
5164 // error 0.000061011436, which is 14 bits
5165 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5166 getF32Constant(DAG, 0xbd67b6d6, dl));
5167 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5168 getF32Constant(DAG, 0x3ee4f4b8, dl));
5169 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5170 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5171 getF32Constant(DAG, 0x3fbc278b, dl));
5172 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5173 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5174 getF32Constant(DAG, 0x40348e95, dl));
5175 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5176 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5177 getF32Constant(DAG, 0x3fdef31a, dl));
5178 } else { // LimitFloatPrecision <= 18
5179 // For floating-point precision of 18:
5180 //
5181 // LogOfMantissa =
5182 // -2.1072184f +
5183 // (4.2372794f +
5184 // (-3.7029485f +
5185 // (2.2781945f +
5186 // (-0.87823314f +
5187 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5188 //
5189 // error 0.0000023660568, which is better than 18 bits
5190 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5191 getF32Constant(DAG, 0xbc91e5ac, dl));
5192 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5193 getF32Constant(DAG, 0x3e4350aa, dl));
5194 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5195 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5196 getF32Constant(DAG, 0x3f60d3e3, dl));
5197 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5198 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5199 getF32Constant(DAG, 0x4011cdf0, dl));
5200 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5201 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5202 getF32Constant(DAG, 0x406cfd1c, dl));
5203 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5204 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5205 getF32Constant(DAG, 0x408797cb, dl));
5206 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5207 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5208 getF32Constant(DAG, 0x4006dcab, dl));
5209 }
5210
5211 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5212 }
5213
5214 // No special expansion.
5215 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5216}
5217
5218/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5219/// limited-precision mode.
5220static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5221 const TargetLowering &TLI, SDNodeFlags Flags) {
5222 // TODO: What fast-math-flags should be set on the floating-point nodes?
5223
5224 if (Op.getValueType() == MVT::f32 &&
5225 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5226 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5227
5228 // Get the exponent.
5229 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5230
5231 // Get the significand and build it into a floating-point number with
5232 // exponent of 1.
5233 SDValue X = GetSignificand(DAG, Op1, dl);
5234
5235 // Different possible minimax approximations of significand in
5236 // floating-point for various degrees of accuracy over [1,2].
5237 SDValue Log2ofMantissa;
5238 if (LimitFloatPrecision <= 6) {
5239 // For floating-point precision of 6:
5240 //
5241 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5242 //
5243 // error 0.0049451742, which is more than 7 bits
5244 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5245 getF32Constant(DAG, 0xbeb08fe0, dl));
5246 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5247 getF32Constant(DAG, 0x40019463, dl));
5248 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5249 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5250 getF32Constant(DAG, 0x3fd6633d, dl));
5251 } else if (LimitFloatPrecision <= 12) {
5252 // For floating-point precision of 12:
5253 //
5254 // Log2ofMantissa =
5255 // -2.51285454f +
5256 // (4.07009056f +
5257 // (-2.12067489f +
5258 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5259 //
5260 // error 0.0000876136000, which is better than 13 bits
5261 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5262 getF32Constant(DAG, 0xbda7262e, dl));
5263 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5264 getF32Constant(DAG, 0x3f25280b, dl));
5265 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5266 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5267 getF32Constant(DAG, 0x4007b923, dl));
5268 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5269 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5270 getF32Constant(DAG, 0x40823e2f, dl));
5271 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5272 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5273 getF32Constant(DAG, 0x4020d29c, dl));
5274 } else { // LimitFloatPrecision <= 18
5275 // For floating-point precision of 18:
5276 //
5277 // Log2ofMantissa =
5278 // -3.0400495f +
5279 // (6.1129976f +
5280 // (-5.3420409f +
5281 // (3.2865683f +
5282 // (-1.2669343f +
5283 // (0.27515199f -
5284 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5285 //
5286 // error 0.0000018516, which is better than 18 bits
5287 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5288 getF32Constant(DAG, 0xbcd2769e, dl));
5289 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5290 getF32Constant(DAG, 0x3e8ce0b9, dl));
5291 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5292 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5293 getF32Constant(DAG, 0x3fa22ae7, dl));
5294 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5295 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5296 getF32Constant(DAG, 0x40525723, dl));
5297 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5298 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5299 getF32Constant(DAG, 0x40aaf200, dl));
5300 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5301 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5302 getF32Constant(DAG, 0x40c39dad, dl));
5303 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5304 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5305 getF32Constant(DAG, 0x4042902c, dl));
5306 }
5307
5308 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5309 }
5310
5311 // No special expansion.
5312 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5313}
5314
5315/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5316/// limited-precision mode.
5317static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5318 const TargetLowering &TLI, SDNodeFlags Flags) {
5319 // TODO: What fast-math-flags should be set on the floating-point nodes?
5320
5321 if (Op.getValueType() == MVT::f32 &&
5322 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5323 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5324
5325 // Scale the exponent by log10(2) [0.30102999f].
5326 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5327 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5328 getF32Constant(DAG, 0x3e9a209a, dl));
5329
5330 // Get the significand and build it into a floating-point number with
5331 // exponent of 1.
5332 SDValue X = GetSignificand(DAG, Op1, dl);
5333
5334 SDValue Log10ofMantissa;
5335 if (LimitFloatPrecision <= 6) {
5336 // For floating-point precision of 6:
5337 //
5338 // Log10ofMantissa =
5339 // -0.50419619f +
5340 // (0.60948995f - 0.10380950f * x) * x;
5341 //
5342 // error 0.0014886165, which is 6 bits
5343 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5344 getF32Constant(DAG, 0xbdd49a13, dl));
5345 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5346 getF32Constant(DAG, 0x3f1c0789, dl));
5347 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5348 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5349 getF32Constant(DAG, 0x3f011300, dl));
5350 } else if (LimitFloatPrecision <= 12) {
5351 // For floating-point precision of 12:
5352 //
5353 // Log10ofMantissa =
5354 // -0.64831180f +
5355 // (0.91751397f +
5356 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5357 //
5358 // error 0.00019228036, which is better than 12 bits
5359 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5360 getF32Constant(DAG, 0x3d431f31, dl));
5361 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5362 getF32Constant(DAG, 0x3ea21fb2, dl));
5363 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5364 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5365 getF32Constant(DAG, 0x3f6ae232, dl));
5366 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5367 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5368 getF32Constant(DAG, 0x3f25f7c3, dl));
5369 } else { // LimitFloatPrecision <= 18
5370 // For floating-point precision of 18:
5371 //
5372 // Log10ofMantissa =
5373 // -0.84299375f +
5374 // (1.5327582f +
5375 // (-1.0688956f +
5376 // (0.49102474f +
5377 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5378 //
5379 // error 0.0000037995730, which is better than 18 bits
5380 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5381 getF32Constant(DAG, 0x3c5d51ce, dl));
5382 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5383 getF32Constant(DAG, 0x3e00685a, dl));
5384 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5385 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5386 getF32Constant(DAG, 0x3efb6798, dl));
5387 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5388 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5389 getF32Constant(DAG, 0x3f88d192, dl));
5390 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5391 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5392 getF32Constant(DAG, 0x3fc4316c, dl));
5393 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5394 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5395 getF32Constant(DAG, 0x3f57ce70, dl));
5396 }
5397
5398 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5399 }
5400
5401 // No special expansion.
5402 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5403}
5404
5405/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5406/// limited-precision mode.
5407static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5408 const TargetLowering &TLI, SDNodeFlags Flags) {
5409 if (Op.getValueType() == MVT::f32 &&
5410 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5411 return getLimitedPrecisionExp2(Op, dl, DAG);
5412
5413 // No special expansion.
5414 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5415}
5416
5417/// visitPow - Lower a pow intrinsic. Handles the special sequences for
5418/// limited-precision mode with x == 10.0f.
5419static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5420 SelectionDAG &DAG, const TargetLowering &TLI,
5421 SDNodeFlags Flags) {
5422 bool IsExp10 = false;
5423 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5424 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5425 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5426 APFloat Ten(10.0f);
5427 IsExp10 = LHSC->isExactlyValue(Ten);
5428 }
5429 }
5430
5431 // TODO: What fast-math-flags should be set on the FMUL node?
5432 if (IsExp10) {
5433 // Put the exponent in the right bit position for later addition to the
5434 // final result:
5435 //
5436 // #define LOG2OF10 3.3219281f
5437 // t0 = Op * LOG2OF10;
5438 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5439 getF32Constant(DAG, 0x40549a78, dl));
5440 return getLimitedPrecisionExp2(t0, dl, DAG);
5441 }
5442
5443 // No special expansion.
5444 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5445}
5446
5447/// ExpandPowI - Expand a llvm.powi intrinsic.
5448static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5449 SelectionDAG &DAG) {
5450 // If RHS is a constant, we can expand this out to a multiplication tree if
5451 // it's beneficial on the target, otherwise we end up lowering to a call to
5452 // __powidf2 (for example).
5453 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5454 unsigned Val = RHSC->getSExtValue();
5455
5456 // powi(x, 0) -> 1.0
5457 if (Val == 0)
5458 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5459
5460 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5461 Val, DAG.shouldOptForSize())) {
5462 // Get the exponent as a positive value.
5463 if ((int)Val < 0)
5464 Val = -Val;
5465 // We use the simple binary decomposition method to generate the multiply
5466 // sequence. There are more optimal ways to do this (for example,
5467 // powi(x,15) generates one more multiply than it should), but this has
5468 // the benefit of being both really simple and much better than a libcall.
5469 SDValue Res; // Logically starts equal to 1.0
5470 SDValue CurSquare = LHS;
5471 // TODO: Intrinsics should have fast-math-flags that propagate to these
5472 // nodes.
5473 while (Val) {
5474 if (Val & 1) {
5475 if (Res.getNode())
5476 Res =
5477 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5478 else
5479 Res = CurSquare; // 1.0*CurSquare.
5480 }
5481
5482 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5483 CurSquare, CurSquare);
5484 Val >>= 1;
5485 }
5486
5487 // If the original was negative, invert the result, producing 1/(x*x*x).
5488 if (RHSC->getSExtValue() < 0)
5489 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5490 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5491 return Res;
5492 }
5493 }
5494
5495 // Otherwise, expand to a libcall.
5496 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5497}
5498
5499static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5500 SDValue LHS, SDValue RHS, SDValue Scale,
5501 SelectionDAG &DAG, const TargetLowering &TLI) {
5502 EVT VT = LHS.getValueType();
5503 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5504 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5505 LLVMContext &Ctx = *DAG.getContext();
5506
5507 // If the type is legal but the operation isn't, this node might survive all
5508 // the way to operation legalization. If we end up there and we do not have
5509 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5510 // node.
5511
5512 // Coax the legalizer into expanding the node during type legalization instead
5513 // by bumping the size by one bit. This will force it to Promote, enabling the
5514 // early expansion and avoiding the need to expand later.
5515
5516 // We don't have to do this if Scale is 0; that can always be expanded, unless
5517 // it's a saturating signed operation. Those can experience true integer
5518 // division overflow, a case which we must avoid.
5519
5520 // FIXME: We wouldn't have to do this (or any of the early
5521 // expansion/promotion) if it was possible to expand a libcall of an
5522 // illegal type during operation legalization. But it's not, so things
5523 // get a bit hacky.
5524 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5525 if ((ScaleInt > 0 || (Saturating && Signed)) &&
5526 (TLI.isTypeLegal(VT) ||
5527 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5528 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5529 Opcode, VT, ScaleInt);
5530 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5531 EVT PromVT;
5532 if (VT.isScalarInteger())
5533 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5534 else if (VT.isVector()) {
5535 PromVT = VT.getVectorElementType();
5536 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5537 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5538 } else
5539 llvm_unreachable("Wrong VT for DIVFIX?")::llvm::llvm_unreachable_internal("Wrong VT for DIVFIX?", "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp"
, 5539)
;
5540 if (Signed) {
5541 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5542 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5543 } else {
5544 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5545 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5546 }
5547 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5548 // For saturating operations, we need to shift up the LHS to get the
5549 // proper saturation width, and then shift down again afterwards.
5550 if (Saturating)
5551 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5552 DAG.getConstant(1, DL, ShiftTy));
5553 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5554 if (Saturating)
5555 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5556 DAG.getConstant(1, DL, ShiftTy));
5557 return DAG.getZExtOrTrunc(Res, DL, VT);
5558 }
5559 }
5560
5561 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5562}
5563
5564// getUnderlyingArgRegs - Find underlying registers used for a truncated,
5565// bitcasted, or split argument. Returns a list of <Register, size in bits>
5566static void
5567getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5568 const SDValue &N) {
5569 switch (N.getOpcode()) {
5570 case ISD::CopyFromReg: {
5571 SDValue Op = N.getOperand(1);
5572 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5573 Op.getValueType().getSizeInBits());
5574 return;
5575 }
5576 case ISD::BITCAST:
5577 case ISD::AssertZext:
5578 case ISD::AssertSext:
5579 case ISD::TRUNCATE:
5580 getUnderlyingArgRegs(Regs, N.getOperand(0));
5581 return;
5582 case ISD::BUILD_PAIR:
5583 case ISD::BUILD_VECTOR:
5584 case ISD::CONCAT_VECTORS:
5585 for (SDValue Op : N->op_values())
5586 getUnderlyingArgRegs(Regs, Op);
5587 return;
5588 default:
5589 return;
5590 }
5591}
5592
5593/// If the DbgValueInst is a dbg_value of a function argument, create the
5594/// corresponding DBG_VALUE machine instruction for it now. At the end of
5595/// instruction selection, they will be inserted to the entry BB.
5596/// We don't currently support this for variadic dbg_values, as they shouldn't
5597/// appear for function arguments or in the prologue.
5598bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5599 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5600 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5601 const Argument *Arg = dyn_cast<Argument>(V);
5602 if (!Arg)
5603 return false;
5604
5605 MachineFunction &MF = DAG.getMachineFunction();
5606 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5607
5608 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5609 // we've been asked to pursue.
5610 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5611 bool Indirect) {
5612 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5613 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5614 // pointing at the VReg, which will be patched up later.
5615 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5616 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5617 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5618 /* isKill */ false, /* isDead */ false,
5619 /* isUndef */ false, /* isEarlyClobber */ false,
5620 /* SubReg */ 0, /* isDebug */ true)});
5621
5622 auto *NewDIExpr = FragExpr;
5623 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5624 // the DIExpression.
5625 if (Indirect)
5626 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5627 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5628 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5629 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5630 } else {
5631 // Create a completely standard DBG_VALUE.
5632 auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5633 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5634 }
5635 };
5636
5637 if (Kind == FuncArgumentDbgValueKind::Value) {
5638 // ArgDbgValues are hoisted to the beginning of the entry block. So we
5639 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5640 // the entry block.
5641 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5642 if (!IsInEntryBlock)
5643 return false;
5644
5645 // ArgDbgValues are hoisted to the beginning of the entry block. So we
5646 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5647 // variable that also is a param.
5648 //
5649 // Although, if we are at the top of the entry block already, we can still
5650 // emit using ArgDbgValue. This might catch some situations when the
5651 // dbg.value refers to an argument that isn't used in the entry block, so
5652 // any CopyToReg node would be optimized out and the only way to express
5653 // this DBG_VALUE is by using the physical reg (or FI) as done in this
5654 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
5655 // we should only emit as ArgDbgValue if the Variable is an argument to the
5656 // current function, and the dbg.value intrinsic is found in the entry
5657 // block.
5658 bool VariableIsFunctionInputArg = Variable->isParameter() &&
5659 !DL->getInlinedAt();
5660 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5661 if (!IsInPrologue && !VariableIsFunctionInputArg)
5662 return false;
5663
5664 // Here we assume that a function argument on IR level only can be used to
5665 // describe one input parameter on source level. If we for example have
5666 // source code like this
5667 //
5668 // struct A { long x, y; };
5669 // void foo(struct A a, long b) {
5670 // ...
5671 // b = a.x;
5672 // ...
5673 // }
5674 //
5675 // and IR like this
5676 //
5677 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
5678 // entry:
5679 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5680 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5681 // call void @llvm.dbg.value(metadata i32 %b, "b",
5682 // ...
5683 // call void @llvm.dbg.value(metadata i32 %a1, "b"
5684 // ...
5685 //
5686 // then the last dbg.value is describing a parameter "b" using a value that
5687 // is an argument. But since we already has used %a1 to describe a parameter
5688 // we should not handle that last dbg.value here (that would result in an
5689 // incorrect hoisting of the DBG_VALUE to the function entry).
5690 // Notice that we allow one dbg.value per IR level argument, to accommodate
5691 // for the situation with fragments above.
5692 if (VariableIsFunctionInputArg) {
5693 unsigned ArgNo = Arg->getArgNo();
5694 if (ArgNo >= FuncInfo.DescribedArgs.size())
5695 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5696 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5697 return false;
5698 FuncInfo.DescribedArgs.set(ArgNo);
5699 }
5700 }
5701
5702 bool IsIndirect = false;
5703 std::optional<MachineOperand> Op;
5704 // Some arguments' frame index is recorded during argument lowering.
5705 int FI = FuncInfo.getArgumentFrameIndex(Arg);
5706 if (FI != std::numeric_limits<int>::max())
5707 Op = MachineOperand::CreateFI(FI);
5708
5709 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5710 if (!Op && N.getNode()) {
5711 getUnderlyingArgRegs(ArgRegsAndSizes, N);
5712 Register Reg;
5713 if (ArgRegsAndSizes.size() == 1)
5714 Reg = ArgRegsAndSizes.front().first;
5715
5716 if (Reg && Reg.isVirtual()) {
5717 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5718 Register PR = RegInfo.getLiveInPhysReg(Reg);
5719 if (PR)
5720 Reg = PR;
5721 }
5722 if (Reg) {
5723 Op = MachineOperand::CreateReg(Reg, false);
5724 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5725 }
5726 }
5727
5728 if (!Op && N.getNode()) {
5729 // Check if frame index is available.
5730 SDValue LCandidate = peekThroughBitcasts(N);
5731 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5732 if (FrameIndexSDNode *FINode =
5733 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5734 Op = MachineOperand::CreateFI(FINode->getIndex());
5735 }
5736
5737 if (!Op) {
5738 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5739 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5740 SplitRegs) {
5741 unsigned Offset = 0;
5742 for (const auto &RegAndSize : SplitRegs) {
5743 // If the expression is already a fragment, the current register
5744 // offset+size might extend beyond the fragment. In this case, only
5745 // the register bits that are inside the fragment are relevant.
5746 int RegFragmentSizeInBits = RegAndSize.second;
5747 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5748 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5749 // The register is entirely outside the expression fragment,
5750 // so is irrelevant for debug info.
5751 if (Offset >= ExprFragmentSizeInBits)
5752 break;
5753 // The register is partially outside the expression fragment, only
5754 // the low bits within the fragment are relevant for debug info.
5755 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5756 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5757 }
5758 }
5759
5760 auto FragmentExpr = DIExpression::createFragmentExpression(
5761 Expr, Offset, RegFragmentSizeInBits);
5762 Offset += RegAndSize.second;
5763 // If a valid fragment expression cannot be created, the variable's
5764 // correct value cannot be determined and so it is set as Undef.
5765 if (!FragmentExpr) {
5766 SDDbgValue *SDV = DAG.getConstantDbgValue(
5767 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5768 DAG.AddDbgValue(SDV, false);
5769 continue;
5770 }
5771 MachineInstr *NewMI =
5772 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5773 Kind != FuncArgumentDbgValueKind::Value);
5774 FuncInfo.ArgDbgValues.push_back(NewMI);
5775 }
5776 };
5777
5778 // Check if ValueMap has reg number.
5779 DenseMap<const Value *, Register>::const_iterator
5780 VMI = FuncInfo.ValueMap.find(V);
5781 if (VMI != FuncInfo.ValueMap.end()) {
5782 const auto &TLI = DAG.getTargetLoweringInfo();
5783 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5784 V->getType(), std::nullopt);
5785 if (RFV.occupiesMultipleRegs()) {
5786 splitMultiRegDbgValue(RFV.getRegsAndSizes());
5787 return true;
5788 }
5789
5790 Op = MachineOperand::CreateReg(VMI->second, false);
5791 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5792 } else if (ArgRegsAndSizes.size() > 1) {
5793 // This was split due to the calling convention, and no virtual register
5794 // mapping exists for the value.
5795 splitMultiRegDbgValue(ArgRegsAndSizes);
5796 return true;
5797 }
5798 }
5799
5800 if (!Op)
5801 return false;
5802
5803 assert(Variable->isValidLocationForIntrinsic(DL) &&(static_cast <bool> (Variable->isValidLocationForIntrinsic
(DL) && "Expected inlined-at fields to agree") ? void
(0) : __assert_fail ("Variable->isValidLocationForIntrinsic(DL) && \"Expected inlined-at fields to agree\""
, "llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp", 5804
, __extension__ __PRETTY_FUNCTION__))
5804