Bug Summary

File:llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1101, 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 -disable-llvm-verifier -discard-value-names -main-file-name SelectionDAGBuilder.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/lib/CodeGen/SelectionDAG -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-17-195756-12974-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp

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