Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1135, 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/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/CodeGen/SelectionDAG -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/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-16/lib/clang/16.0.0/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/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O3 -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/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -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-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp

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