1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/Analysis/BranchProbabilityInfo.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/EHPersonalities.h"
28 #include "llvm/Analysis/Loads.h"
29 #include "llvm/Analysis/MemoryLocation.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/CodeGen/Analysis.h"
33 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
34 #include "llvm/CodeGen/CodeGenCommonISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCMetadata.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
42 #include "llvm/CodeGen/MachineMemOperand.h"
43 #include "llvm/CodeGen/MachineModuleInfo.h"
44 #include "llvm/CodeGen/MachineOperand.h"
45 #include "llvm/CodeGen/MachineRegisterInfo.h"
46 #include "llvm/CodeGen/RuntimeLibcalls.h"
47 #include "llvm/CodeGen/SelectionDAG.h"
48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
49 #include "llvm/CodeGen/StackMaps.h"
50 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
51 #include "llvm/CodeGen/TargetFrameLowering.h"
52 #include "llvm/CodeGen/TargetInstrInfo.h"
53 #include "llvm/CodeGen/TargetOpcodes.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/TargetSubtargetInfo.h"
56 #include "llvm/CodeGen/WinEHFuncInfo.h"
57 #include "llvm/IR/Argument.h"
58 #include "llvm/IR/Attributes.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/CFG.h"
61 #include "llvm/IR/CallingConv.h"
62 #include "llvm/IR/Constant.h"
63 #include "llvm/IR/ConstantRange.h"
64 #include "llvm/IR/Constants.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugInfo.h"
67 #include "llvm/IR/DebugInfoMetadata.h"
68 #include "llvm/IR/DerivedTypes.h"
69 #include "llvm/IR/DiagnosticInfo.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/GetElementPtrTypeIterator.h"
72 #include "llvm/IR/InlineAsm.h"
73 #include "llvm/IR/InstrTypes.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/Intrinsics.h"
77 #include "llvm/IR/IntrinsicsAArch64.h"
78 #include "llvm/IR/IntrinsicsWebAssembly.h"
79 #include "llvm/IR/LLVMContext.h"
80 #include "llvm/IR/Metadata.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/Operator.h"
83 #include "llvm/IR/PatternMatch.h"
84 #include "llvm/IR/Statepoint.h"
85 #include "llvm/IR/Type.h"
86 #include "llvm/IR/User.h"
87 #include "llvm/IR/Value.h"
88 #include "llvm/MC/MCContext.h"
89 #include "llvm/Support/AtomicOrdering.h"
90 #include "llvm/Support/Casting.h"
91 #include "llvm/Support/CommandLine.h"
92 #include "llvm/Support/Compiler.h"
93 #include "llvm/Support/Debug.h"
94 #include "llvm/Support/MathExtras.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Target/TargetIntrinsicInfo.h"
97 #include "llvm/Target/TargetMachine.h"
98 #include "llvm/Target/TargetOptions.h"
99 #include "llvm/Transforms/Utils/Local.h"
100 #include <cstddef>
101 #include <iterator>
102 #include <limits>
103 #include <optional>
104 #include <tuple>
105
106 using namespace llvm;
107 using namespace PatternMatch;
108 using namespace SwitchCG;
109
110 #define DEBUG_TYPE "isel"
111
112 /// LimitFloatPrecision - Generate low-precision inline sequences for
113 /// some float libcalls (6, 8 or 12 bits).
114 static unsigned LimitFloatPrecision;
115
116 static cl::opt<bool>
117 InsertAssertAlign("insert-assert-align", cl::init(true),
118 cl::desc("Insert the experimental `assertalign` node."),
119 cl::ReallyHidden);
120
121 static cl::opt<unsigned, true>
122 LimitFPPrecision("limit-float-precision",
123 cl::desc("Generate low-precision inline sequences "
124 "for some float libcalls"),
125 cl::location(LimitFloatPrecision), cl::Hidden,
126 cl::init(0));
127
128 static cl::opt<unsigned> SwitchPeelThreshold(
129 "switch-peel-threshold", cl::Hidden, cl::init(66),
130 cl::desc("Set the case probability threshold for peeling the case from a "
131 "switch statement. A value greater than 100 will void this "
132 "optimization"));
133
134 // Limit the width of DAG chains. This is important in general to prevent
135 // DAG-based analysis from blowing up. For example, alias analysis and
136 // load clustering may not complete in reasonable time. It is difficult to
137 // recognize and avoid this situation within each individual analysis, and
138 // future analyses are likely to have the same behavior. Limiting DAG width is
139 // the safe approach and will be especially important with global DAGs.
140 //
141 // MaxParallelChains default is arbitrarily high to avoid affecting
142 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
143 // sequence over this should have been converted to llvm.memcpy by the
144 // frontend. It is easy to induce this behavior with .ll code such as:
145 // %buffer = alloca [4096 x i8]
146 // %data = load [4096 x i8]* %argPtr
147 // store [4096 x i8] %data, [4096 x i8]* %buffer
148 static const unsigned MaxParallelChains = 64;
149
150 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
151 const SDValue *Parts, unsigned NumParts,
152 MVT PartVT, EVT ValueVT, const Value *V,
153 std::optional<CallingConv::ID> CC);
154
155 /// getCopyFromParts - Create a value that contains the specified legal parts
156 /// combined into the value they represent. If the parts combine to a type
157 /// larger than ValueVT then AssertOp can be used to specify whether the extra
158 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
159 /// (ISD::AssertSext).
160 static SDValue
getCopyFromParts(SelectionDAG & DAG,const SDLoc & DL,const SDValue * Parts,unsigned NumParts,MVT PartVT,EVT ValueVT,const Value * V,std::optional<CallingConv::ID> CC=std::nullopt,std::optional<ISD::NodeType> AssertOp=std::nullopt)161 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
162 unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
163 std::optional<CallingConv::ID> CC = std::nullopt,
164 std::optional<ISD::NodeType> AssertOp = std::nullopt) {
165 // Let the target assemble the parts if it wants to
166 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
167 if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
168 PartVT, ValueVT, CC))
169 return Val;
170
171 if (ValueVT.isVector())
172 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
173 CC);
174
175 assert(NumParts > 0 && "No parts to assemble!");
176 SDValue Val = Parts[0];
177
178 if (NumParts > 1) {
179 // Assemble the value from multiple parts.
180 if (ValueVT.isInteger()) {
181 unsigned PartBits = PartVT.getSizeInBits();
182 unsigned ValueBits = ValueVT.getSizeInBits();
183
184 // Assemble the power of 2 part.
185 unsigned RoundParts = llvm::bit_floor(NumParts);
186 unsigned RoundBits = PartBits * RoundParts;
187 EVT RoundVT = RoundBits == ValueBits ?
188 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
189 SDValue Lo, Hi;
190
191 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
192
193 if (RoundParts > 2) {
194 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
195 PartVT, HalfVT, V);
196 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
197 RoundParts / 2, PartVT, HalfVT, V);
198 } else {
199 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
200 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
201 }
202
203 if (DAG.getDataLayout().isBigEndian())
204 std::swap(Lo, Hi);
205
206 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
207
208 if (RoundParts < NumParts) {
209 // Assemble the trailing non-power-of-2 part.
210 unsigned OddParts = NumParts - RoundParts;
211 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
212 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
213 OddVT, V, CC);
214
215 // Combine the round and odd parts.
216 Lo = Val;
217 if (DAG.getDataLayout().isBigEndian())
218 std::swap(Lo, Hi);
219 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
220 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
221 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
222 DAG.getConstant(Lo.getValueSizeInBits(), DL,
223 TLI.getShiftAmountTy(
224 TotalVT, DAG.getDataLayout())));
225 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
226 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
227 }
228 } else if (PartVT.isFloatingPoint()) {
229 // FP split into multiple FP parts (for ppcf128)
230 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
231 "Unexpected split");
232 SDValue Lo, Hi;
233 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
234 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
235 if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
236 std::swap(Lo, Hi);
237 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
238 } else {
239 // FP split into integer parts (soft fp)
240 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
241 !PartVT.isVector() && "Unexpected split");
242 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
243 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
244 }
245 }
246
247 // There is now one part, held in Val. Correct it to match ValueVT.
248 // PartEVT is the type of the register class that holds the value.
249 // ValueVT is the type of the inline asm operation.
250 EVT PartEVT = Val.getValueType();
251
252 if (PartEVT == ValueVT)
253 return Val;
254
255 if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
256 ValueVT.bitsLT(PartEVT)) {
257 // For an FP value in an integer part, we need to truncate to the right
258 // width first.
259 PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
260 Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
261 }
262
263 // Handle types that have the same size.
264 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
265 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
266
267 // Handle types with different sizes.
268 if (PartEVT.isInteger() && ValueVT.isInteger()) {
269 if (ValueVT.bitsLT(PartEVT)) {
270 // For a truncate, see if we have any information to
271 // indicate whether the truncated bits will always be
272 // zero or sign-extension.
273 if (AssertOp)
274 Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
275 DAG.getValueType(ValueVT));
276 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
277 }
278 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
279 }
280
281 if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
282 // FP_ROUND's are always exact here.
283 if (ValueVT.bitsLT(Val.getValueType()))
284 return DAG.getNode(
285 ISD::FP_ROUND, DL, ValueVT, Val,
286 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
287
288 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
289 }
290
291 // Handle MMX to a narrower integer type by bitcasting MMX to integer and
292 // then truncating.
293 if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
294 ValueVT.bitsLT(PartEVT)) {
295 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
296 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
297 }
298
299 report_fatal_error("Unknown mismatch in getCopyFromParts!");
300 }
301
diagnosePossiblyInvalidConstraint(LLVMContext & Ctx,const Value * V,const Twine & ErrMsg)302 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
303 const Twine &ErrMsg) {
304 const Instruction *I = dyn_cast_or_null<Instruction>(V);
305 if (!V)
306 return Ctx.emitError(ErrMsg);
307
308 const char *AsmError = ", possible invalid constraint for vector type";
309 if (const CallInst *CI = dyn_cast<CallInst>(I))
310 if (CI->isInlineAsm())
311 return Ctx.emitError(I, ErrMsg + AsmError);
312
313 return Ctx.emitError(I, ErrMsg);
314 }
315
316 /// getCopyFromPartsVector - Create a value that contains the specified legal
317 /// parts combined into the value they represent. If the parts combine to a
318 /// type larger than ValueVT then AssertOp can be used to specify whether the
319 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
320 /// ValueVT (ISD::AssertSext).
getCopyFromPartsVector(SelectionDAG & DAG,const SDLoc & DL,const SDValue * Parts,unsigned NumParts,MVT PartVT,EVT ValueVT,const Value * V,std::optional<CallingConv::ID> CallConv)321 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
322 const SDValue *Parts, unsigned NumParts,
323 MVT PartVT, EVT ValueVT, const Value *V,
324 std::optional<CallingConv::ID> CallConv) {
325 assert(ValueVT.isVector() && "Not a vector value");
326 assert(NumParts > 0 && "No parts to assemble!");
327 const bool IsABIRegCopy = CallConv.has_value();
328
329 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
330 SDValue Val = Parts[0];
331
332 // Handle a multi-element vector.
333 if (NumParts > 1) {
334 EVT IntermediateVT;
335 MVT RegisterVT;
336 unsigned NumIntermediates;
337 unsigned NumRegs;
338
339 if (IsABIRegCopy) {
340 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
341 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
342 NumIntermediates, RegisterVT);
343 } else {
344 NumRegs =
345 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
346 NumIntermediates, RegisterVT);
347 }
348
349 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
350 NumParts = NumRegs; // Silence a compiler warning.
351 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
352 assert(RegisterVT.getSizeInBits() ==
353 Parts[0].getSimpleValueType().getSizeInBits() &&
354 "Part type sizes don't match!");
355
356 // Assemble the parts into intermediate operands.
357 SmallVector<SDValue, 8> Ops(NumIntermediates);
358 if (NumIntermediates == NumParts) {
359 // If the register was not expanded, truncate or copy the value,
360 // as appropriate.
361 for (unsigned i = 0; i != NumParts; ++i)
362 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
363 PartVT, IntermediateVT, V, CallConv);
364 } else if (NumParts > 0) {
365 // If the intermediate type was expanded, build the intermediate
366 // operands from the parts.
367 assert(NumParts % NumIntermediates == 0 &&
368 "Must expand into a divisible number of parts!");
369 unsigned Factor = NumParts / NumIntermediates;
370 for (unsigned i = 0; i != NumIntermediates; ++i)
371 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
372 PartVT, IntermediateVT, V, CallConv);
373 }
374
375 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
376 // intermediate operands.
377 EVT BuiltVectorTy =
378 IntermediateVT.isVector()
379 ? EVT::getVectorVT(
380 *DAG.getContext(), IntermediateVT.getScalarType(),
381 IntermediateVT.getVectorElementCount() * NumParts)
382 : EVT::getVectorVT(*DAG.getContext(),
383 IntermediateVT.getScalarType(),
384 NumIntermediates);
385 Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
386 : ISD::BUILD_VECTOR,
387 DL, BuiltVectorTy, Ops);
388 }
389
390 // There is now one part, held in Val. Correct it to match ValueVT.
391 EVT PartEVT = Val.getValueType();
392
393 if (PartEVT == ValueVT)
394 return Val;
395
396 if (PartEVT.isVector()) {
397 // Vector/Vector bitcast.
398 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
399 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
400
401 // If the parts vector has more elements than the value vector, then we
402 // have a vector widening case (e.g. <2 x float> -> <4 x float>).
403 // Extract the elements we want.
404 if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
405 assert((PartEVT.getVectorElementCount().getKnownMinValue() >
406 ValueVT.getVectorElementCount().getKnownMinValue()) &&
407 (PartEVT.getVectorElementCount().isScalable() ==
408 ValueVT.getVectorElementCount().isScalable()) &&
409 "Cannot narrow, it would be a lossy transformation");
410 PartEVT =
411 EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
412 ValueVT.getVectorElementCount());
413 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
414 DAG.getVectorIdxConstant(0, DL));
415 if (PartEVT == ValueVT)
416 return Val;
417 if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
418 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419 }
420
421 // Promoted vector extract
422 return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
423 }
424
425 // Trivial bitcast if the types are the same size and the destination
426 // vector type is legal.
427 if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
428 TLI.isTypeLegal(ValueVT))
429 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
430
431 if (ValueVT.getVectorNumElements() != 1) {
432 // Certain ABIs require that vectors are passed as integers. For vectors
433 // are the same size, this is an obvious bitcast.
434 if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
435 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
436 } else if (ValueVT.bitsLT(PartEVT)) {
437 const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
438 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
439 // Drop the extra bits.
440 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
441 return DAG.getBitcast(ValueVT, Val);
442 }
443
444 diagnosePossiblyInvalidConstraint(
445 *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
446 return DAG.getUNDEF(ValueVT);
447 }
448
449 // Handle cases such as i8 -> <1 x i1>
450 EVT ValueSVT = ValueVT.getVectorElementType();
451 if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
452 unsigned ValueSize = ValueSVT.getSizeInBits();
453 if (ValueSize == PartEVT.getSizeInBits()) {
454 Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
455 } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
456 // It's possible a scalar floating point type gets softened to integer and
457 // then promoted to a larger integer. If PartEVT is the larger integer
458 // we need to truncate it and then bitcast to the FP type.
459 assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
460 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
461 Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
462 Val = DAG.getBitcast(ValueSVT, Val);
463 } else {
464 Val = ValueVT.isFloatingPoint()
465 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
466 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
467 }
468 }
469
470 return DAG.getBuildVector(ValueVT, DL, Val);
471 }
472
473 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
474 SDValue Val, SDValue *Parts, unsigned NumParts,
475 MVT PartVT, const Value *V,
476 std::optional<CallingConv::ID> CallConv);
477
478 /// getCopyToParts - Create a series of nodes that contain the specified value
479 /// split into legal parts. If the parts contain more bits than Val, then, for
480 /// integers, ExtendKind can be used to specify how to generate the extra bits.
481 static void
getCopyToParts(SelectionDAG & DAG,const SDLoc & DL,SDValue Val,SDValue * Parts,unsigned NumParts,MVT PartVT,const Value * V,std::optional<CallingConv::ID> CallConv=std::nullopt,ISD::NodeType ExtendKind=ISD::ANY_EXTEND)482 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
483 unsigned NumParts, MVT PartVT, const Value *V,
484 std::optional<CallingConv::ID> CallConv = std::nullopt,
485 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
486 // Let the target split the parts if it wants to
487 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
488 if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
489 CallConv))
490 return;
491 EVT ValueVT = Val.getValueType();
492
493 // Handle the vector case separately.
494 if (ValueVT.isVector())
495 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
496 CallConv);
497
498 unsigned PartBits = PartVT.getSizeInBits();
499 unsigned OrigNumParts = NumParts;
500 assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
501 "Copying to an illegal type!");
502
503 if (NumParts == 0)
504 return;
505
506 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
507 EVT PartEVT = PartVT;
508 if (PartEVT == ValueVT) {
509 assert(NumParts == 1 && "No-op copy with multiple parts!");
510 Parts[0] = Val;
511 return;
512 }
513
514 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
515 // If the parts cover more bits than the value has, promote the value.
516 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
517 assert(NumParts == 1 && "Do not know what to promote to!");
518 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
519 } else {
520 if (ValueVT.isFloatingPoint()) {
521 // FP values need to be bitcast, then extended if they are being put
522 // into a larger container.
523 ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
524 Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
525 }
526 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
527 ValueVT.isInteger() &&
528 "Unknown mismatch!");
529 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
530 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
531 if (PartVT == MVT::x86mmx)
532 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
533 }
534 } else if (PartBits == ValueVT.getSizeInBits()) {
535 // Different types of the same size.
536 assert(NumParts == 1 && PartEVT != ValueVT);
537 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
538 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
539 // If the parts cover less bits than value has, truncate the value.
540 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
541 ValueVT.isInteger() &&
542 "Unknown mismatch!");
543 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
544 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
545 if (PartVT == MVT::x86mmx)
546 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
547 }
548
549 // The value may have changed - recompute ValueVT.
550 ValueVT = Val.getValueType();
551 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
552 "Failed to tile the value with PartVT!");
553
554 if (NumParts == 1) {
555 if (PartEVT != ValueVT) {
556 diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
557 "scalar-to-vector conversion failed");
558 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
559 }
560
561 Parts[0] = Val;
562 return;
563 }
564
565 // Expand the value into multiple parts.
566 if (NumParts & (NumParts - 1)) {
567 // The number of parts is not a power of 2. Split off and copy the tail.
568 assert(PartVT.isInteger() && ValueVT.isInteger() &&
569 "Do not know what to expand to!");
570 unsigned RoundParts = llvm::bit_floor(NumParts);
571 unsigned RoundBits = RoundParts * PartBits;
572 unsigned OddParts = NumParts - RoundParts;
573 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
574 DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
575
576 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
577 CallConv);
578
579 if (DAG.getDataLayout().isBigEndian())
580 // The odd parts were reversed by getCopyToParts - unreverse them.
581 std::reverse(Parts + RoundParts, Parts + NumParts);
582
583 NumParts = RoundParts;
584 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
585 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
586 }
587
588 // The number of parts is a power of 2. Repeatedly bisect the value using
589 // EXTRACT_ELEMENT.
590 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
591 EVT::getIntegerVT(*DAG.getContext(),
592 ValueVT.getSizeInBits()),
593 Val);
594
595 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
596 for (unsigned i = 0; i < NumParts; i += StepSize) {
597 unsigned ThisBits = StepSize * PartBits / 2;
598 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
599 SDValue &Part0 = Parts[i];
600 SDValue &Part1 = Parts[i+StepSize/2];
601
602 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
603 ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
604 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
605 ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
606
607 if (ThisBits == PartBits && ThisVT != PartVT) {
608 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
609 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
610 }
611 }
612 }
613
614 if (DAG.getDataLayout().isBigEndian())
615 std::reverse(Parts, Parts + OrigNumParts);
616 }
617
widenVectorToPartType(SelectionDAG & DAG,SDValue Val,const SDLoc & DL,EVT PartVT)618 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
619 const SDLoc &DL, EVT PartVT) {
620 if (!PartVT.isVector())
621 return SDValue();
622
623 EVT ValueVT = Val.getValueType();
624 ElementCount PartNumElts = PartVT.getVectorElementCount();
625 ElementCount ValueNumElts = ValueVT.getVectorElementCount();
626
627 // We only support widening vectors with equivalent element types and
628 // fixed/scalable properties. If a target needs to widen a fixed-length type
629 // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
630 if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
631 PartNumElts.isScalable() != ValueNumElts.isScalable() ||
632 PartVT.getVectorElementType() != ValueVT.getVectorElementType())
633 return SDValue();
634
635 // Widening a scalable vector to another scalable vector is done by inserting
636 // the vector into a larger undef one.
637 if (PartNumElts.isScalable())
638 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
639 Val, DAG.getVectorIdxConstant(0, DL));
640
641 EVT ElementVT = PartVT.getVectorElementType();
642 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
643 // undef elements.
644 SmallVector<SDValue, 16> Ops;
645 DAG.ExtractVectorElements(Val, Ops);
646 SDValue EltUndef = DAG.getUNDEF(ElementVT);
647 Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
648
649 // FIXME: Use CONCAT for 2x -> 4x.
650 return DAG.getBuildVector(PartVT, DL, Ops);
651 }
652
653 /// getCopyToPartsVector - Create a series of nodes that contain the specified
654 /// value split into legal parts.
getCopyToPartsVector(SelectionDAG & DAG,const SDLoc & DL,SDValue Val,SDValue * Parts,unsigned NumParts,MVT PartVT,const Value * V,std::optional<CallingConv::ID> CallConv)655 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
656 SDValue Val, SDValue *Parts, unsigned NumParts,
657 MVT PartVT, const Value *V,
658 std::optional<CallingConv::ID> CallConv) {
659 EVT ValueVT = Val.getValueType();
660 assert(ValueVT.isVector() && "Not a vector");
661 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
662 const bool IsABIRegCopy = CallConv.has_value();
663
664 if (NumParts == 1) {
665 EVT PartEVT = PartVT;
666 if (PartEVT == ValueVT) {
667 // Nothing to do.
668 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
669 // Bitconvert vector->vector case.
670 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
671 } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
672 Val = Widened;
673 } else if (PartVT.isVector() &&
674 PartEVT.getVectorElementType().bitsGE(
675 ValueVT.getVectorElementType()) &&
676 PartEVT.getVectorElementCount() ==
677 ValueVT.getVectorElementCount()) {
678
679 // Promoted vector extract
680 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
681 } else if (PartEVT.isVector() &&
682 PartEVT.getVectorElementType() !=
683 ValueVT.getVectorElementType() &&
684 TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
685 TargetLowering::TypeWidenVector) {
686 // Combination of widening and promotion.
687 EVT WidenVT =
688 EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
689 PartVT.getVectorElementCount());
690 SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
691 Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
692 } else {
693 // Don't extract an integer from a float vector. This can happen if the
694 // FP type gets softened to integer and then promoted. The promotion
695 // prevents it from being picked up by the earlier bitcast case.
696 if (ValueVT.getVectorElementCount().isScalar() &&
697 (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
698 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
699 DAG.getVectorIdxConstant(0, DL));
700 } else {
701 uint64_t ValueSize = ValueVT.getFixedSizeInBits();
702 assert(PartVT.getFixedSizeInBits() > ValueSize &&
703 "lossy conversion of vector to scalar type");
704 EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
705 Val = DAG.getBitcast(IntermediateType, Val);
706 Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
707 }
708 }
709
710 assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
711 Parts[0] = Val;
712 return;
713 }
714
715 // Handle a multi-element vector.
716 EVT IntermediateVT;
717 MVT RegisterVT;
718 unsigned NumIntermediates;
719 unsigned NumRegs;
720 if (IsABIRegCopy) {
721 NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
722 *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
723 RegisterVT);
724 } else {
725 NumRegs =
726 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
727 NumIntermediates, RegisterVT);
728 }
729
730 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
731 NumParts = NumRegs; // Silence a compiler warning.
732 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
733
734 assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
735 "Mixing scalable and fixed vectors when copying in parts");
736
737 std::optional<ElementCount> DestEltCnt;
738
739 if (IntermediateVT.isVector())
740 DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
741 else
742 DestEltCnt = ElementCount::getFixed(NumIntermediates);
743
744 EVT BuiltVectorTy = EVT::getVectorVT(
745 *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
746
747 if (ValueVT == BuiltVectorTy) {
748 // Nothing to do.
749 } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
750 // Bitconvert vector->vector case.
751 Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
752 } else {
753 if (BuiltVectorTy.getVectorElementType().bitsGT(
754 ValueVT.getVectorElementType())) {
755 // Integer promotion.
756 ValueVT = EVT::getVectorVT(*DAG.getContext(),
757 BuiltVectorTy.getVectorElementType(),
758 ValueVT.getVectorElementCount());
759 Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
760 }
761
762 if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
763 Val = Widened;
764 }
765 }
766
767 assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
768
769 // Split the vector into intermediate operands.
770 SmallVector<SDValue, 8> Ops(NumIntermediates);
771 for (unsigned i = 0; i != NumIntermediates; ++i) {
772 if (IntermediateVT.isVector()) {
773 // This does something sensible for scalable vectors - see the
774 // definition of EXTRACT_SUBVECTOR for further details.
775 unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
776 Ops[i] =
777 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
778 DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
779 } else {
780 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
781 DAG.getVectorIdxConstant(i, DL));
782 }
783 }
784
785 // Split the intermediate operands into legal parts.
786 if (NumParts == NumIntermediates) {
787 // If the register was not expanded, promote or copy the value,
788 // as appropriate.
789 for (unsigned i = 0; i != NumParts; ++i)
790 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
791 } else if (NumParts > 0) {
792 // If the intermediate type was expanded, split each the value into
793 // legal parts.
794 assert(NumIntermediates != 0 && "division by zero");
795 assert(NumParts % NumIntermediates == 0 &&
796 "Must expand into a divisible number of parts!");
797 unsigned Factor = NumParts / NumIntermediates;
798 for (unsigned i = 0; i != NumIntermediates; ++i)
799 getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
800 CallConv);
801 }
802 }
803
RegsForValue(const SmallVector<unsigned,4> & regs,MVT regvt,EVT valuevt,std::optional<CallingConv::ID> CC)804 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt,
805 EVT valuevt, std::optional<CallingConv::ID> CC)
806 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
807 RegCount(1, regs.size()), CallConv(CC) {}
808
RegsForValue(LLVMContext & Context,const TargetLowering & TLI,const DataLayout & DL,unsigned Reg,Type * Ty,std::optional<CallingConv::ID> CC)809 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
810 const DataLayout &DL, unsigned Reg, Type *Ty,
811 std::optional<CallingConv::ID> CC) {
812 ComputeValueVTs(TLI, DL, Ty, ValueVTs);
813
814 CallConv = CC;
815
816 for (EVT ValueVT : ValueVTs) {
817 unsigned NumRegs =
818 isABIMangled()
819 ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
820 : TLI.getNumRegisters(Context, ValueVT);
821 MVT RegisterVT =
822 isABIMangled()
823 ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
824 : TLI.getRegisterType(Context, ValueVT);
825 for (unsigned i = 0; i != NumRegs; ++i)
826 Regs.push_back(Reg + i);
827 RegVTs.push_back(RegisterVT);
828 RegCount.push_back(NumRegs);
829 Reg += NumRegs;
830 }
831 }
832
getCopyFromRegs(SelectionDAG & DAG,FunctionLoweringInfo & FuncInfo,const SDLoc & dl,SDValue & Chain,SDValue * Flag,const Value * V) const833 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
834 FunctionLoweringInfo &FuncInfo,
835 const SDLoc &dl, SDValue &Chain,
836 SDValue *Flag, const Value *V) const {
837 // A Value with type {} or [0 x %t] needs no registers.
838 if (ValueVTs.empty())
839 return SDValue();
840
841 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
842
843 // Assemble the legal parts into the final values.
844 SmallVector<SDValue, 4> Values(ValueVTs.size());
845 SmallVector<SDValue, 8> Parts;
846 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
847 // Copy the legal parts from the registers.
848 EVT ValueVT = ValueVTs[Value];
849 unsigned NumRegs = RegCount[Value];
850 MVT RegisterVT = isABIMangled()
851 ? TLI.getRegisterTypeForCallingConv(
852 *DAG.getContext(), *CallConv, RegVTs[Value])
853 : RegVTs[Value];
854
855 Parts.resize(NumRegs);
856 for (unsigned i = 0; i != NumRegs; ++i) {
857 SDValue P;
858 if (!Flag) {
859 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
860 } else {
861 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
862 *Flag = P.getValue(2);
863 }
864
865 Chain = P.getValue(1);
866 Parts[i] = P;
867
868 // If the source register was virtual and if we know something about it,
869 // add an assert node.
870 if (!Register::isVirtualRegister(Regs[Part + i]) ||
871 !RegisterVT.isInteger())
872 continue;
873
874 const FunctionLoweringInfo::LiveOutInfo *LOI =
875 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
876 if (!LOI)
877 continue;
878
879 unsigned RegSize = RegisterVT.getScalarSizeInBits();
880 unsigned NumSignBits = LOI->NumSignBits;
881 unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
882
883 if (NumZeroBits == RegSize) {
884 // The current value is a zero.
885 // Explicitly express that as it would be easier for
886 // optimizations to kick in.
887 Parts[i] = DAG.getConstant(0, dl, RegisterVT);
888 continue;
889 }
890
891 // FIXME: We capture more information than the dag can represent. For
892 // now, just use the tightest assertzext/assertsext possible.
893 bool isSExt;
894 EVT FromVT(MVT::Other);
895 if (NumZeroBits) {
896 FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
897 isSExt = false;
898 } else if (NumSignBits > 1) {
899 FromVT =
900 EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
901 isSExt = true;
902 } else {
903 continue;
904 }
905 // Add an assertion node.
906 assert(FromVT != MVT::Other);
907 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
908 RegisterVT, P, DAG.getValueType(FromVT));
909 }
910
911 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
912 RegisterVT, ValueVT, V, CallConv);
913 Part += NumRegs;
914 Parts.clear();
915 }
916
917 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
918 }
919
getCopyToRegs(SDValue Val,SelectionDAG & DAG,const SDLoc & dl,SDValue & Chain,SDValue * Flag,const Value * V,ISD::NodeType PreferredExtendType) const920 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
921 const SDLoc &dl, SDValue &Chain, SDValue *Flag,
922 const Value *V,
923 ISD::NodeType PreferredExtendType) const {
924 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
925 ISD::NodeType ExtendKind = PreferredExtendType;
926
927 // Get the list of the values's legal parts.
928 unsigned NumRegs = Regs.size();
929 SmallVector<SDValue, 8> Parts(NumRegs);
930 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
931 unsigned NumParts = RegCount[Value];
932
933 MVT RegisterVT = isABIMangled()
934 ? TLI.getRegisterTypeForCallingConv(
935 *DAG.getContext(), *CallConv, RegVTs[Value])
936 : RegVTs[Value];
937
938 if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
939 ExtendKind = ISD::ZERO_EXTEND;
940
941 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
942 NumParts, RegisterVT, V, CallConv, ExtendKind);
943 Part += NumParts;
944 }
945
946 // Copy the parts into the registers.
947 SmallVector<SDValue, 8> Chains(NumRegs);
948 for (unsigned i = 0; i != NumRegs; ++i) {
949 SDValue Part;
950 if (!Flag) {
951 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
952 } else {
953 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
954 *Flag = Part.getValue(1);
955 }
956
957 Chains[i] = Part.getValue(0);
958 }
959
960 if (NumRegs == 1 || Flag)
961 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
962 // flagged to it. That is the CopyToReg nodes and the user are considered
963 // a single scheduling unit. If we create a TokenFactor and return it as
964 // chain, then the TokenFactor is both a predecessor (operand) of the
965 // user as well as a successor (the TF operands are flagged to the user).
966 // c1, f1 = CopyToReg
967 // c2, f2 = CopyToReg
968 // c3 = TokenFactor c1, c2
969 // ...
970 // = op c3, ..., f2
971 Chain = Chains[NumRegs-1];
972 else
973 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
974 }
975
AddInlineAsmOperands(unsigned Code,bool HasMatching,unsigned MatchingIdx,const SDLoc & dl,SelectionDAG & DAG,std::vector<SDValue> & Ops) const976 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
977 unsigned MatchingIdx, const SDLoc &dl,
978 SelectionDAG &DAG,
979 std::vector<SDValue> &Ops) const {
980 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
981
982 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
983 if (HasMatching)
984 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
985 else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
986 // Put the register class of the virtual registers in the flag word. That
987 // way, later passes can recompute register class constraints for inline
988 // assembly as well as normal instructions.
989 // Don't do this for tied operands that can use the regclass information
990 // from the def.
991 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
992 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
993 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
994 }
995
996 SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
997 Ops.push_back(Res);
998
999 if (Code == InlineAsm::Kind_Clobber) {
1000 // Clobbers should always have a 1:1 mapping with registers, and may
1001 // reference registers that have illegal (e.g. vector) types. Hence, we
1002 // shouldn't try to apply any sort of splitting logic to them.
1003 assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1004 "No 1:1 mapping from clobbers to regs?");
1005 Register SP = TLI.getStackPointerRegisterToSaveRestore();
1006 (void)SP;
1007 for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1008 Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1009 assert(
1010 (Regs[I] != SP ||
1011 DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1012 "If we clobbered the stack pointer, MFI should know about it.");
1013 }
1014 return;
1015 }
1016
1017 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1018 MVT RegisterVT = RegVTs[Value];
1019 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1020 RegisterVT);
1021 for (unsigned i = 0; i != NumRegs; ++i) {
1022 assert(Reg < Regs.size() && "Mismatch in # registers expected");
1023 unsigned TheReg = Regs[Reg++];
1024 Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1025 }
1026 }
1027 }
1028
1029 SmallVector<std::pair<unsigned, TypeSize>, 4>
getRegsAndSizes() const1030 RegsForValue::getRegsAndSizes() const {
1031 SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1032 unsigned I = 0;
1033 for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1034 unsigned RegCount = std::get<0>(CountAndVT);
1035 MVT RegisterVT = std::get<1>(CountAndVT);
1036 TypeSize RegisterSize = RegisterVT.getSizeInBits();
1037 for (unsigned E = I + RegCount; I != E; ++I)
1038 OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1039 }
1040 return OutVec;
1041 }
1042
init(GCFunctionInfo * gfi,AliasAnalysis * aa,AssumptionCache * ac,const TargetLibraryInfo * li)1043 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1044 AssumptionCache *ac,
1045 const TargetLibraryInfo *li) {
1046 AA = aa;
1047 AC = ac;
1048 GFI = gfi;
1049 LibInfo = li;
1050 Context = DAG.getContext();
1051 LPadToCallSiteMap.clear();
1052 SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1053 }
1054
clear()1055 void SelectionDAGBuilder::clear() {
1056 NodeMap.clear();
1057 UnusedArgNodeMap.clear();
1058 PendingLoads.clear();
1059 PendingExports.clear();
1060 PendingConstrainedFP.clear();
1061 PendingConstrainedFPStrict.clear();
1062 CurInst = nullptr;
1063 HasTailCall = false;
1064 SDNodeOrder = LowestSDNodeOrder;
1065 StatepointLowering.clear();
1066 }
1067
clearDanglingDebugInfo()1068 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1069 DanglingDebugInfoMap.clear();
1070 }
1071
1072 // Update DAG root to include dependencies on Pending chains.
updateRoot(SmallVectorImpl<SDValue> & Pending)1073 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1074 SDValue Root = DAG.getRoot();
1075
1076 if (Pending.empty())
1077 return Root;
1078
1079 // Add current root to PendingChains, unless we already indirectly
1080 // depend on it.
1081 if (Root.getOpcode() != ISD::EntryToken) {
1082 unsigned i = 0, e = Pending.size();
1083 for (; i != e; ++i) {
1084 assert(Pending[i].getNode()->getNumOperands() > 1);
1085 if (Pending[i].getNode()->getOperand(0) == Root)
1086 break; // Don't add the root if we already indirectly depend on it.
1087 }
1088
1089 if (i == e)
1090 Pending.push_back(Root);
1091 }
1092
1093 if (Pending.size() == 1)
1094 Root = Pending[0];
1095 else
1096 Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1097
1098 DAG.setRoot(Root);
1099 Pending.clear();
1100 return Root;
1101 }
1102
getMemoryRoot()1103 SDValue SelectionDAGBuilder::getMemoryRoot() {
1104 return updateRoot(PendingLoads);
1105 }
1106
getRoot()1107 SDValue SelectionDAGBuilder::getRoot() {
1108 // Chain up all pending constrained intrinsics together with all
1109 // pending loads, by simply appending them to PendingLoads and
1110 // then calling getMemoryRoot().
1111 PendingLoads.reserve(PendingLoads.size() +
1112 PendingConstrainedFP.size() +
1113 PendingConstrainedFPStrict.size());
1114 PendingLoads.append(PendingConstrainedFP.begin(),
1115 PendingConstrainedFP.end());
1116 PendingLoads.append(PendingConstrainedFPStrict.begin(),
1117 PendingConstrainedFPStrict.end());
1118 PendingConstrainedFP.clear();
1119 PendingConstrainedFPStrict.clear();
1120 return getMemoryRoot();
1121 }
1122
getControlRoot()1123 SDValue SelectionDAGBuilder::getControlRoot() {
1124 // We need to emit pending fpexcept.strict constrained intrinsics,
1125 // so append them to the PendingExports list.
1126 PendingExports.append(PendingConstrainedFPStrict.begin(),
1127 PendingConstrainedFPStrict.end());
1128 PendingConstrainedFPStrict.clear();
1129 return updateRoot(PendingExports);
1130 }
1131
visit(const Instruction & I)1132 void SelectionDAGBuilder::visit(const Instruction &I) {
1133 // Set up outgoing PHI node register values before emitting the terminator.
1134 if (I.isTerminator()) {
1135 HandlePHINodesInSuccessorBlocks(I.getParent());
1136 }
1137
1138 // Add SDDbgValue nodes for any var locs here. Do so before updating
1139 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1140 if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1141 // Add SDDbgValue nodes for any var locs here. Do so before updating
1142 // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1143 for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1144 It != End; ++It) {
1145 auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1146 dropDanglingDebugInfo(Var, It->Expr);
1147 if (!handleDebugValue(It->V, Var, It->Expr, It->DL, SDNodeOrder,
1148 /*IsVariadic=*/false))
1149 addDanglingDebugInfo(It, SDNodeOrder);
1150 }
1151 }
1152
1153 // Increase the SDNodeOrder if dealing with a non-debug instruction.
1154 if (!isa<DbgInfoIntrinsic>(I))
1155 ++SDNodeOrder;
1156
1157 CurInst = &I;
1158
1159 // Set inserted listener only if required.
1160 bool NodeInserted = false;
1161 std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1162 MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1163 if (PCSectionsMD) {
1164 InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1165 DAG, [&](SDNode *) { NodeInserted = true; });
1166 }
1167
1168 visit(I.getOpcode(), I);
1169
1170 if (!I.isTerminator() && !HasTailCall &&
1171 !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1172 CopyToExportRegsIfNeeded(&I);
1173
1174 // Handle metadata.
1175 if (PCSectionsMD) {
1176 auto It = NodeMap.find(&I);
1177 if (It != NodeMap.end()) {
1178 DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1179 } else if (NodeInserted) {
1180 // This should not happen; if it does, don't let it go unnoticed so we can
1181 // fix it. Relevant visit*() function is probably missing a setValue().
1182 errs() << "warning: loosing !pcsections metadata ["
1183 << I.getModule()->getName() << "]\n";
1184 LLVM_DEBUG(I.dump());
1185 assert(false);
1186 }
1187 }
1188
1189 CurInst = nullptr;
1190 }
1191
visitPHI(const PHINode &)1192 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1193 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1194 }
1195
visit(unsigned Opcode,const User & I)1196 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1197 // Note: this doesn't use InstVisitor, because it has to work with
1198 // ConstantExpr's in addition to instructions.
1199 switch (Opcode) {
1200 default: llvm_unreachable("Unknown instruction type encountered!");
1201 // Build the switch statement using the Instruction.def file.
1202 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1203 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1204 #include "llvm/IR/Instruction.def"
1205 }
1206 }
1207
addDanglingDebugInfo(const VarLocInfo * VarLoc,unsigned Order)1208 void SelectionDAGBuilder::addDanglingDebugInfo(const VarLocInfo *VarLoc,
1209 unsigned Order) {
1210 DanglingDebugInfoMap[VarLoc->V].emplace_back(VarLoc, Order);
1211 }
1212
addDanglingDebugInfo(const DbgValueInst * DI,unsigned Order)1213 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1214 unsigned Order) {
1215 // We treat variadic dbg_values differently at this stage.
1216 if (DI->hasArgList()) {
1217 // For variadic dbg_values we will now insert an undef.
1218 // FIXME: We can potentially recover these!
1219 SmallVector<SDDbgOperand, 2> Locs;
1220 for (const Value *V : DI->getValues()) {
1221 auto Undef = UndefValue::get(V->getType());
1222 Locs.push_back(SDDbgOperand::fromConst(Undef));
1223 }
1224 SDDbgValue *SDV = DAG.getDbgValueList(
1225 DI->getVariable(), DI->getExpression(), Locs, {},
1226 /*IsIndirect=*/false, DI->getDebugLoc(), Order, /*IsVariadic=*/true);
1227 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1228 } else {
1229 // TODO: Dangling debug info will eventually either be resolved or produce
1230 // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1231 // between the original dbg.value location and its resolved DBG_VALUE,
1232 // which we should ideally fill with an extra Undef DBG_VALUE.
1233 assert(DI->getNumVariableLocationOps() == 1 &&
1234 "DbgValueInst without an ArgList should have a single location "
1235 "operand.");
1236 DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, Order);
1237 }
1238 }
1239
dropDanglingDebugInfo(const DILocalVariable * Variable,const DIExpression * Expr)1240 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1241 const DIExpression *Expr) {
1242 auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1243 DIVariable *DanglingVariable = DDI.getVariable(DAG.getFunctionVarLocs());
1244 DIExpression *DanglingExpr = DDI.getExpression();
1245 if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1246 LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << printDDI(DDI)
1247 << "\n");
1248 return true;
1249 }
1250 return false;
1251 };
1252
1253 for (auto &DDIMI : DanglingDebugInfoMap) {
1254 DanglingDebugInfoVector &DDIV = DDIMI.second;
1255
1256 // If debug info is to be dropped, run it through final checks to see
1257 // whether it can be salvaged.
1258 for (auto &DDI : DDIV)
1259 if (isMatchingDbgValue(DDI))
1260 salvageUnresolvedDbgValue(DDI);
1261
1262 erase_if(DDIV, isMatchingDbgValue);
1263 }
1264 }
1265
1266 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1267 // generate the debug data structures now that we've seen its definition.
resolveDanglingDebugInfo(const Value * V,SDValue Val)1268 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1269 SDValue Val) {
1270 auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1271 if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1272 return;
1273
1274 DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1275 for (auto &DDI : DDIV) {
1276 DebugLoc DL = DDI.getDebugLoc();
1277 unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1278 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1279 DILocalVariable *Variable = DDI.getVariable(DAG.getFunctionVarLocs());
1280 DIExpression *Expr = DDI.getExpression();
1281 assert(Variable->isValidLocationForIntrinsic(DL) &&
1282 "Expected inlined-at fields to agree");
1283 SDDbgValue *SDV;
1284 if (Val.getNode()) {
1285 // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1286 // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1287 // we couldn't resolve it directly when examining the DbgValue intrinsic
1288 // in the first place we should not be more successful here). Unless we
1289 // have some test case that prove this to be correct we should avoid
1290 // calling EmitFuncArgumentDbgValue here.
1291 if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1292 FuncArgumentDbgValueKind::Value, Val)) {
1293 LLVM_DEBUG(dbgs() << "Resolve dangling debug info for " << printDDI(DDI)
1294 << "\n");
1295 LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
1296 // Increase the SDNodeOrder for the DbgValue here to make sure it is
1297 // inserted after the definition of Val when emitting the instructions
1298 // after ISel. An alternative could be to teach
1299 // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1300 LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1301 << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1302 << ValSDNodeOrder << "\n");
1303 SDV = getDbgValue(Val, Variable, Expr, DL,
1304 std::max(DbgSDNodeOrder, ValSDNodeOrder));
1305 DAG.AddDbgValue(SDV, false);
1306 } else
1307 LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1308 << printDDI(DDI) << " in EmitFuncArgumentDbgValue\n");
1309 } else {
1310 LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(DDI) << "\n");
1311 auto Undef = UndefValue::get(V->getType());
1312 auto SDV =
1313 DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1314 DAG.AddDbgValue(SDV, false);
1315 }
1316 }
1317 DDIV.clear();
1318 }
1319
salvageUnresolvedDbgValue(DanglingDebugInfo & DDI)1320 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1321 // TODO: For the variadic implementation, instead of only checking the fail
1322 // state of `handleDebugValue`, we need know specifically which values were
1323 // invalid, so that we attempt to salvage only those values when processing
1324 // a DIArgList.
1325 Value *V = DDI.getVariableLocationOp(0);
1326 Value *OrigV = V;
1327 DILocalVariable *Var = DDI.getVariable(DAG.getFunctionVarLocs());
1328 DIExpression *Expr = DDI.getExpression();
1329 DebugLoc DL = DDI.getDebugLoc();
1330 unsigned SDOrder = DDI.getSDNodeOrder();
1331
1332 // Currently we consider only dbg.value intrinsics -- we tell the salvager
1333 // that DW_OP_stack_value is desired.
1334 bool StackValue = true;
1335
1336 // Can this Value can be encoded without any further work?
1337 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1338 return;
1339
1340 // Attempt to salvage back through as many instructions as possible. Bail if
1341 // a non-instruction is seen, such as a constant expression or global
1342 // variable. FIXME: Further work could recover those too.
1343 while (isa<Instruction>(V)) {
1344 Instruction &VAsInst = *cast<Instruction>(V);
1345 // Temporary "0", awaiting real implementation.
1346 SmallVector<uint64_t, 16> Ops;
1347 SmallVector<Value *, 4> AdditionalValues;
1348 V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1349 AdditionalValues);
1350 // If we cannot salvage any further, and haven't yet found a suitable debug
1351 // expression, bail out.
1352 if (!V)
1353 break;
1354
1355 // TODO: If AdditionalValues isn't empty, then the salvage can only be
1356 // represented with a DBG_VALUE_LIST, so we give up. When we have support
1357 // here for variadic dbg_values, remove that condition.
1358 if (!AdditionalValues.empty())
1359 break;
1360
1361 // New value and expr now represent this debuginfo.
1362 Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1363
1364 // Some kind of simplification occurred: check whether the operand of the
1365 // salvaged debug expression can be encoded in this DAG.
1366 if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1367 LLVM_DEBUG(
1368 dbgs() << "Salvaged debug location info for:\n " << *Var << "\n"
1369 << *OrigV << "\nBy stripping back to:\n " << *V << "\n");
1370 return;
1371 }
1372 }
1373
1374 // This was the final opportunity to salvage this debug information, and it
1375 // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1376 // any earlier variable location.
1377 assert(OrigV && "V shouldn't be null");
1378 auto *Undef = UndefValue::get(OrigV->getType());
1379 auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1380 DAG.AddDbgValue(SDV, false);
1381 LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << printDDI(DDI)
1382 << "\n");
1383 }
1384
handleDebugValue(ArrayRef<const Value * > Values,DILocalVariable * Var,DIExpression * Expr,DebugLoc DbgLoc,unsigned Order,bool IsVariadic)1385 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1386 DILocalVariable *Var,
1387 DIExpression *Expr, DebugLoc DbgLoc,
1388 unsigned Order, bool IsVariadic) {
1389 if (Values.empty())
1390 return true;
1391 SmallVector<SDDbgOperand> LocationOps;
1392 SmallVector<SDNode *> Dependencies;
1393 for (const Value *V : Values) {
1394 // Constant value.
1395 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1396 isa<ConstantPointerNull>(V)) {
1397 LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1398 continue;
1399 }
1400
1401 // Look through IntToPtr constants.
1402 if (auto *CE = dyn_cast<ConstantExpr>(V))
1403 if (CE->getOpcode() == Instruction::IntToPtr) {
1404 LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1405 continue;
1406 }
1407
1408 // If the Value is a frame index, we can create a FrameIndex debug value
1409 // without relying on the DAG at all.
1410 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1411 auto SI = FuncInfo.StaticAllocaMap.find(AI);
1412 if (SI != FuncInfo.StaticAllocaMap.end()) {
1413 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1414 continue;
1415 }
1416 }
1417
1418 // Do not use getValue() in here; we don't want to generate code at
1419 // this point if it hasn't been done yet.
1420 SDValue N = NodeMap[V];
1421 if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1422 N = UnusedArgNodeMap[V];
1423 if (N.getNode()) {
1424 // Only emit func arg dbg value for non-variadic dbg.values for now.
1425 if (!IsVariadic &&
1426 EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1427 FuncArgumentDbgValueKind::Value, N))
1428 return true;
1429 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1430 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1431 // describe stack slot locations.
1432 //
1433 // Consider "int x = 0; int *px = &x;". There are two kinds of
1434 // interesting debug values here after optimization:
1435 //
1436 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
1437 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1438 //
1439 // Both describe the direct values of their associated variables.
1440 Dependencies.push_back(N.getNode());
1441 LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1442 continue;
1443 }
1444 LocationOps.emplace_back(
1445 SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1446 continue;
1447 }
1448
1449 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1450 // Special rules apply for the first dbg.values of parameter variables in a
1451 // function. Identify them by the fact they reference Argument Values, that
1452 // they're parameters, and they are parameters of the current function. We
1453 // need to let them dangle until they get an SDNode.
1454 bool IsParamOfFunc =
1455 isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1456 if (IsParamOfFunc)
1457 return false;
1458
1459 // The value is not used in this block yet (or it would have an SDNode).
1460 // We still want the value to appear for the user if possible -- if it has
1461 // an associated VReg, we can refer to that instead.
1462 auto VMI = FuncInfo.ValueMap.find(V);
1463 if (VMI != FuncInfo.ValueMap.end()) {
1464 unsigned Reg = VMI->second;
1465 // If this is a PHI node, it may be split up into several MI PHI nodes
1466 // (in FunctionLoweringInfo::set).
1467 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1468 V->getType(), std::nullopt);
1469 if (RFV.occupiesMultipleRegs()) {
1470 // FIXME: We could potentially support variadic dbg_values here.
1471 if (IsVariadic)
1472 return false;
1473 unsigned Offset = 0;
1474 unsigned BitsToDescribe = 0;
1475 if (auto VarSize = Var->getSizeInBits())
1476 BitsToDescribe = *VarSize;
1477 if (auto Fragment = Expr->getFragmentInfo())
1478 BitsToDescribe = Fragment->SizeInBits;
1479 for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1480 // Bail out if all bits are described already.
1481 if (Offset >= BitsToDescribe)
1482 break;
1483 // TODO: handle scalable vectors.
1484 unsigned RegisterSize = RegAndSize.second;
1485 unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1486 ? BitsToDescribe - Offset
1487 : RegisterSize;
1488 auto FragmentExpr = DIExpression::createFragmentExpression(
1489 Expr, Offset, FragmentSize);
1490 if (!FragmentExpr)
1491 continue;
1492 SDDbgValue *SDV = DAG.getVRegDbgValue(
1493 Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1494 DAG.AddDbgValue(SDV, false);
1495 Offset += RegisterSize;
1496 }
1497 return true;
1498 }
1499 // We can use simple vreg locations for variadic dbg_values as well.
1500 LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1501 continue;
1502 }
1503 // We failed to create a SDDbgOperand for V.
1504 return false;
1505 }
1506
1507 // We have created a SDDbgOperand for each Value in Values.
1508 // Should use Order instead of SDNodeOrder?
1509 assert(!LocationOps.empty());
1510 SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1511 /*IsIndirect=*/false, DbgLoc,
1512 SDNodeOrder, IsVariadic);
1513 DAG.AddDbgValue(SDV, /*isParameter=*/false);
1514 return true;
1515 }
1516
resolveOrClearDbgInfo()1517 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1518 // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1519 for (auto &Pair : DanglingDebugInfoMap)
1520 for (auto &DDI : Pair.second)
1521 salvageUnresolvedDbgValue(DDI);
1522 clearDanglingDebugInfo();
1523 }
1524
1525 /// getCopyFromRegs - If there was virtual register allocated for the value V
1526 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
getCopyFromRegs(const Value * V,Type * Ty)1527 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1528 DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1529 SDValue Result;
1530
1531 if (It != FuncInfo.ValueMap.end()) {
1532 Register InReg = It->second;
1533
1534 RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1535 DAG.getDataLayout(), InReg, Ty,
1536 std::nullopt); // This is not an ABI copy.
1537 SDValue Chain = DAG.getEntryNode();
1538 Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1539 V);
1540 resolveDanglingDebugInfo(V, Result);
1541 }
1542
1543 return Result;
1544 }
1545
1546 /// getValue - Return an SDValue for the given Value.
getValue(const Value * V)1547 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1548 // If we already have an SDValue for this value, use it. It's important
1549 // to do this first, so that we don't create a CopyFromReg if we already
1550 // have a regular SDValue.
1551 SDValue &N = NodeMap[V];
1552 if (N.getNode()) return N;
1553
1554 // If there's a virtual register allocated and initialized for this
1555 // value, use it.
1556 if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1557 return copyFromReg;
1558
1559 // Otherwise create a new SDValue and remember it.
1560 SDValue Val = getValueImpl(V);
1561 NodeMap[V] = Val;
1562 resolveDanglingDebugInfo(V, Val);
1563 return Val;
1564 }
1565
1566 /// getNonRegisterValue - Return an SDValue for the given Value, but
1567 /// don't look in FuncInfo.ValueMap for a virtual register.
getNonRegisterValue(const Value * V)1568 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1569 // If we already have an SDValue for this value, use it.
1570 SDValue &N = NodeMap[V];
1571 if (N.getNode()) {
1572 if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1573 // Remove the debug location from the node as the node is about to be used
1574 // in a location which may differ from the original debug location. This
1575 // is relevant to Constant and ConstantFP nodes because they can appear
1576 // as constant expressions inside PHI nodes.
1577 N->setDebugLoc(DebugLoc());
1578 }
1579 return N;
1580 }
1581
1582 // Otherwise create a new SDValue and remember it.
1583 SDValue Val = getValueImpl(V);
1584 NodeMap[V] = Val;
1585 resolveDanglingDebugInfo(V, Val);
1586 return Val;
1587 }
1588
1589 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1590 /// Create an SDValue for the given value.
getValueImpl(const Value * V)1591 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1592 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1593
1594 if (const Constant *C = dyn_cast<Constant>(V)) {
1595 EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1596
1597 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1598 return DAG.getConstant(*CI, getCurSDLoc(), VT);
1599
1600 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1601 return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1602
1603 if (isa<ConstantPointerNull>(C)) {
1604 unsigned AS = V->getType()->getPointerAddressSpace();
1605 return DAG.getConstant(0, getCurSDLoc(),
1606 TLI.getPointerTy(DAG.getDataLayout(), AS));
1607 }
1608
1609 if (match(C, m_VScale(DAG.getDataLayout())))
1610 return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1611
1612 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1613 return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1614
1615 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1616 return DAG.getUNDEF(VT);
1617
1618 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1619 visit(CE->getOpcode(), *CE);
1620 SDValue N1 = NodeMap[V];
1621 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1622 return N1;
1623 }
1624
1625 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1626 SmallVector<SDValue, 4> Constants;
1627 for (const Use &U : C->operands()) {
1628 SDNode *Val = getValue(U).getNode();
1629 // If the operand is an empty aggregate, there are no values.
1630 if (!Val) continue;
1631 // Add each leaf value from the operand to the Constants list
1632 // to form a flattened list of all the values.
1633 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1634 Constants.push_back(SDValue(Val, i));
1635 }
1636
1637 return DAG.getMergeValues(Constants, getCurSDLoc());
1638 }
1639
1640 if (const ConstantDataSequential *CDS =
1641 dyn_cast<ConstantDataSequential>(C)) {
1642 SmallVector<SDValue, 4> Ops;
1643 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1644 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1645 // Add each leaf value from the operand to the Constants list
1646 // to form a flattened list of all the values.
1647 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1648 Ops.push_back(SDValue(Val, i));
1649 }
1650
1651 if (isa<ArrayType>(CDS->getType()))
1652 return DAG.getMergeValues(Ops, getCurSDLoc());
1653 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1654 }
1655
1656 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1657 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1658 "Unknown struct or array constant!");
1659
1660 SmallVector<EVT, 4> ValueVTs;
1661 ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1662 unsigned NumElts = ValueVTs.size();
1663 if (NumElts == 0)
1664 return SDValue(); // empty struct
1665 SmallVector<SDValue, 4> Constants(NumElts);
1666 for (unsigned i = 0; i != NumElts; ++i) {
1667 EVT EltVT = ValueVTs[i];
1668 if (isa<UndefValue>(C))
1669 Constants[i] = DAG.getUNDEF(EltVT);
1670 else if (EltVT.isFloatingPoint())
1671 Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1672 else
1673 Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1674 }
1675
1676 return DAG.getMergeValues(Constants, getCurSDLoc());
1677 }
1678
1679 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1680 return DAG.getBlockAddress(BA, VT);
1681
1682 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1683 return getValue(Equiv->getGlobalValue());
1684
1685 if (const auto *NC = dyn_cast<NoCFIValue>(C))
1686 return getValue(NC->getGlobalValue());
1687
1688 VectorType *VecTy = cast<VectorType>(V->getType());
1689
1690 // Now that we know the number and type of the elements, get that number of
1691 // elements into the Ops array based on what kind of constant it is.
1692 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1693 SmallVector<SDValue, 16> Ops;
1694 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1695 for (unsigned i = 0; i != NumElements; ++i)
1696 Ops.push_back(getValue(CV->getOperand(i)));
1697
1698 return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1699 }
1700
1701 if (isa<ConstantAggregateZero>(C)) {
1702 EVT EltVT =
1703 TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1704
1705 SDValue Op;
1706 if (EltVT.isFloatingPoint())
1707 Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1708 else
1709 Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1710
1711 return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1712 }
1713
1714 llvm_unreachable("Unknown vector constant");
1715 }
1716
1717 // If this is a static alloca, generate it as the frameindex instead of
1718 // computation.
1719 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1720 DenseMap<const AllocaInst*, int>::iterator SI =
1721 FuncInfo.StaticAllocaMap.find(AI);
1722 if (SI != FuncInfo.StaticAllocaMap.end())
1723 return DAG.getFrameIndex(
1724 SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1725 }
1726
1727 // If this is an instruction which fast-isel has deferred, select it now.
1728 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1729 Register InReg = FuncInfo.InitializeRegForValue(Inst);
1730
1731 RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1732 Inst->getType(), std::nullopt);
1733 SDValue Chain = DAG.getEntryNode();
1734 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1735 }
1736
1737 if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1738 return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1739
1740 if (const auto *BB = dyn_cast<BasicBlock>(V))
1741 return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1742
1743 llvm_unreachable("Can't get register for value!");
1744 }
1745
visitCatchPad(const CatchPadInst & I)1746 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1747 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1748 bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1749 bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1750 bool IsSEH = isAsynchronousEHPersonality(Pers);
1751 MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1752 if (!IsSEH)
1753 CatchPadMBB->setIsEHScopeEntry();
1754 // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1755 if (IsMSVCCXX || IsCoreCLR)
1756 CatchPadMBB->setIsEHFuncletEntry();
1757 }
1758
visitCatchRet(const CatchReturnInst & I)1759 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1760 // Update machine-CFG edge.
1761 MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1762 FuncInfo.MBB->addSuccessor(TargetMBB);
1763 TargetMBB->setIsEHCatchretTarget(true);
1764 DAG.getMachineFunction().setHasEHCatchret(true);
1765
1766 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1767 bool IsSEH = isAsynchronousEHPersonality(Pers);
1768 if (IsSEH) {
1769 // If this is not a fall-through branch or optimizations are switched off,
1770 // emit the branch.
1771 if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1772 TM.getOptLevel() == CodeGenOpt::None)
1773 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1774 getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1775 return;
1776 }
1777
1778 // Figure out the funclet membership for the catchret's successor.
1779 // This will be used by the FuncletLayout pass to determine how to order the
1780 // BB's.
1781 // A 'catchret' returns to the outer scope's color.
1782 Value *ParentPad = I.getCatchSwitchParentPad();
1783 const BasicBlock *SuccessorColor;
1784 if (isa<ConstantTokenNone>(ParentPad))
1785 SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1786 else
1787 SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1788 assert(SuccessorColor && "No parent funclet for catchret!");
1789 MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1790 assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1791
1792 // Create the terminator node.
1793 SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1794 getControlRoot(), DAG.getBasicBlock(TargetMBB),
1795 DAG.getBasicBlock(SuccessorColorMBB));
1796 DAG.setRoot(Ret);
1797 }
1798
visitCleanupPad(const CleanupPadInst & CPI)1799 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1800 // Don't emit any special code for the cleanuppad instruction. It just marks
1801 // the start of an EH scope/funclet.
1802 FuncInfo.MBB->setIsEHScopeEntry();
1803 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1804 if (Pers != EHPersonality::Wasm_CXX) {
1805 FuncInfo.MBB->setIsEHFuncletEntry();
1806 FuncInfo.MBB->setIsCleanupFuncletEntry();
1807 }
1808 }
1809
1810 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1811 // not match, it is OK to add only the first unwind destination catchpad to the
1812 // successors, because there will be at least one invoke instruction within the
1813 // catch scope that points to the next unwind destination, if one exists, so
1814 // CFGSort cannot mess up with BB sorting order.
1815 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1816 // call within them, and catchpads only consisting of 'catch (...)' have a
1817 // '__cxa_end_catch' call within them, both of which generate invokes in case
1818 // the next unwind destination exists, i.e., the next unwind destination is not
1819 // the caller.)
1820 //
1821 // Having at most one EH pad successor is also simpler and helps later
1822 // transformations.
1823 //
1824 // For example,
1825 // current:
1826 // invoke void @foo to ... unwind label %catch.dispatch
1827 // catch.dispatch:
1828 // %0 = catchswitch within ... [label %catch.start] unwind label %next
1829 // catch.start:
1830 // ...
1831 // ... in this BB or some other child BB dominated by this BB there will be an
1832 // invoke that points to 'next' BB as an unwind destination
1833 //
1834 // next: ; We don't need to add this to 'current' BB's successor
1835 // ...
findWasmUnwindDestinations(FunctionLoweringInfo & FuncInfo,const BasicBlock * EHPadBB,BranchProbability Prob,SmallVectorImpl<std::pair<MachineBasicBlock *,BranchProbability>> & UnwindDests)1836 static void findWasmUnwindDestinations(
1837 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1838 BranchProbability Prob,
1839 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1840 &UnwindDests) {
1841 while (EHPadBB) {
1842 const Instruction *Pad = EHPadBB->getFirstNonPHI();
1843 if (isa<CleanupPadInst>(Pad)) {
1844 // Stop on cleanup pads.
1845 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1846 UnwindDests.back().first->setIsEHScopeEntry();
1847 break;
1848 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1849 // Add the catchpad handlers to the possible destinations. We don't
1850 // continue to the unwind destination of the catchswitch for wasm.
1851 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1852 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1853 UnwindDests.back().first->setIsEHScopeEntry();
1854 }
1855 break;
1856 } else {
1857 continue;
1858 }
1859 }
1860 }
1861
1862 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1863 /// many places it could ultimately go. In the IR, we have a single unwind
1864 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1865 /// This function skips over imaginary basic blocks that hold catchswitch
1866 /// instructions, and finds all the "real" machine
1867 /// basic block destinations. As those destinations may not be successors of
1868 /// EHPadBB, here we also calculate the edge probability to those destinations.
1869 /// The passed-in Prob is the edge probability to EHPadBB.
findUnwindDestinations(FunctionLoweringInfo & FuncInfo,const BasicBlock * EHPadBB,BranchProbability Prob,SmallVectorImpl<std::pair<MachineBasicBlock *,BranchProbability>> & UnwindDests)1870 static void findUnwindDestinations(
1871 FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1872 BranchProbability Prob,
1873 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1874 &UnwindDests) {
1875 EHPersonality Personality =
1876 classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1877 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1878 bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1879 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1880 bool IsSEH = isAsynchronousEHPersonality(Personality);
1881
1882 if (IsWasmCXX) {
1883 findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1884 assert(UnwindDests.size() <= 1 &&
1885 "There should be at most one unwind destination for wasm");
1886 return;
1887 }
1888
1889 while (EHPadBB) {
1890 const Instruction *Pad = EHPadBB->getFirstNonPHI();
1891 BasicBlock *NewEHPadBB = nullptr;
1892 if (isa<LandingPadInst>(Pad)) {
1893 // Stop on landingpads. They are not funclets.
1894 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1895 break;
1896 } else if (isa<CleanupPadInst>(Pad)) {
1897 // Stop on cleanup pads. Cleanups are always funclet entries for all known
1898 // personalities.
1899 UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1900 UnwindDests.back().first->setIsEHScopeEntry();
1901 UnwindDests.back().first->setIsEHFuncletEntry();
1902 break;
1903 } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1904 // Add the catchpad handlers to the possible destinations.
1905 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1906 UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1907 // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1908 if (IsMSVCCXX || IsCoreCLR)
1909 UnwindDests.back().first->setIsEHFuncletEntry();
1910 if (!IsSEH)
1911 UnwindDests.back().first->setIsEHScopeEntry();
1912 }
1913 NewEHPadBB = CatchSwitch->getUnwindDest();
1914 } else {
1915 continue;
1916 }
1917
1918 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1919 if (BPI && NewEHPadBB)
1920 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1921 EHPadBB = NewEHPadBB;
1922 }
1923 }
1924
visitCleanupRet(const CleanupReturnInst & I)1925 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1926 // Update successor info.
1927 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1928 auto UnwindDest = I.getUnwindDest();
1929 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1930 BranchProbability UnwindDestProb =
1931 (BPI && UnwindDest)
1932 ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1933 : BranchProbability::getZero();
1934 findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1935 for (auto &UnwindDest : UnwindDests) {
1936 UnwindDest.first->setIsEHPad();
1937 addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1938 }
1939 FuncInfo.MBB->normalizeSuccProbs();
1940
1941 // Create the terminator node.
1942 SDValue Ret =
1943 DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1944 DAG.setRoot(Ret);
1945 }
1946
visitCatchSwitch(const CatchSwitchInst & CSI)1947 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1948 report_fatal_error("visitCatchSwitch not yet implemented!");
1949 }
1950
visitRet(const ReturnInst & I)1951 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1952 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1953 auto &DL = DAG.getDataLayout();
1954 SDValue Chain = getControlRoot();
1955 SmallVector<ISD::OutputArg, 8> Outs;
1956 SmallVector<SDValue, 8> OutVals;
1957
1958 // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1959 // lower
1960 //
1961 // %val = call <ty> @llvm.experimental.deoptimize()
1962 // ret <ty> %val
1963 //
1964 // differently.
1965 if (I.getParent()->getTerminatingDeoptimizeCall()) {
1966 LowerDeoptimizingReturn();
1967 return;
1968 }
1969
1970 if (!FuncInfo.CanLowerReturn) {
1971 unsigned DemoteReg = FuncInfo.DemoteRegister;
1972 const Function *F = I.getParent()->getParent();
1973
1974 // Emit a store of the return value through the virtual register.
1975 // Leave Outs empty so that LowerReturn won't try to load return
1976 // registers the usual way.
1977 SmallVector<EVT, 1> PtrValueVTs;
1978 ComputeValueVTs(TLI, DL,
1979 F->getReturnType()->getPointerTo(
1980 DAG.getDataLayout().getAllocaAddrSpace()),
1981 PtrValueVTs);
1982
1983 SDValue RetPtr =
1984 DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1985 SDValue RetOp = getValue(I.getOperand(0));
1986
1987 SmallVector<EVT, 4> ValueVTs, MemVTs;
1988 SmallVector<uint64_t, 4> Offsets;
1989 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1990 &Offsets);
1991 unsigned NumValues = ValueVTs.size();
1992
1993 SmallVector<SDValue, 4> Chains(NumValues);
1994 Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1995 for (unsigned i = 0; i != NumValues; ++i) {
1996 // An aggregate return value cannot wrap around the address space, so
1997 // offsets to its parts don't wrap either.
1998 SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1999 TypeSize::Fixed(Offsets[i]));
2000
2001 SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2002 if (MemVTs[i] != ValueVTs[i])
2003 Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2004 Chains[i] = DAG.getStore(
2005 Chain, getCurSDLoc(), Val,
2006 // FIXME: better loc info would be nice.
2007 Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2008 commonAlignment(BaseAlign, Offsets[i]));
2009 }
2010
2011 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2012 MVT::Other, Chains);
2013 } else if (I.getNumOperands() != 0) {
2014 SmallVector<EVT, 4> ValueVTs;
2015 ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2016 unsigned NumValues = ValueVTs.size();
2017 if (NumValues) {
2018 SDValue RetOp = getValue(I.getOperand(0));
2019
2020 const Function *F = I.getParent()->getParent();
2021
2022 bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2023 I.getOperand(0)->getType(), F->getCallingConv(),
2024 /*IsVarArg*/ false, DL);
2025
2026 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2027 if (F->getAttributes().hasRetAttr(Attribute::SExt))
2028 ExtendKind = ISD::SIGN_EXTEND;
2029 else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2030 ExtendKind = ISD::ZERO_EXTEND;
2031
2032 LLVMContext &Context = F->getContext();
2033 bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2034
2035 for (unsigned j = 0; j != NumValues; ++j) {
2036 EVT VT = ValueVTs[j];
2037
2038 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2039 VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2040
2041 CallingConv::ID CC = F->getCallingConv();
2042
2043 unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2044 MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2045 SmallVector<SDValue, 4> Parts(NumParts);
2046 getCopyToParts(DAG, getCurSDLoc(),
2047 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2048 &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2049
2050 // 'inreg' on function refers to return value
2051 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2052 if (RetInReg)
2053 Flags.setInReg();
2054
2055 if (I.getOperand(0)->getType()->isPointerTy()) {
2056 Flags.setPointer();
2057 Flags.setPointerAddrSpace(
2058 cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2059 }
2060
2061 if (NeedsRegBlock) {
2062 Flags.setInConsecutiveRegs();
2063 if (j == NumValues - 1)
2064 Flags.setInConsecutiveRegsLast();
2065 }
2066
2067 // Propagate extension type if any
2068 if (ExtendKind == ISD::SIGN_EXTEND)
2069 Flags.setSExt();
2070 else if (ExtendKind == ISD::ZERO_EXTEND)
2071 Flags.setZExt();
2072
2073 for (unsigned i = 0; i < NumParts; ++i) {
2074 Outs.push_back(ISD::OutputArg(Flags,
2075 Parts[i].getValueType().getSimpleVT(),
2076 VT, /*isfixed=*/true, 0, 0));
2077 OutVals.push_back(Parts[i]);
2078 }
2079 }
2080 }
2081 }
2082
2083 // Push in swifterror virtual register as the last element of Outs. This makes
2084 // sure swifterror virtual register will be returned in the swifterror
2085 // physical register.
2086 const Function *F = I.getParent()->getParent();
2087 if (TLI.supportSwiftError() &&
2088 F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2089 assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2090 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2091 Flags.setSwiftError();
2092 Outs.push_back(ISD::OutputArg(
2093 Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2094 /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2095 // Create SDNode for the swifterror virtual register.
2096 OutVals.push_back(
2097 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2098 &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2099 EVT(TLI.getPointerTy(DL))));
2100 }
2101
2102 bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2103 CallingConv::ID CallConv =
2104 DAG.getMachineFunction().getFunction().getCallingConv();
2105 Chain = DAG.getTargetLoweringInfo().LowerReturn(
2106 Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2107
2108 // Verify that the target's LowerReturn behaved as expected.
2109 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2110 "LowerReturn didn't return a valid chain!");
2111
2112 // Update the DAG with the new chain value resulting from return lowering.
2113 DAG.setRoot(Chain);
2114 }
2115
2116 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2117 /// created for it, emit nodes to copy the value into the virtual
2118 /// registers.
CopyToExportRegsIfNeeded(const Value * V)2119 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2120 // Skip empty types
2121 if (V->getType()->isEmptyTy())
2122 return;
2123
2124 DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2125 if (VMI != FuncInfo.ValueMap.end()) {
2126 assert(!V->use_empty() && "Unused value assigned virtual registers!");
2127 CopyValueToVirtualRegister(V, VMI->second);
2128 }
2129 }
2130
2131 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2132 /// the current basic block, add it to ValueMap now so that we'll get a
2133 /// CopyTo/FromReg.
ExportFromCurrentBlock(const Value * V)2134 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2135 // No need to export constants.
2136 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2137
2138 // Already exported?
2139 if (FuncInfo.isExportedInst(V)) return;
2140
2141 Register Reg = FuncInfo.InitializeRegForValue(V);
2142 CopyValueToVirtualRegister(V, Reg);
2143 }
2144
isExportableFromCurrentBlock(const Value * V,const BasicBlock * FromBB)2145 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2146 const BasicBlock *FromBB) {
2147 // The operands of the setcc have to be in this block. We don't know
2148 // how to export them from some other block.
2149 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2150 // Can export from current BB.
2151 if (VI->getParent() == FromBB)
2152 return true;
2153
2154 // Is already exported, noop.
2155 return FuncInfo.isExportedInst(V);
2156 }
2157
2158 // If this is an argument, we can export it if the BB is the entry block or
2159 // if it is already exported.
2160 if (isa<Argument>(V)) {
2161 if (FromBB->isEntryBlock())
2162 return true;
2163
2164 // Otherwise, can only export this if it is already exported.
2165 return FuncInfo.isExportedInst(V);
2166 }
2167
2168 // Otherwise, constants can always be exported.
2169 return true;
2170 }
2171
2172 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2173 BranchProbability
getEdgeProbability(const MachineBasicBlock * Src,const MachineBasicBlock * Dst) const2174 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2175 const MachineBasicBlock *Dst) const {
2176 BranchProbabilityInfo *BPI = FuncInfo.BPI;
2177 const BasicBlock *SrcBB = Src->getBasicBlock();
2178 const BasicBlock *DstBB = Dst->getBasicBlock();
2179 if (!BPI) {
2180 // If BPI is not available, set the default probability as 1 / N, where N is
2181 // the number of successors.
2182 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2183 return BranchProbability(1, SuccSize);
2184 }
2185 return BPI->getEdgeProbability(SrcBB, DstBB);
2186 }
2187
addSuccessorWithProb(MachineBasicBlock * Src,MachineBasicBlock * Dst,BranchProbability Prob)2188 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2189 MachineBasicBlock *Dst,
2190 BranchProbability Prob) {
2191 if (!FuncInfo.BPI)
2192 Src->addSuccessorWithoutProb(Dst);
2193 else {
2194 if (Prob.isUnknown())
2195 Prob = getEdgeProbability(Src, Dst);
2196 Src->addSuccessor(Dst, Prob);
2197 }
2198 }
2199
InBlock(const Value * V,const BasicBlock * BB)2200 static bool InBlock(const Value *V, const BasicBlock *BB) {
2201 if (const Instruction *I = dyn_cast<Instruction>(V))
2202 return I->getParent() == BB;
2203 return true;
2204 }
2205
2206 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2207 /// This function emits a branch and is used at the leaves of an OR or an
2208 /// AND operator tree.
2209 void
EmitBranchForMergedCondition(const Value * Cond,MachineBasicBlock * TBB,MachineBasicBlock * FBB,MachineBasicBlock * CurBB,MachineBasicBlock * SwitchBB,BranchProbability TProb,BranchProbability FProb,bool InvertCond)2210 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2211 MachineBasicBlock *TBB,
2212 MachineBasicBlock *FBB,
2213 MachineBasicBlock *CurBB,
2214 MachineBasicBlock *SwitchBB,
2215 BranchProbability TProb,
2216 BranchProbability FProb,
2217 bool InvertCond) {
2218 const BasicBlock *BB = CurBB->getBasicBlock();
2219
2220 // If the leaf of the tree is a comparison, merge the condition into
2221 // the caseblock.
2222 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2223 // The operands of the cmp have to be in this block. We don't know
2224 // how to export them from some other block. If this is the first block
2225 // of the sequence, no exporting is needed.
2226 if (CurBB == SwitchBB ||
2227 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2228 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2229 ISD::CondCode Condition;
2230 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2231 ICmpInst::Predicate Pred =
2232 InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2233 Condition = getICmpCondCode(Pred);
2234 } else {
2235 const FCmpInst *FC = cast<FCmpInst>(Cond);
2236 FCmpInst::Predicate Pred =
2237 InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2238 Condition = getFCmpCondCode(Pred);
2239 if (TM.Options.NoNaNsFPMath)
2240 Condition = getFCmpCodeWithoutNaN(Condition);
2241 }
2242
2243 CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2244 TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2245 SL->SwitchCases.push_back(CB);
2246 return;
2247 }
2248 }
2249
2250 // Create a CaseBlock record representing this branch.
2251 ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2252 CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2253 nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2254 SL->SwitchCases.push_back(CB);
2255 }
2256
FindMergedConditions(const Value * Cond,MachineBasicBlock * TBB,MachineBasicBlock * FBB,MachineBasicBlock * CurBB,MachineBasicBlock * SwitchBB,Instruction::BinaryOps Opc,BranchProbability TProb,BranchProbability FProb,bool InvertCond)2257 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2258 MachineBasicBlock *TBB,
2259 MachineBasicBlock *FBB,
2260 MachineBasicBlock *CurBB,
2261 MachineBasicBlock *SwitchBB,
2262 Instruction::BinaryOps Opc,
2263 BranchProbability TProb,
2264 BranchProbability FProb,
2265 bool InvertCond) {
2266 // Skip over not part of the tree and remember to invert op and operands at
2267 // next level.
2268 Value *NotCond;
2269 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2270 InBlock(NotCond, CurBB->getBasicBlock())) {
2271 FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2272 !InvertCond);
2273 return;
2274 }
2275
2276 const Instruction *BOp = dyn_cast<Instruction>(Cond);
2277 const Value *BOpOp0, *BOpOp1;
2278 // Compute the effective opcode for Cond, taking into account whether it needs
2279 // to be inverted, e.g.
2280 // and (not (or A, B)), C
2281 // gets lowered as
2282 // and (and (not A, not B), C)
2283 Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2284 if (BOp) {
2285 BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2286 ? Instruction::And
2287 : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2288 ? Instruction::Or
2289 : (Instruction::BinaryOps)0);
2290 if (InvertCond) {
2291 if (BOpc == Instruction::And)
2292 BOpc = Instruction::Or;
2293 else if (BOpc == Instruction::Or)
2294 BOpc = Instruction::And;
2295 }
2296 }
2297
2298 // If this node is not part of the or/and tree, emit it as a branch.
2299 // Note that all nodes in the tree should have same opcode.
2300 bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2301 if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2302 !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2303 !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2304 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2305 TProb, FProb, InvertCond);
2306 return;
2307 }
2308
2309 // Create TmpBB after CurBB.
2310 MachineFunction::iterator BBI(CurBB);
2311 MachineFunction &MF = DAG.getMachineFunction();
2312 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2313 CurBB->getParent()->insert(++BBI, TmpBB);
2314
2315 if (Opc == Instruction::Or) {
2316 // Codegen X | Y as:
2317 // BB1:
2318 // jmp_if_X TBB
2319 // jmp TmpBB
2320 // TmpBB:
2321 // jmp_if_Y TBB
2322 // jmp FBB
2323 //
2324
2325 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2326 // The requirement is that
2327 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2328 // = TrueProb for original BB.
2329 // Assuming the original probabilities are A and B, one choice is to set
2330 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2331 // A/(1+B) and 2B/(1+B). This choice assumes that
2332 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2333 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2334 // TmpBB, but the math is more complicated.
2335
2336 auto NewTrueProb = TProb / 2;
2337 auto NewFalseProb = TProb / 2 + FProb;
2338 // Emit the LHS condition.
2339 FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2340 NewFalseProb, InvertCond);
2341
2342 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2343 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2344 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2345 // Emit the RHS condition into TmpBB.
2346 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2347 Probs[1], InvertCond);
2348 } else {
2349 assert(Opc == Instruction::And && "Unknown merge op!");
2350 // Codegen X & Y as:
2351 // BB1:
2352 // jmp_if_X TmpBB
2353 // jmp FBB
2354 // TmpBB:
2355 // jmp_if_Y TBB
2356 // jmp FBB
2357 //
2358 // This requires creation of TmpBB after CurBB.
2359
2360 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2361 // The requirement is that
2362 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2363 // = FalseProb for original BB.
2364 // Assuming the original probabilities are A and B, one choice is to set
2365 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2366 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2367 // TrueProb for BB1 * FalseProb for TmpBB.
2368
2369 auto NewTrueProb = TProb + FProb / 2;
2370 auto NewFalseProb = FProb / 2;
2371 // Emit the LHS condition.
2372 FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2373 NewFalseProb, InvertCond);
2374
2375 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2376 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2377 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2378 // Emit the RHS condition into TmpBB.
2379 FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2380 Probs[1], InvertCond);
2381 }
2382 }
2383
2384 /// If the set of cases should be emitted as a series of branches, return true.
2385 /// If we should emit this as a bunch of and/or'd together conditions, return
2386 /// false.
2387 bool
ShouldEmitAsBranches(const std::vector<CaseBlock> & Cases)2388 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2389 if (Cases.size() != 2) return true;
2390
2391 // If this is two comparisons of the same values or'd or and'd together, they
2392 // will get folded into a single comparison, so don't emit two blocks.
2393 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2394 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2395 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2396 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2397 return false;
2398 }
2399
2400 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2401 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2402 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2403 Cases[0].CC == Cases[1].CC &&
2404 isa<Constant>(Cases[0].CmpRHS) &&
2405 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2406 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2407 return false;
2408 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2409 return false;
2410 }
2411
2412 return true;
2413 }
2414
visitBr(const BranchInst & I)2415 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2416 MachineBasicBlock *BrMBB = FuncInfo.MBB;
2417
2418 // Update machine-CFG edges.
2419 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2420
2421 if (I.isUnconditional()) {
2422 // Update machine-CFG edges.
2423 BrMBB->addSuccessor(Succ0MBB);
2424
2425 // If this is not a fall-through branch or optimizations are switched off,
2426 // emit the branch.
2427 if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2428 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2429 MVT::Other, getControlRoot(),
2430 DAG.getBasicBlock(Succ0MBB)));
2431
2432 return;
2433 }
2434
2435 // If this condition is one of the special cases we handle, do special stuff
2436 // now.
2437 const Value *CondVal = I.getCondition();
2438 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2439
2440 // If this is a series of conditions that are or'd or and'd together, emit
2441 // this as a sequence of branches instead of setcc's with and/or operations.
2442 // As long as jumps are not expensive (exceptions for multi-use logic ops,
2443 // unpredictable branches, and vector extracts because those jumps are likely
2444 // expensive for any target), this should improve performance.
2445 // For example, instead of something like:
2446 // cmp A, B
2447 // C = seteq
2448 // cmp D, E
2449 // F = setle
2450 // or C, F
2451 // jnz foo
2452 // Emit:
2453 // cmp A, B
2454 // je foo
2455 // cmp D, E
2456 // jle foo
2457 const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2458 if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2459 BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2460 Value *Vec;
2461 const Value *BOp0, *BOp1;
2462 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2463 if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2464 Opcode = Instruction::And;
2465 else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2466 Opcode = Instruction::Or;
2467
2468 if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2469 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2470 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2471 getEdgeProbability(BrMBB, Succ0MBB),
2472 getEdgeProbability(BrMBB, Succ1MBB),
2473 /*InvertCond=*/false);
2474 // If the compares in later blocks need to use values not currently
2475 // exported from this block, export them now. This block should always
2476 // be the first entry.
2477 assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2478
2479 // Allow some cases to be rejected.
2480 if (ShouldEmitAsBranches(SL->SwitchCases)) {
2481 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2482 ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2483 ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2484 }
2485
2486 // Emit the branch for this block.
2487 visitSwitchCase(SL->SwitchCases[0], BrMBB);
2488 SL->SwitchCases.erase(SL->SwitchCases.begin());
2489 return;
2490 }
2491
2492 // Okay, we decided not to do this, remove any inserted MBB's and clear
2493 // SwitchCases.
2494 for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2495 FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2496
2497 SL->SwitchCases.clear();
2498 }
2499 }
2500
2501 // Create a CaseBlock record representing this branch.
2502 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2503 nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2504
2505 // Use visitSwitchCase to actually insert the fast branch sequence for this
2506 // cond branch.
2507 visitSwitchCase(CB, BrMBB);
2508 }
2509
2510 /// visitSwitchCase - Emits the necessary code to represent a single node in
2511 /// the binary search tree resulting from lowering a switch instruction.
visitSwitchCase(CaseBlock & CB,MachineBasicBlock * SwitchBB)2512 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2513 MachineBasicBlock *SwitchBB) {
2514 SDValue Cond;
2515 SDValue CondLHS = getValue(CB.CmpLHS);
2516 SDLoc dl = CB.DL;
2517
2518 if (CB.CC == ISD::SETTRUE) {
2519 // Branch or fall through to TrueBB.
2520 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2521 SwitchBB->normalizeSuccProbs();
2522 if (CB.TrueBB != NextBlock(SwitchBB)) {
2523 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2524 DAG.getBasicBlock(CB.TrueBB)));
2525 }
2526 return;
2527 }
2528
2529 auto &TLI = DAG.getTargetLoweringInfo();
2530 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2531
2532 // Build the setcc now.
2533 if (!CB.CmpMHS) {
2534 // Fold "(X == true)" to X and "(X == false)" to !X to
2535 // handle common cases produced by branch lowering.
2536 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2537 CB.CC == ISD::SETEQ)
2538 Cond = CondLHS;
2539 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2540 CB.CC == ISD::SETEQ) {
2541 SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2542 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2543 } else {
2544 SDValue CondRHS = getValue(CB.CmpRHS);
2545
2546 // If a pointer's DAG type is larger than its memory type then the DAG
2547 // values are zero-extended. This breaks signed comparisons so truncate
2548 // back to the underlying type before doing the compare.
2549 if (CondLHS.getValueType() != MemVT) {
2550 CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2551 CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2552 }
2553 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2554 }
2555 } else {
2556 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2557
2558 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2559 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2560
2561 SDValue CmpOp = getValue(CB.CmpMHS);
2562 EVT VT = CmpOp.getValueType();
2563
2564 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2565 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2566 ISD::SETLE);
2567 } else {
2568 SDValue SUB = DAG.getNode(ISD::SUB, dl,
2569 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2570 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2571 DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2572 }
2573 }
2574
2575 // Update successor info
2576 addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2577 // TrueBB and FalseBB are always different unless the incoming IR is
2578 // degenerate. This only happens when running llc on weird IR.
2579 if (CB.TrueBB != CB.FalseBB)
2580 addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2581 SwitchBB->normalizeSuccProbs();
2582
2583 // If the lhs block is the next block, invert the condition so that we can
2584 // fall through to the lhs instead of the rhs block.
2585 if (CB.TrueBB == NextBlock(SwitchBB)) {
2586 std::swap(CB.TrueBB, CB.FalseBB);
2587 SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2588 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2589 }
2590
2591 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2592 MVT::Other, getControlRoot(), Cond,
2593 DAG.getBasicBlock(CB.TrueBB));
2594
2595 setValue(CurInst, BrCond);
2596
2597 // Insert the false branch. Do this even if it's a fall through branch,
2598 // this makes it easier to do DAG optimizations which require inverting
2599 // the branch condition.
2600 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2601 DAG.getBasicBlock(CB.FalseBB));
2602
2603 DAG.setRoot(BrCond);
2604 }
2605
2606 /// visitJumpTable - Emit JumpTable node in the current MBB
visitJumpTable(SwitchCG::JumpTable & JT)2607 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2608 // Emit the code for the jump table
2609 assert(JT.Reg != -1U && "Should lower JT Header first!");
2610 EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2611 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2612 JT.Reg, PTy);
2613 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2614 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2615 MVT::Other, Index.getValue(1),
2616 Table, Index);
2617 DAG.setRoot(BrJumpTable);
2618 }
2619
2620 /// visitJumpTableHeader - This function emits necessary code to produce index
2621 /// in the JumpTable from switch case.
visitJumpTableHeader(SwitchCG::JumpTable & JT,JumpTableHeader & JTH,MachineBasicBlock * SwitchBB)2622 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2623 JumpTableHeader &JTH,
2624 MachineBasicBlock *SwitchBB) {
2625 SDLoc dl = getCurSDLoc();
2626
2627 // Subtract the lowest switch case value from the value being switched on.
2628 SDValue SwitchOp = getValue(JTH.SValue);
2629 EVT VT = SwitchOp.getValueType();
2630 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2631 DAG.getConstant(JTH.First, dl, VT));
2632
2633 // The SDNode we just created, which holds the value being switched on minus
2634 // the smallest case value, needs to be copied to a virtual register so it
2635 // can be used as an index into the jump table in a subsequent basic block.
2636 // This value may be smaller or larger than the target's pointer type, and
2637 // therefore require extension or truncating.
2638 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2639 SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2640
2641 unsigned JumpTableReg =
2642 FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2643 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2644 JumpTableReg, SwitchOp);
2645 JT.Reg = JumpTableReg;
2646
2647 if (!JTH.FallthroughUnreachable) {
2648 // Emit the range check for the jump table, and branch to the default block
2649 // for the switch statement if the value being switched on exceeds the
2650 // largest case in the switch.
2651 SDValue CMP = DAG.getSetCC(
2652 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2653 Sub.getValueType()),
2654 Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2655
2656 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2657 MVT::Other, CopyTo, CMP,
2658 DAG.getBasicBlock(JT.Default));
2659
2660 // Avoid emitting unnecessary branches to the next block.
2661 if (JT.MBB != NextBlock(SwitchBB))
2662 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2663 DAG.getBasicBlock(JT.MBB));
2664
2665 DAG.setRoot(BrCond);
2666 } else {
2667 // Avoid emitting unnecessary branches to the next block.
2668 if (JT.MBB != NextBlock(SwitchBB))
2669 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2670 DAG.getBasicBlock(JT.MBB)));
2671 else
2672 DAG.setRoot(CopyTo);
2673 }
2674 }
2675
2676 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2677 /// variable if there exists one.
getLoadStackGuard(SelectionDAG & DAG,const SDLoc & DL,SDValue & Chain)2678 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2679 SDValue &Chain) {
2680 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2681 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2682 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2683 MachineFunction &MF = DAG.getMachineFunction();
2684 Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2685 MachineSDNode *Node =
2686 DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2687 if (Global) {
2688 MachinePointerInfo MPInfo(Global);
2689 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2690 MachineMemOperand::MODereferenceable;
2691 MachineMemOperand *MemRef = MF.getMachineMemOperand(
2692 MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2693 DAG.setNodeMemRefs(Node, {MemRef});
2694 }
2695 if (PtrTy != PtrMemTy)
2696 return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2697 return SDValue(Node, 0);
2698 }
2699
2700 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2701 /// tail spliced into a stack protector check success bb.
2702 ///
2703 /// For a high level explanation of how this fits into the stack protector
2704 /// generation see the comment on the declaration of class
2705 /// StackProtectorDescriptor.
visitSPDescriptorParent(StackProtectorDescriptor & SPD,MachineBasicBlock * ParentBB)2706 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2707 MachineBasicBlock *ParentBB) {
2708
2709 // First create the loads to the guard/stack slot for the comparison.
2710 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2711 EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2712 EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2713
2714 MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2715 int FI = MFI.getStackProtectorIndex();
2716
2717 SDValue Guard;
2718 SDLoc dl = getCurSDLoc();
2719 SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2720 const Module &M = *ParentBB->getParent()->getFunction().getParent();
2721 Align Align =
2722 DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2723
2724 // Generate code to load the content of the guard slot.
2725 SDValue GuardVal = DAG.getLoad(
2726 PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2727 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2728 MachineMemOperand::MOVolatile);
2729
2730 if (TLI.useStackGuardXorFP())
2731 GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2732
2733 // Retrieve guard check function, nullptr if instrumentation is inlined.
2734 if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2735 // The target provides a guard check function to validate the guard value.
2736 // Generate a call to that function with the content of the guard slot as
2737 // argument.
2738 FunctionType *FnTy = GuardCheckFn->getFunctionType();
2739 assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2740
2741 TargetLowering::ArgListTy Args;
2742 TargetLowering::ArgListEntry Entry;
2743 Entry.Node = GuardVal;
2744 Entry.Ty = FnTy->getParamType(0);
2745 if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2746 Entry.IsInReg = true;
2747 Args.push_back(Entry);
2748
2749 TargetLowering::CallLoweringInfo CLI(DAG);
2750 CLI.setDebugLoc(getCurSDLoc())
2751 .setChain(DAG.getEntryNode())
2752 .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2753 getValue(GuardCheckFn), std::move(Args));
2754
2755 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2756 DAG.setRoot(Result.second);
2757 return;
2758 }
2759
2760 // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2761 // Otherwise, emit a volatile load to retrieve the stack guard value.
2762 SDValue Chain = DAG.getEntryNode();
2763 if (TLI.useLoadStackGuardNode()) {
2764 Guard = getLoadStackGuard(DAG, dl, Chain);
2765 } else {
2766 const Value *IRGuard = TLI.getSDagStackGuard(M);
2767 SDValue GuardPtr = getValue(IRGuard);
2768
2769 Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2770 MachinePointerInfo(IRGuard, 0), Align,
2771 MachineMemOperand::MOVolatile);
2772 }
2773
2774 // Perform the comparison via a getsetcc.
2775 SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2776 *DAG.getContext(),
2777 Guard.getValueType()),
2778 Guard, GuardVal, ISD::SETNE);
2779
2780 // If the guard/stackslot do not equal, branch to failure MBB.
2781 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2782 MVT::Other, GuardVal.getOperand(0),
2783 Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2784 // Otherwise branch to success MBB.
2785 SDValue Br = DAG.getNode(ISD::BR, dl,
2786 MVT::Other, BrCond,
2787 DAG.getBasicBlock(SPD.getSuccessMBB()));
2788
2789 DAG.setRoot(Br);
2790 }
2791
2792 /// Codegen the failure basic block for a stack protector check.
2793 ///
2794 /// A failure stack protector machine basic block consists simply of a call to
2795 /// __stack_chk_fail().
2796 ///
2797 /// For a high level explanation of how this fits into the stack protector
2798 /// generation see the comment on the declaration of class
2799 /// StackProtectorDescriptor.
2800 void
visitSPDescriptorFailure(StackProtectorDescriptor & SPD)2801 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2802 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2803 TargetLowering::MakeLibCallOptions CallOptions;
2804 CallOptions.setDiscardResult(true);
2805 SDValue Chain =
2806 TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2807 std::nullopt, CallOptions, getCurSDLoc())
2808 .second;
2809 // On PS4/PS5, the "return address" must still be within the calling
2810 // function, even if it's at the very end, so emit an explicit TRAP here.
2811 // Passing 'true' for doesNotReturn above won't generate the trap for us.
2812 if (TM.getTargetTriple().isPS())
2813 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2814 // WebAssembly needs an unreachable instruction after a non-returning call,
2815 // because the function return type can be different from __stack_chk_fail's
2816 // return type (void).
2817 if (TM.getTargetTriple().isWasm())
2818 Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2819
2820 DAG.setRoot(Chain);
2821 }
2822
2823 /// visitBitTestHeader - This function emits necessary code to produce value
2824 /// suitable for "bit tests"
visitBitTestHeader(BitTestBlock & B,MachineBasicBlock * SwitchBB)2825 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2826 MachineBasicBlock *SwitchBB) {
2827 SDLoc dl = getCurSDLoc();
2828
2829 // Subtract the minimum value.
2830 SDValue SwitchOp = getValue(B.SValue);
2831 EVT VT = SwitchOp.getValueType();
2832 SDValue RangeSub =
2833 DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2834
2835 // Determine the type of the test operands.
2836 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2837 bool UsePtrType = false;
2838 if (!TLI.isTypeLegal(VT)) {
2839 UsePtrType = true;
2840 } else {
2841 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2842 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2843 // Switch table case range are encoded into series of masks.
2844 // Just use pointer type, it's guaranteed to fit.
2845 UsePtrType = true;
2846 break;
2847 }
2848 }
2849 SDValue Sub = RangeSub;
2850 if (UsePtrType) {
2851 VT = TLI.getPointerTy(DAG.getDataLayout());
2852 Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2853 }
2854
2855 B.RegVT = VT.getSimpleVT();
2856 B.Reg = FuncInfo.CreateReg(B.RegVT);
2857 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2858
2859 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2860
2861 if (!B.FallthroughUnreachable)
2862 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2863 addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2864 SwitchBB->normalizeSuccProbs();
2865
2866 SDValue Root = CopyTo;
2867 if (!B.FallthroughUnreachable) {
2868 // Conditional branch to the default block.
2869 SDValue RangeCmp = DAG.getSetCC(dl,
2870 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2871 RangeSub.getValueType()),
2872 RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2873 ISD::SETUGT);
2874
2875 Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2876 DAG.getBasicBlock(B.Default));
2877 }
2878
2879 // Avoid emitting unnecessary branches to the next block.
2880 if (MBB != NextBlock(SwitchBB))
2881 Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2882
2883 DAG.setRoot(Root);
2884 }
2885
2886 /// visitBitTestCase - this function produces one "bit test"
visitBitTestCase(BitTestBlock & BB,MachineBasicBlock * NextMBB,BranchProbability BranchProbToNext,unsigned Reg,BitTestCase & B,MachineBasicBlock * SwitchBB)2887 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2888 MachineBasicBlock* NextMBB,
2889 BranchProbability BranchProbToNext,
2890 unsigned Reg,
2891 BitTestCase &B,
2892 MachineBasicBlock *SwitchBB) {
2893 SDLoc dl = getCurSDLoc();
2894 MVT VT = BB.RegVT;
2895 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2896 SDValue Cmp;
2897 unsigned PopCount = llvm::popcount(B.Mask);
2898 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2899 if (PopCount == 1) {
2900 // Testing for a single bit; just compare the shift count with what it
2901 // would need to be to shift a 1 bit in that position.
2902 Cmp = DAG.getSetCC(
2903 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2904 ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2905 ISD::SETEQ);
2906 } else if (PopCount == BB.Range) {
2907 // There is only one zero bit in the range, test for it directly.
2908 Cmp = DAG.getSetCC(
2909 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2910 ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2911 ISD::SETNE);
2912 } else {
2913 // Make desired shift
2914 SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2915 DAG.getConstant(1, dl, VT), ShiftOp);
2916
2917 // Emit bit tests and jumps
2918 SDValue AndOp = DAG.getNode(ISD::AND, dl,
2919 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2920 Cmp = DAG.getSetCC(
2921 dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2922 AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2923 }
2924
2925 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2926 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2927 // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2928 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2929 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2930 // one as they are relative probabilities (and thus work more like weights),
2931 // and hence we need to normalize them to let the sum of them become one.
2932 SwitchBB->normalizeSuccProbs();
2933
2934 SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2935 MVT::Other, getControlRoot(),
2936 Cmp, DAG.getBasicBlock(B.TargetBB));
2937
2938 // Avoid emitting unnecessary branches to the next block.
2939 if (NextMBB != NextBlock(SwitchBB))
2940 BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2941 DAG.getBasicBlock(NextMBB));
2942
2943 DAG.setRoot(BrAnd);
2944 }
2945
visitInvoke(const InvokeInst & I)2946 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2947 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2948
2949 // Retrieve successors. Look through artificial IR level blocks like
2950 // catchswitch for successors.
2951 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2952 const BasicBlock *EHPadBB = I.getSuccessor(1);
2953
2954 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2955 // have to do anything here to lower funclet bundles.
2956 assert(!I.hasOperandBundlesOtherThan(
2957 {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2958 LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2959 LLVMContext::OB_cfguardtarget,
2960 LLVMContext::OB_clang_arc_attachedcall}) &&
2961 "Cannot lower invokes with arbitrary operand bundles yet!");
2962
2963 const Value *Callee(I.getCalledOperand());
2964 const Function *Fn = dyn_cast<Function>(Callee);
2965 if (isa<InlineAsm>(Callee))
2966 visitInlineAsm(I, EHPadBB);
2967 else if (Fn && Fn->isIntrinsic()) {
2968 switch (Fn->getIntrinsicID()) {
2969 default:
2970 llvm_unreachable("Cannot invoke this intrinsic");
2971 case Intrinsic::donothing:
2972 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2973 case Intrinsic::seh_try_begin:
2974 case Intrinsic::seh_scope_begin:
2975 case Intrinsic::seh_try_end:
2976 case Intrinsic::seh_scope_end:
2977 break;
2978 case Intrinsic::experimental_patchpoint_void:
2979 case Intrinsic::experimental_patchpoint_i64:
2980 visitPatchpoint(I, EHPadBB);
2981 break;
2982 case Intrinsic::experimental_gc_statepoint:
2983 LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2984 break;
2985 case Intrinsic::wasm_rethrow: {
2986 // This is usually done in visitTargetIntrinsic, but this intrinsic is
2987 // special because it can be invoked, so we manually lower it to a DAG
2988 // node here.
2989 SmallVector<SDValue, 8> Ops;
2990 Ops.push_back(getRoot()); // inchain
2991 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2992 Ops.push_back(
2993 DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2994 TLI.getPointerTy(DAG.getDataLayout())));
2995 SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2996 DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2997 break;
2998 }
2999 }
3000 } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3001 // Currently we do not lower any intrinsic calls with deopt operand bundles.
3002 // Eventually we will support lowering the @llvm.experimental.deoptimize
3003 // intrinsic, and right now there are no plans to support other intrinsics
3004 // with deopt state.
3005 LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3006 } else {
3007 LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3008 }
3009
3010 // If the value of the invoke is used outside of its defining block, make it
3011 // available as a virtual register.
3012 // We already took care of the exported value for the statepoint instruction
3013 // during call to the LowerStatepoint.
3014 if (!isa<GCStatepointInst>(I)) {
3015 CopyToExportRegsIfNeeded(&I);
3016 }
3017
3018 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3019 BranchProbabilityInfo *BPI = FuncInfo.BPI;
3020 BranchProbability EHPadBBProb =
3021 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3022 : BranchProbability::getZero();
3023 findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3024
3025 // Update successor info.
3026 addSuccessorWithProb(InvokeMBB, Return);
3027 for (auto &UnwindDest : UnwindDests) {
3028 UnwindDest.first->setIsEHPad();
3029 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3030 }
3031 InvokeMBB->normalizeSuccProbs();
3032
3033 // Drop into normal successor.
3034 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3035 DAG.getBasicBlock(Return)));
3036 }
3037
visitCallBr(const CallBrInst & I)3038 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3039 MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3040
3041 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3042 // have to do anything here to lower funclet bundles.
3043 assert(!I.hasOperandBundlesOtherThan(
3044 {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3045 "Cannot lower callbrs with arbitrary operand bundles yet!");
3046
3047 assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3048 visitInlineAsm(I);
3049 CopyToExportRegsIfNeeded(&I);
3050
3051 // Retrieve successors.
3052 SmallPtrSet<BasicBlock *, 8> Dests;
3053 Dests.insert(I.getDefaultDest());
3054 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3055
3056 // Update successor info.
3057 addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3058 for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3059 BasicBlock *Dest = I.getIndirectDest(i);
3060 MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3061 Target->setIsInlineAsmBrIndirectTarget();
3062 Target->setMachineBlockAddressTaken();
3063 Target->setLabelMustBeEmitted();
3064 // Don't add duplicate machine successors.
3065 if (Dests.insert(Dest).second)
3066 addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3067 }
3068 CallBrMBB->normalizeSuccProbs();
3069
3070 // Drop into default successor.
3071 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3072 MVT::Other, getControlRoot(),
3073 DAG.getBasicBlock(Return)));
3074 }
3075
visitResume(const ResumeInst & RI)3076 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3077 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3078 }
3079
visitLandingPad(const LandingPadInst & LP)3080 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3081 assert(FuncInfo.MBB->isEHPad() &&
3082 "Call to landingpad not in landing pad!");
3083
3084 // If there aren't registers to copy the values into (e.g., during SjLj
3085 // exceptions), then don't bother to create these DAG nodes.
3086 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3087 const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3088 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3089 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3090 return;
3091
3092 // If landingpad's return type is token type, we don't create DAG nodes
3093 // for its exception pointer and selector value. The extraction of exception
3094 // pointer or selector value from token type landingpads is not currently
3095 // supported.
3096 if (LP.getType()->isTokenTy())
3097 return;
3098
3099 SmallVector<EVT, 2> ValueVTs;
3100 SDLoc dl = getCurSDLoc();
3101 ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3102 assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3103
3104 // Get the two live-in registers as SDValues. The physregs have already been
3105 // copied into virtual registers.
3106 SDValue Ops[2];
3107 if (FuncInfo.ExceptionPointerVirtReg) {
3108 Ops[0] = DAG.getZExtOrTrunc(
3109 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3110 FuncInfo.ExceptionPointerVirtReg,
3111 TLI.getPointerTy(DAG.getDataLayout())),
3112 dl, ValueVTs[0]);
3113 } else {
3114 Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3115 }
3116 Ops[1] = DAG.getZExtOrTrunc(
3117 DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3118 FuncInfo.ExceptionSelectorVirtReg,
3119 TLI.getPointerTy(DAG.getDataLayout())),
3120 dl, ValueVTs[1]);
3121
3122 // Merge into one.
3123 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3124 DAG.getVTList(ValueVTs), Ops);
3125 setValue(&LP, Res);
3126 }
3127
UpdateSplitBlock(MachineBasicBlock * First,MachineBasicBlock * Last)3128 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3129 MachineBasicBlock *Last) {
3130 // Update JTCases.
3131 for (JumpTableBlock &JTB : SL->JTCases)
3132 if (JTB.first.HeaderBB == First)
3133 JTB.first.HeaderBB = Last;
3134
3135 // Update BitTestCases.
3136 for (BitTestBlock &BTB : SL->BitTestCases)
3137 if (BTB.Parent == First)
3138 BTB.Parent = Last;
3139 }
3140
visitIndirectBr(const IndirectBrInst & I)3141 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3142 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3143
3144 // Update machine-CFG edges with unique successors.
3145 SmallSet<BasicBlock*, 32> Done;
3146 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3147 BasicBlock *BB = I.getSuccessor(i);
3148 bool Inserted = Done.insert(BB).second;
3149 if (!Inserted)
3150 continue;
3151
3152 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3153 addSuccessorWithProb(IndirectBrMBB, Succ);
3154 }
3155 IndirectBrMBB->normalizeSuccProbs();
3156
3157 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3158 MVT::Other, getControlRoot(),
3159 getValue(I.getAddress())));
3160 }
3161
visitUnreachable(const UnreachableInst & I)3162 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3163 if (!DAG.getTarget().Options.TrapUnreachable)
3164 return;
3165
3166 // We may be able to ignore unreachable behind a noreturn call.
3167 if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3168 const BasicBlock &BB = *I.getParent();
3169 if (&I != &BB.front()) {
3170 BasicBlock::const_iterator PredI =
3171 std::prev(BasicBlock::const_iterator(&I));
3172 if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3173 if (Call->doesNotReturn())
3174 return;
3175 }
3176 }
3177 }
3178
3179 DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3180 }
3181
visitUnary(const User & I,unsigned Opcode)3182 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3183 SDNodeFlags Flags;
3184 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3185 Flags.copyFMF(*FPOp);
3186
3187 SDValue Op = getValue(I.getOperand(0));
3188 SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3189 Op, Flags);
3190 setValue(&I, UnNodeValue);
3191 }
3192
visitBinary(const User & I,unsigned Opcode)3193 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3194 SDNodeFlags Flags;
3195 if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3196 Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3197 Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3198 }
3199 if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3200 Flags.setExact(ExactOp->isExact());
3201 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3202 Flags.copyFMF(*FPOp);
3203
3204 SDValue Op1 = getValue(I.getOperand(0));
3205 SDValue Op2 = getValue(I.getOperand(1));
3206 SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3207 Op1, Op2, Flags);
3208 setValue(&I, BinNodeValue);
3209 }
3210
visitShift(const User & I,unsigned Opcode)3211 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3212 SDValue Op1 = getValue(I.getOperand(0));
3213 SDValue Op2 = getValue(I.getOperand(1));
3214
3215 EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3216 Op1.getValueType(), DAG.getDataLayout());
3217
3218 // Coerce the shift amount to the right type if we can. This exposes the
3219 // truncate or zext to optimization early.
3220 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3221 assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3222 "Unexpected shift type");
3223 Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3224 }
3225
3226 bool nuw = false;
3227 bool nsw = false;
3228 bool exact = false;
3229
3230 if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3231
3232 if (const OverflowingBinaryOperator *OFBinOp =
3233 dyn_cast<const OverflowingBinaryOperator>(&I)) {
3234 nuw = OFBinOp->hasNoUnsignedWrap();
3235 nsw = OFBinOp->hasNoSignedWrap();
3236 }
3237 if (const PossiblyExactOperator *ExactOp =
3238 dyn_cast<const PossiblyExactOperator>(&I))
3239 exact = ExactOp->isExact();
3240 }
3241 SDNodeFlags Flags;
3242 Flags.setExact(exact);
3243 Flags.setNoSignedWrap(nsw);
3244 Flags.setNoUnsignedWrap(nuw);
3245 SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3246 Flags);
3247 setValue(&I, Res);
3248 }
3249
visitSDiv(const User & I)3250 void SelectionDAGBuilder::visitSDiv(const User &I) {
3251 SDValue Op1 = getValue(I.getOperand(0));
3252 SDValue Op2 = getValue(I.getOperand(1));
3253
3254 SDNodeFlags Flags;
3255 Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3256 cast<PossiblyExactOperator>(&I)->isExact());
3257 setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3258 Op2, Flags));
3259 }
3260
visitICmp(const User & I)3261 void SelectionDAGBuilder::visitICmp(const User &I) {
3262 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3263 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3264 predicate = IC->getPredicate();
3265 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3266 predicate = ICmpInst::Predicate(IC->getPredicate());
3267 SDValue Op1 = getValue(I.getOperand(0));
3268 SDValue Op2 = getValue(I.getOperand(1));
3269 ISD::CondCode Opcode = getICmpCondCode(predicate);
3270
3271 auto &TLI = DAG.getTargetLoweringInfo();
3272 EVT MemVT =
3273 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3274
3275 // If a pointer's DAG type is larger than its memory type then the DAG values
3276 // are zero-extended. This breaks signed comparisons so truncate back to the
3277 // underlying type before doing the compare.
3278 if (Op1.getValueType() != MemVT) {
3279 Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3280 Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3281 }
3282
3283 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3284 I.getType());
3285 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3286 }
3287
visitFCmp(const User & I)3288 void SelectionDAGBuilder::visitFCmp(const User &I) {
3289 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3290 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3291 predicate = FC->getPredicate();
3292 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3293 predicate = FCmpInst::Predicate(FC->getPredicate());
3294 SDValue Op1 = getValue(I.getOperand(0));
3295 SDValue Op2 = getValue(I.getOperand(1));
3296
3297 ISD::CondCode Condition = getFCmpCondCode(predicate);
3298 auto *FPMO = cast<FPMathOperator>(&I);
3299 if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3300 Condition = getFCmpCodeWithoutNaN(Condition);
3301
3302 SDNodeFlags Flags;
3303 Flags.copyFMF(*FPMO);
3304 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3305
3306 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3307 I.getType());
3308 setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3309 }
3310
3311 // Check if the condition of the select has one use or two users that are both
3312 // selects with the same condition.
hasOnlySelectUsers(const Value * Cond)3313 static bool hasOnlySelectUsers(const Value *Cond) {
3314 return llvm::all_of(Cond->users(), [](const Value *V) {
3315 return isa<SelectInst>(V);
3316 });
3317 }
3318
visitSelect(const User & I)3319 void SelectionDAGBuilder::visitSelect(const User &I) {
3320 SmallVector<EVT, 4> ValueVTs;
3321 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3322 ValueVTs);
3323 unsigned NumValues = ValueVTs.size();
3324 if (NumValues == 0) return;
3325
3326 SmallVector<SDValue, 4> Values(NumValues);
3327 SDValue Cond = getValue(I.getOperand(0));
3328 SDValue LHSVal = getValue(I.getOperand(1));
3329 SDValue RHSVal = getValue(I.getOperand(2));
3330 SmallVector<SDValue, 1> BaseOps(1, Cond);
3331 ISD::NodeType OpCode =
3332 Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3333
3334 bool IsUnaryAbs = false;
3335 bool Negate = false;
3336
3337 SDNodeFlags Flags;
3338 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3339 Flags.copyFMF(*FPOp);
3340
3341 // Min/max matching is only viable if all output VTs are the same.
3342 if (all_equal(ValueVTs)) {
3343 EVT VT = ValueVTs[0];
3344 LLVMContext &Ctx = *DAG.getContext();
3345 auto &TLI = DAG.getTargetLoweringInfo();
3346
3347 // We care about the legality of the operation after it has been type
3348 // legalized.
3349 while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3350 VT = TLI.getTypeToTransformTo(Ctx, VT);
3351
3352 // If the vselect is legal, assume we want to leave this as a vector setcc +
3353 // vselect. Otherwise, if this is going to be scalarized, we want to see if
3354 // min/max is legal on the scalar type.
3355 bool UseScalarMinMax = VT.isVector() &&
3356 !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3357
3358 Value *LHS, *RHS;
3359 auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3360 ISD::NodeType Opc = ISD::DELETED_NODE;
3361 switch (SPR.Flavor) {
3362 case SPF_UMAX: Opc = ISD::UMAX; break;
3363 case SPF_UMIN: Opc = ISD::UMIN; break;
3364 case SPF_SMAX: Opc = ISD::SMAX; break;
3365 case SPF_SMIN: Opc = ISD::SMIN; break;
3366 case SPF_FMINNUM:
3367 switch (SPR.NaNBehavior) {
3368 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3369 case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
3370 case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3371 case SPNB_RETURNS_ANY: {
3372 if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3373 Opc = ISD::FMINNUM;
3374 else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3375 Opc = ISD::FMINIMUM;
3376 else if (UseScalarMinMax)
3377 Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3378 ISD::FMINNUM : ISD::FMINIMUM;
3379 break;
3380 }
3381 }
3382 break;
3383 case SPF_FMAXNUM:
3384 switch (SPR.NaNBehavior) {
3385 case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3386 case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
3387 case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3388 case SPNB_RETURNS_ANY:
3389
3390 if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3391 Opc = ISD::FMAXNUM;
3392 else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3393 Opc = ISD::FMAXIMUM;
3394 else if (UseScalarMinMax)
3395 Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3396 ISD::FMAXNUM : ISD::FMAXIMUM;
3397 break;
3398 }
3399 break;
3400 case SPF_NABS:
3401 Negate = true;
3402 [[fallthrough]];
3403 case SPF_ABS:
3404 IsUnaryAbs = true;
3405 Opc = ISD::ABS;
3406 break;
3407 default: break;
3408 }
3409
3410 if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3411 (TLI.isOperationLegalOrCustom(Opc, VT) ||
3412 (UseScalarMinMax &&
3413 TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3414 // If the underlying comparison instruction is used by any other
3415 // instruction, the consumed instructions won't be destroyed, so it is
3416 // not profitable to convert to a min/max.
3417 hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3418 OpCode = Opc;
3419 LHSVal = getValue(LHS);
3420 RHSVal = getValue(RHS);
3421 BaseOps.clear();
3422 }
3423
3424 if (IsUnaryAbs) {
3425 OpCode = Opc;
3426 LHSVal = getValue(LHS);
3427 BaseOps.clear();
3428 }
3429 }
3430
3431 if (IsUnaryAbs) {
3432 for (unsigned i = 0; i != NumValues; ++i) {
3433 SDLoc dl = getCurSDLoc();
3434 EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3435 Values[i] =
3436 DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3437 if (Negate)
3438 Values[i] = DAG.getNegative(Values[i], dl, VT);
3439 }
3440 } else {
3441 for (unsigned i = 0; i != NumValues; ++i) {
3442 SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3443 Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3444 Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3445 Values[i] = DAG.getNode(
3446 OpCode, getCurSDLoc(),
3447 LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3448 }
3449 }
3450
3451 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3452 DAG.getVTList(ValueVTs), Values));
3453 }
3454
visitTrunc(const User & I)3455 void SelectionDAGBuilder::visitTrunc(const User &I) {
3456 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3457 SDValue N = getValue(I.getOperand(0));
3458 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3459 I.getType());
3460 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3461 }
3462
visitZExt(const User & I)3463 void SelectionDAGBuilder::visitZExt(const User &I) {
3464 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3465 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3466 SDValue N = getValue(I.getOperand(0));
3467 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3468 I.getType());
3469 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3470 }
3471
visitSExt(const User & I)3472 void SelectionDAGBuilder::visitSExt(const User &I) {
3473 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3474 // SExt also can't be a cast to bool for same reason. So, nothing much to do
3475 SDValue N = getValue(I.getOperand(0));
3476 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3477 I.getType());
3478 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3479 }
3480
visitFPTrunc(const User & I)3481 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3482 // FPTrunc is never a no-op cast, no need to check
3483 SDValue N = getValue(I.getOperand(0));
3484 SDLoc dl = getCurSDLoc();
3485 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3486 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3487 setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3488 DAG.getTargetConstant(
3489 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3490 }
3491
visitFPExt(const User & I)3492 void SelectionDAGBuilder::visitFPExt(const User &I) {
3493 // FPExt is never a no-op cast, no need to check
3494 SDValue N = getValue(I.getOperand(0));
3495 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3496 I.getType());
3497 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3498 }
3499
visitFPToUI(const User & I)3500 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3501 // FPToUI is never a no-op cast, no need to check
3502 SDValue N = getValue(I.getOperand(0));
3503 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3504 I.getType());
3505 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3506 }
3507
visitFPToSI(const User & I)3508 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3509 // FPToSI is never a no-op cast, no need to check
3510 SDValue N = getValue(I.getOperand(0));
3511 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3512 I.getType());
3513 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3514 }
3515
visitUIToFP(const User & I)3516 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3517 // UIToFP is never a no-op cast, no need to check
3518 SDValue N = getValue(I.getOperand(0));
3519 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3520 I.getType());
3521 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3522 }
3523
visitSIToFP(const User & I)3524 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3525 // SIToFP is never a no-op cast, no need to check
3526 SDValue N = getValue(I.getOperand(0));
3527 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3528 I.getType());
3529 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3530 }
3531
visitPtrToInt(const User & I)3532 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3533 // What to do depends on the size of the integer and the size of the pointer.
3534 // We can either truncate, zero extend, or no-op, accordingly.
3535 SDValue N = getValue(I.getOperand(0));
3536 auto &TLI = DAG.getTargetLoweringInfo();
3537 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3538 I.getType());
3539 EVT PtrMemVT =
3540 TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3541 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3542 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3543 setValue(&I, N);
3544 }
3545
visitIntToPtr(const User & I)3546 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3547 // What to do depends on the size of the integer and the size of the pointer.
3548 // We can either truncate, zero extend, or no-op, accordingly.
3549 SDValue N = getValue(I.getOperand(0));
3550 auto &TLI = DAG.getTargetLoweringInfo();
3551 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3552 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3553 N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3554 N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3555 setValue(&I, N);
3556 }
3557
visitBitCast(const User & I)3558 void SelectionDAGBuilder::visitBitCast(const User &I) {
3559 SDValue N = getValue(I.getOperand(0));
3560 SDLoc dl = getCurSDLoc();
3561 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3562 I.getType());
3563
3564 // BitCast assures us that source and destination are the same size so this is
3565 // either a BITCAST or a no-op.
3566 if (DestVT != N.getValueType())
3567 setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3568 DestVT, N)); // convert types.
3569 // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3570 // might fold any kind of constant expression to an integer constant and that
3571 // is not what we are looking for. Only recognize a bitcast of a genuine
3572 // constant integer as an opaque constant.
3573 else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3574 setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3575 /*isOpaque*/true));
3576 else
3577 setValue(&I, N); // noop cast.
3578 }
3579
visitAddrSpaceCast(const User & I)3580 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3581 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3582 const Value *SV = I.getOperand(0);
3583 SDValue N = getValue(SV);
3584 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3585
3586 unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3587 unsigned DestAS = I.getType()->getPointerAddressSpace();
3588
3589 if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3590 N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3591
3592 setValue(&I, N);
3593 }
3594
visitInsertElement(const User & I)3595 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3596 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3597 SDValue InVec = getValue(I.getOperand(0));
3598 SDValue InVal = getValue(I.getOperand(1));
3599 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3600 TLI.getVectorIdxTy(DAG.getDataLayout()));
3601 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3602 TLI.getValueType(DAG.getDataLayout(), I.getType()),
3603 InVec, InVal, InIdx));
3604 }
3605
visitExtractElement(const User & I)3606 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3607 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3608 SDValue InVec = getValue(I.getOperand(0));
3609 SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3610 TLI.getVectorIdxTy(DAG.getDataLayout()));
3611 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3612 TLI.getValueType(DAG.getDataLayout(), I.getType()),
3613 InVec, InIdx));
3614 }
3615
visitShuffleVector(const User & I)3616 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3617 SDValue Src1 = getValue(I.getOperand(0));
3618 SDValue Src2 = getValue(I.getOperand(1));
3619 ArrayRef<int> Mask;
3620 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3621 Mask = SVI->getShuffleMask();
3622 else
3623 Mask = cast<ConstantExpr>(I).getShuffleMask();
3624 SDLoc DL = getCurSDLoc();
3625 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3626 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3627 EVT SrcVT = Src1.getValueType();
3628
3629 if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3630 VT.isScalableVector()) {
3631 // Canonical splat form of first element of first input vector.
3632 SDValue FirstElt =
3633 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3634 DAG.getVectorIdxConstant(0, DL));
3635 setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3636 return;
3637 }
3638
3639 // For now, we only handle splats for scalable vectors.
3640 // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3641 // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3642 assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3643
3644 unsigned SrcNumElts = SrcVT.getVectorNumElements();
3645 unsigned MaskNumElts = Mask.size();
3646
3647 if (SrcNumElts == MaskNumElts) {
3648 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3649 return;
3650 }
3651
3652 // Normalize the shuffle vector since mask and vector length don't match.
3653 if (SrcNumElts < MaskNumElts) {
3654 // Mask is longer than the source vectors. We can use concatenate vector to
3655 // make the mask and vectors lengths match.
3656
3657 if (MaskNumElts % SrcNumElts == 0) {
3658 // Mask length is a multiple of the source vector length.
3659 // Check if the shuffle is some kind of concatenation of the input
3660 // vectors.
3661 unsigned NumConcat = MaskNumElts / SrcNumElts;
3662 bool IsConcat = true;
3663 SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3664 for (unsigned i = 0; i != MaskNumElts; ++i) {
3665 int Idx = Mask[i];
3666 if (Idx < 0)
3667 continue;
3668 // Ensure the indices in each SrcVT sized piece are sequential and that
3669 // the same source is used for the whole piece.
3670 if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3671 (ConcatSrcs[i / SrcNumElts] >= 0 &&
3672 ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3673 IsConcat = false;
3674 break;
3675 }
3676 // Remember which source this index came from.
3677 ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3678 }
3679
3680 // The shuffle is concatenating multiple vectors together. Just emit
3681 // a CONCAT_VECTORS operation.
3682 if (IsConcat) {
3683 SmallVector<SDValue, 8> ConcatOps;
3684 for (auto Src : ConcatSrcs) {
3685 if (Src < 0)
3686 ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3687 else if (Src == 0)
3688 ConcatOps.push_back(Src1);
3689 else
3690 ConcatOps.push_back(Src2);
3691 }
3692 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3693 return;
3694 }
3695 }
3696
3697 unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3698 unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3699 EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3700 PaddedMaskNumElts);
3701
3702 // Pad both vectors with undefs to make them the same length as the mask.
3703 SDValue UndefVal = DAG.getUNDEF(SrcVT);
3704
3705 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3706 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3707 MOps1[0] = Src1;
3708 MOps2[0] = Src2;
3709
3710 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3711 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3712
3713 // Readjust mask for new input vector length.
3714 SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3715 for (unsigned i = 0; i != MaskNumElts; ++i) {
3716 int Idx = Mask[i];
3717 if (Idx >= (int)SrcNumElts)
3718 Idx -= SrcNumElts - PaddedMaskNumElts;
3719 MappedOps[i] = Idx;
3720 }
3721
3722 SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3723
3724 // If the concatenated vector was padded, extract a subvector with the
3725 // correct number of elements.
3726 if (MaskNumElts != PaddedMaskNumElts)
3727 Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3728 DAG.getVectorIdxConstant(0, DL));
3729
3730 setValue(&I, Result);
3731 return;
3732 }
3733
3734 if (SrcNumElts > MaskNumElts) {
3735 // Analyze the access pattern of the vector to see if we can extract
3736 // two subvectors and do the shuffle.
3737 int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
3738 bool CanExtract = true;
3739 for (int Idx : Mask) {
3740 unsigned Input = 0;
3741 if (Idx < 0)
3742 continue;
3743
3744 if (Idx >= (int)SrcNumElts) {
3745 Input = 1;
3746 Idx -= SrcNumElts;
3747 }
3748
3749 // If all the indices come from the same MaskNumElts sized portion of
3750 // the sources we can use extract. Also make sure the extract wouldn't
3751 // extract past the end of the source.
3752 int NewStartIdx = alignDown(Idx, MaskNumElts);
3753 if (NewStartIdx + MaskNumElts > SrcNumElts ||
3754 (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3755 CanExtract = false;
3756 // Make sure we always update StartIdx as we use it to track if all
3757 // elements are undef.
3758 StartIdx[Input] = NewStartIdx;
3759 }
3760
3761 if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3762 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3763 return;
3764 }
3765 if (CanExtract) {
3766 // Extract appropriate subvector and generate a vector shuffle
3767 for (unsigned Input = 0; Input < 2; ++Input) {
3768 SDValue &Src = Input == 0 ? Src1 : Src2;
3769 if (StartIdx[Input] < 0)
3770 Src = DAG.getUNDEF(VT);
3771 else {
3772 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3773 DAG.getVectorIdxConstant(StartIdx[Input], DL));
3774 }
3775 }
3776
3777 // Calculate new mask.
3778 SmallVector<int, 8> MappedOps(Mask);
3779 for (int &Idx : MappedOps) {
3780 if (Idx >= (int)SrcNumElts)
3781 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3782 else if (Idx >= 0)
3783 Idx -= StartIdx[0];
3784 }
3785
3786 setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3787 return;
3788 }
3789 }
3790
3791 // We can't use either concat vectors or extract subvectors so fall back to
3792 // replacing the shuffle with extract and build vector.
3793 // to insert and build vector.
3794 EVT EltVT = VT.getVectorElementType();
3795 SmallVector<SDValue,8> Ops;
3796 for (int Idx : Mask) {
3797 SDValue Res;
3798
3799 if (Idx < 0) {
3800 Res = DAG.getUNDEF(EltVT);
3801 } else {
3802 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3803 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3804
3805 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3806 DAG.getVectorIdxConstant(Idx, DL));
3807 }
3808
3809 Ops.push_back(Res);
3810 }
3811
3812 setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3813 }
3814
visitInsertValue(const InsertValueInst & I)3815 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3816 ArrayRef<unsigned> Indices = I.getIndices();
3817 const Value *Op0 = I.getOperand(0);
3818 const Value *Op1 = I.getOperand(1);
3819 Type *AggTy = I.getType();
3820 Type *ValTy = Op1->getType();
3821 bool IntoUndef = isa<UndefValue>(Op0);
3822 bool FromUndef = isa<UndefValue>(Op1);
3823
3824 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3825
3826 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3827 SmallVector<EVT, 4> AggValueVTs;
3828 ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3829 SmallVector<EVT, 4> ValValueVTs;
3830 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3831
3832 unsigned NumAggValues = AggValueVTs.size();
3833 unsigned NumValValues = ValValueVTs.size();
3834 SmallVector<SDValue, 4> Values(NumAggValues);
3835
3836 // Ignore an insertvalue that produces an empty object
3837 if (!NumAggValues) {
3838 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3839 return;
3840 }
3841
3842 SDValue Agg = getValue(Op0);
3843 unsigned i = 0;
3844 // Copy the beginning value(s) from the original aggregate.
3845 for (; i != LinearIndex; ++i)
3846 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3847 SDValue(Agg.getNode(), Agg.getResNo() + i);
3848 // Copy values from the inserted value(s).
3849 if (NumValValues) {
3850 SDValue Val = getValue(Op1);
3851 for (; i != LinearIndex + NumValValues; ++i)
3852 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3853 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3854 }
3855 // Copy remaining value(s) from the original aggregate.
3856 for (; i != NumAggValues; ++i)
3857 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3858 SDValue(Agg.getNode(), Agg.getResNo() + i);
3859
3860 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3861 DAG.getVTList(AggValueVTs), Values));
3862 }
3863
visitExtractValue(const ExtractValueInst & I)3864 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3865 ArrayRef<unsigned> Indices = I.getIndices();
3866 const Value *Op0 = I.getOperand(0);
3867 Type *AggTy = Op0->getType();
3868 Type *ValTy = I.getType();
3869 bool OutOfUndef = isa<UndefValue>(Op0);
3870
3871 unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3872
3873 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3874 SmallVector<EVT, 4> ValValueVTs;
3875 ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3876
3877 unsigned NumValValues = ValValueVTs.size();
3878
3879 // Ignore a extractvalue that produces an empty object
3880 if (!NumValValues) {
3881 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3882 return;
3883 }
3884
3885 SmallVector<SDValue, 4> Values(NumValValues);
3886
3887 SDValue Agg = getValue(Op0);
3888 // Copy out the selected value(s).
3889 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3890 Values[i - LinearIndex] =
3891 OutOfUndef ?
3892 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3893 SDValue(Agg.getNode(), Agg.getResNo() + i);
3894
3895 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3896 DAG.getVTList(ValValueVTs), Values));
3897 }
3898
visitGetElementPtr(const User & I)3899 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3900 Value *Op0 = I.getOperand(0);
3901 // Note that the pointer operand may be a vector of pointers. Take the scalar
3902 // element which holds a pointer.
3903 unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3904 SDValue N = getValue(Op0);
3905 SDLoc dl = getCurSDLoc();
3906 auto &TLI = DAG.getTargetLoweringInfo();
3907
3908 // Normalize Vector GEP - all scalar operands should be converted to the
3909 // splat vector.
3910 bool IsVectorGEP = I.getType()->isVectorTy();
3911 ElementCount VectorElementCount =
3912 IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3913 : ElementCount::getFixed(0);
3914
3915 if (IsVectorGEP && !N.getValueType().isVector()) {
3916 LLVMContext &Context = *DAG.getContext();
3917 EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3918 N = DAG.getSplat(VT, dl, N);
3919 }
3920
3921 for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3922 GTI != E; ++GTI) {
3923 const Value *Idx = GTI.getOperand();
3924 if (StructType *StTy = GTI.getStructTypeOrNull()) {
3925 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3926 if (Field) {
3927 // N = N + Offset
3928 uint64_t Offset =
3929 DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3930
3931 // In an inbounds GEP with an offset that is nonnegative even when
3932 // interpreted as signed, assume there is no unsigned overflow.
3933 SDNodeFlags Flags;
3934 if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3935 Flags.setNoUnsignedWrap(true);
3936
3937 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3938 DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3939 }
3940 } else {
3941 // IdxSize is the width of the arithmetic according to IR semantics.
3942 // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3943 // (and fix up the result later).
3944 unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3945 MVT IdxTy = MVT::getIntegerVT(IdxSize);
3946 TypeSize ElementSize =
3947 DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3948 // We intentionally mask away the high bits here; ElementSize may not
3949 // fit in IdxTy.
3950 APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
3951 bool ElementScalable = ElementSize.isScalable();
3952
3953 // If this is a scalar constant or a splat vector of constants,
3954 // handle it quickly.
3955 const auto *C = dyn_cast<Constant>(Idx);
3956 if (C && isa<VectorType>(C->getType()))
3957 C = C->getSplatValue();
3958
3959 const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3960 if (CI && CI->isZero())
3961 continue;
3962 if (CI && !ElementScalable) {
3963 APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3964 LLVMContext &Context = *DAG.getContext();
3965 SDValue OffsVal;
3966 if (IsVectorGEP)
3967 OffsVal = DAG.getConstant(
3968 Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3969 else
3970 OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3971
3972 // In an inbounds GEP with an offset that is nonnegative even when
3973 // interpreted as signed, assume there is no unsigned overflow.
3974 SDNodeFlags Flags;
3975 if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3976 Flags.setNoUnsignedWrap(true);
3977
3978 OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3979
3980 N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3981 continue;
3982 }
3983
3984 // N = N + Idx * ElementMul;
3985 SDValue IdxN = getValue(Idx);
3986
3987 if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3988 EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3989 VectorElementCount);
3990 IdxN = DAG.getSplat(VT, dl, IdxN);
3991 }
3992
3993 // If the index is smaller or larger than intptr_t, truncate or extend
3994 // it.
3995 IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3996
3997 if (ElementScalable) {
3998 EVT VScaleTy = N.getValueType().getScalarType();
3999 SDValue VScale = DAG.getNode(
4000 ISD::VSCALE, dl, VScaleTy,
4001 DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4002 if (IsVectorGEP)
4003 VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4004 IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4005 } else {
4006 // If this is a multiply by a power of two, turn it into a shl
4007 // immediately. This is a very common case.
4008 if (ElementMul != 1) {
4009 if (ElementMul.isPowerOf2()) {
4010 unsigned Amt = ElementMul.logBase2();
4011 IdxN = DAG.getNode(ISD::SHL, dl,
4012 N.getValueType(), IdxN,
4013 DAG.getConstant(Amt, dl, IdxN.getValueType()));
4014 } else {
4015 SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4016 IdxN.getValueType());
4017 IdxN = DAG.getNode(ISD::MUL, dl,
4018 N.getValueType(), IdxN, Scale);
4019 }
4020 }
4021 }
4022
4023 N = DAG.getNode(ISD::ADD, dl,
4024 N.getValueType(), N, IdxN);
4025 }
4026 }
4027
4028 MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4029 MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4030 if (IsVectorGEP) {
4031 PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4032 PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4033 }
4034
4035 if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4036 N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4037
4038 setValue(&I, N);
4039 }
4040
visitAlloca(const AllocaInst & I)4041 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4042 // If this is a fixed sized alloca in the entry block of the function,
4043 // allocate it statically on the stack.
4044 if (FuncInfo.StaticAllocaMap.count(&I))
4045 return; // getValue will auto-populate this.
4046
4047 SDLoc dl = getCurSDLoc();
4048 Type *Ty = I.getAllocatedType();
4049 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4050 auto &DL = DAG.getDataLayout();
4051 TypeSize TySize = DL.getTypeAllocSize(Ty);
4052 MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4053
4054 SDValue AllocSize = getValue(I.getArraySize());
4055
4056 EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), I.getAddressSpace());
4057 if (AllocSize.getValueType() != IntPtr)
4058 AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4059
4060 if (TySize.isScalable())
4061 AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4062 DAG.getVScale(dl, IntPtr,
4063 APInt(IntPtr.getScalarSizeInBits(),
4064 TySize.getKnownMinValue())));
4065 else
4066 AllocSize =
4067 DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4068 DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4069
4070 // Handle alignment. If the requested alignment is less than or equal to
4071 // the stack alignment, ignore it. If the size is greater than or equal to
4072 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4073 Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4074 if (*Alignment <= StackAlign)
4075 Alignment = std::nullopt;
4076
4077 const uint64_t StackAlignMask = StackAlign.value() - 1U;
4078 // Round the size of the allocation up to the stack alignment size
4079 // by add SA-1 to the size. This doesn't overflow because we're computing
4080 // an address inside an alloca.
4081 SDNodeFlags Flags;
4082 Flags.setNoUnsignedWrap(true);
4083 AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4084 DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4085
4086 // Mask out the low bits for alignment purposes.
4087 AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4088 DAG.getConstant(~StackAlignMask, dl, IntPtr));
4089
4090 SDValue Ops[] = {
4091 getRoot(), AllocSize,
4092 DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4093 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4094 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4095 setValue(&I, DSA);
4096 DAG.setRoot(DSA.getValue(1));
4097
4098 assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4099 }
4100
visitLoad(const LoadInst & I)4101 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4102 if (I.isAtomic())
4103 return visitAtomicLoad(I);
4104
4105 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4106 const Value *SV = I.getOperand(0);
4107 if (TLI.supportSwiftError()) {
4108 // Swifterror values can come from either a function parameter with
4109 // swifterror attribute or an alloca with swifterror attribute.
4110 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4111 if (Arg->hasSwiftErrorAttr())
4112 return visitLoadFromSwiftError(I);
4113 }
4114
4115 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4116 if (Alloca->isSwiftError())
4117 return visitLoadFromSwiftError(I);
4118 }
4119 }
4120
4121 SDValue Ptr = getValue(SV);
4122
4123 Type *Ty = I.getType();
4124 SmallVector<EVT, 4> ValueVTs, MemVTs;
4125 SmallVector<uint64_t, 4> Offsets;
4126 ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4127 unsigned NumValues = ValueVTs.size();
4128 if (NumValues == 0)
4129 return;
4130
4131 Align Alignment = I.getAlign();
4132 AAMDNodes AAInfo = I.getAAMetadata();
4133 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4134 bool isVolatile = I.isVolatile();
4135 MachineMemOperand::Flags MMOFlags =
4136 TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4137
4138 SDValue Root;
4139 bool ConstantMemory = false;
4140 if (isVolatile)
4141 // Serialize volatile loads with other side effects.
4142 Root = getRoot();
4143 else if (NumValues > MaxParallelChains)
4144 Root = getMemoryRoot();
4145 else if (AA &&
4146 AA->pointsToConstantMemory(MemoryLocation(
4147 SV,
4148 LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4149 AAInfo))) {
4150 // Do not serialize (non-volatile) loads of constant memory with anything.
4151 Root = DAG.getEntryNode();
4152 ConstantMemory = true;
4153 MMOFlags |= MachineMemOperand::MOInvariant;
4154 } else {
4155 // Do not serialize non-volatile loads against each other.
4156 Root = DAG.getRoot();
4157 }
4158
4159 SDLoc dl = getCurSDLoc();
4160
4161 if (isVolatile)
4162 Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4163
4164 // An aggregate load cannot wrap around the address space, so offsets to its
4165 // parts don't wrap either.
4166 SDNodeFlags Flags;
4167 Flags.setNoUnsignedWrap(true);
4168
4169 SmallVector<SDValue, 4> Values(NumValues);
4170 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4171 EVT PtrVT = Ptr.getValueType();
4172
4173 unsigned ChainI = 0;
4174 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4175 // Serializing loads here may result in excessive register pressure, and
4176 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4177 // could recover a bit by hoisting nodes upward in the chain by recognizing
4178 // they are side-effect free or do not alias. The optimizer should really
4179 // avoid this case by converting large object/array copies to llvm.memcpy
4180 // (MaxParallelChains should always remain as failsafe).
4181 if (ChainI == MaxParallelChains) {
4182 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4183 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4184 ArrayRef(Chains.data(), ChainI));
4185 Root = Chain;
4186 ChainI = 0;
4187 }
4188 SDValue A = DAG.getNode(ISD::ADD, dl,
4189 PtrVT, Ptr,
4190 DAG.getConstant(Offsets[i], dl, PtrVT),
4191 Flags);
4192
4193 SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4194 MachinePointerInfo(SV, Offsets[i]), Alignment,
4195 MMOFlags, AAInfo, Ranges);
4196 Chains[ChainI] = L.getValue(1);
4197
4198 if (MemVTs[i] != ValueVTs[i])
4199 L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4200
4201 Values[i] = L;
4202 }
4203
4204 if (!ConstantMemory) {
4205 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4206 ArrayRef(Chains.data(), ChainI));
4207 if (isVolatile)
4208 DAG.setRoot(Chain);
4209 else
4210 PendingLoads.push_back(Chain);
4211 }
4212
4213 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4214 DAG.getVTList(ValueVTs), Values));
4215 }
4216
visitStoreToSwiftError(const StoreInst & I)4217 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4218 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4219 "call visitStoreToSwiftError when backend supports swifterror");
4220
4221 SmallVector<EVT, 4> ValueVTs;
4222 SmallVector<uint64_t, 4> Offsets;
4223 const Value *SrcV = I.getOperand(0);
4224 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4225 SrcV->getType(), ValueVTs, &Offsets);
4226 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4227 "expect a single EVT for swifterror");
4228
4229 SDValue Src = getValue(SrcV);
4230 // Create a virtual register, then update the virtual register.
4231 Register VReg =
4232 SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4233 // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4234 // Chain can be getRoot or getControlRoot.
4235 SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4236 SDValue(Src.getNode(), Src.getResNo()));
4237 DAG.setRoot(CopyNode);
4238 }
4239
visitLoadFromSwiftError(const LoadInst & I)4240 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4241 assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4242 "call visitLoadFromSwiftError when backend supports swifterror");
4243
4244 assert(!I.isVolatile() &&
4245 !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4246 !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4247 "Support volatile, non temporal, invariant for load_from_swift_error");
4248
4249 const Value *SV = I.getOperand(0);
4250 Type *Ty = I.getType();
4251 assert(
4252 (!AA ||
4253 !AA->pointsToConstantMemory(MemoryLocation(
4254 SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4255 I.getAAMetadata()))) &&
4256 "load_from_swift_error should not be constant memory");
4257
4258 SmallVector<EVT, 4> ValueVTs;
4259 SmallVector<uint64_t, 4> Offsets;
4260 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4261 ValueVTs, &Offsets);
4262 assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4263 "expect a single EVT for swifterror");
4264
4265 // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4266 SDValue L = DAG.getCopyFromReg(
4267 getRoot(), getCurSDLoc(),
4268 SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4269
4270 setValue(&I, L);
4271 }
4272
visitStore(const StoreInst & I)4273 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4274 if (I.isAtomic())
4275 return visitAtomicStore(I);
4276
4277 const Value *SrcV = I.getOperand(0);
4278 const Value *PtrV = I.getOperand(1);
4279
4280 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4281 if (TLI.supportSwiftError()) {
4282 // Swifterror values can come from either a function parameter with
4283 // swifterror attribute or an alloca with swifterror attribute.
4284 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4285 if (Arg->hasSwiftErrorAttr())
4286 return visitStoreToSwiftError(I);
4287 }
4288
4289 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4290 if (Alloca->isSwiftError())
4291 return visitStoreToSwiftError(I);
4292 }
4293 }
4294
4295 SmallVector<EVT, 4> ValueVTs, MemVTs;
4296 SmallVector<uint64_t, 4> Offsets;
4297 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4298 SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4299 unsigned NumValues = ValueVTs.size();
4300 if (NumValues == 0)
4301 return;
4302
4303 // Get the lowered operands. Note that we do this after
4304 // checking if NumResults is zero, because with zero results
4305 // the operands won't have values in the map.
4306 SDValue Src = getValue(SrcV);
4307 SDValue Ptr = getValue(PtrV);
4308
4309 SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4310 SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4311 SDLoc dl = getCurSDLoc();
4312 Align Alignment = I.getAlign();
4313 AAMDNodes AAInfo = I.getAAMetadata();
4314
4315 auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4316
4317 // An aggregate load cannot wrap around the address space, so offsets to its
4318 // parts don't wrap either.
4319 SDNodeFlags Flags;
4320 Flags.setNoUnsignedWrap(true);
4321
4322 unsigned ChainI = 0;
4323 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4324 // See visitLoad comments.
4325 if (ChainI == MaxParallelChains) {
4326 SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4327 ArrayRef(Chains.data(), ChainI));
4328 Root = Chain;
4329 ChainI = 0;
4330 }
4331 SDValue Add =
4332 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4333 SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4334 if (MemVTs[i] != ValueVTs[i])
4335 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4336 SDValue St =
4337 DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4338 Alignment, MMOFlags, AAInfo);
4339 Chains[ChainI] = St;
4340 }
4341
4342 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4343 ArrayRef(Chains.data(), ChainI));
4344 setValue(&I, StoreNode);
4345 DAG.setRoot(StoreNode);
4346 }
4347
visitMaskedStore(const CallInst & I,bool IsCompressing)4348 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4349 bool IsCompressing) {
4350 SDLoc sdl = getCurSDLoc();
4351
4352 auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4353 MaybeAlign &Alignment) {
4354 // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4355 Src0 = I.getArgOperand(0);
4356 Ptr = I.getArgOperand(1);
4357 Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4358 Mask = I.getArgOperand(3);
4359 };
4360 auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4361 MaybeAlign &Alignment) {
4362 // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4363 Src0 = I.getArgOperand(0);
4364 Ptr = I.getArgOperand(1);
4365 Mask = I.getArgOperand(2);
4366 Alignment = std::nullopt;
4367 };
4368
4369 Value *PtrOperand, *MaskOperand, *Src0Operand;
4370 MaybeAlign Alignment;
4371 if (IsCompressing)
4372 getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4373 else
4374 getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4375
4376 SDValue Ptr = getValue(PtrOperand);
4377 SDValue Src0 = getValue(Src0Operand);
4378 SDValue Mask = getValue(MaskOperand);
4379 SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4380
4381 EVT VT = Src0.getValueType();
4382 if (!Alignment)
4383 Alignment = DAG.getEVTAlign(VT);
4384
4385 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4386 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4387 MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4388 SDValue StoreNode =
4389 DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4390 ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4391 DAG.setRoot(StoreNode);
4392 setValue(&I, StoreNode);
4393 }
4394
4395 // Get a uniform base for the Gather/Scatter intrinsic.
4396 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4397 // We try to represent it as a base pointer + vector of indices.
4398 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4399 // The first operand of the GEP may be a single pointer or a vector of pointers
4400 // Example:
4401 // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4402 // or
4403 // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
4404 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4405 //
4406 // When the first GEP operand is a single pointer - it is the uniform base we
4407 // are looking for. If first operand of the GEP is a splat vector - we
4408 // extract the splat value and use it as a uniform base.
4409 // In all other cases the function returns 'false'.
getUniformBase(const Value * Ptr,SDValue & Base,SDValue & Index,ISD::MemIndexType & IndexType,SDValue & Scale,SelectionDAGBuilder * SDB,const BasicBlock * CurBB,uint64_t ElemSize)4410 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4411 ISD::MemIndexType &IndexType, SDValue &Scale,
4412 SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4413 uint64_t ElemSize) {
4414 SelectionDAG& DAG = SDB->DAG;
4415 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4416 const DataLayout &DL = DAG.getDataLayout();
4417
4418 assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4419
4420 // Handle splat constant pointer.
4421 if (auto *C = dyn_cast<Constant>(Ptr)) {
4422 C = C->getSplatValue();
4423 if (!C)
4424 return false;
4425
4426 Base = SDB->getValue(C);
4427
4428 ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4429 EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4430 Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4431 IndexType = ISD::SIGNED_SCALED;
4432 Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4433 return true;
4434 }
4435
4436 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4437 if (!GEP || GEP->getParent() != CurBB)
4438 return false;
4439
4440 if (GEP->getNumOperands() != 2)
4441 return false;
4442
4443 const Value *BasePtr = GEP->getPointerOperand();
4444 const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4445
4446 // Make sure the base is scalar and the index is a vector.
4447 if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4448 return false;
4449
4450 uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4451
4452 // Target may not support the required addressing mode.
4453 if (ScaleVal != 1 &&
4454 !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4455 return false;
4456
4457 Base = SDB->getValue(BasePtr);
4458 Index = SDB->getValue(IndexVal);
4459 IndexType = ISD::SIGNED_SCALED;
4460
4461 Scale =
4462 DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4463 return true;
4464 }
4465
visitMaskedScatter(const CallInst & I)4466 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4467 SDLoc sdl = getCurSDLoc();
4468
4469 // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4470 const Value *Ptr = I.getArgOperand(1);
4471 SDValue Src0 = getValue(I.getArgOperand(0));
4472 SDValue Mask = getValue(I.getArgOperand(3));
4473 EVT VT = Src0.getValueType();
4474 Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4475 ->getMaybeAlignValue()
4476 .value_or(DAG.getEVTAlign(VT.getScalarType()));
4477 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4478
4479 SDValue Base;
4480 SDValue Index;
4481 ISD::MemIndexType IndexType;
4482 SDValue Scale;
4483 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4484 I.getParent(), VT.getScalarStoreSize());
4485
4486 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4487 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4488 MachinePointerInfo(AS), MachineMemOperand::MOStore,
4489 // TODO: Make MachineMemOperands aware of scalable
4490 // vectors.
4491 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4492 if (!UniformBase) {
4493 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4494 Index = getValue(Ptr);
4495 IndexType = ISD::SIGNED_SCALED;
4496 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4497 }
4498
4499 EVT IdxVT = Index.getValueType();
4500 EVT EltTy = IdxVT.getVectorElementType();
4501 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4502 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4503 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4504 }
4505
4506 SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4507 SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4508 Ops, MMO, IndexType, false);
4509 DAG.setRoot(Scatter);
4510 setValue(&I, Scatter);
4511 }
4512
visitMaskedLoad(const CallInst & I,bool IsExpanding)4513 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4514 SDLoc sdl = getCurSDLoc();
4515
4516 auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4517 MaybeAlign &Alignment) {
4518 // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4519 Ptr = I.getArgOperand(0);
4520 Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4521 Mask = I.getArgOperand(2);
4522 Src0 = I.getArgOperand(3);
4523 };
4524 auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4525 MaybeAlign &Alignment) {
4526 // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4527 Ptr = I.getArgOperand(0);
4528 Alignment = std::nullopt;
4529 Mask = I.getArgOperand(1);
4530 Src0 = I.getArgOperand(2);
4531 };
4532
4533 Value *PtrOperand, *MaskOperand, *Src0Operand;
4534 MaybeAlign Alignment;
4535 if (IsExpanding)
4536 getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4537 else
4538 getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4539
4540 SDValue Ptr = getValue(PtrOperand);
4541 SDValue Src0 = getValue(Src0Operand);
4542 SDValue Mask = getValue(MaskOperand);
4543 SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4544
4545 EVT VT = Src0.getValueType();
4546 if (!Alignment)
4547 Alignment = DAG.getEVTAlign(VT);
4548
4549 AAMDNodes AAInfo = I.getAAMetadata();
4550 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4551
4552 // Do not serialize masked loads of constant memory with anything.
4553 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4554 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4555
4556 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4557
4558 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4559 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4560 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4561
4562 SDValue Load =
4563 DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4564 ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4565 if (AddToChain)
4566 PendingLoads.push_back(Load.getValue(1));
4567 setValue(&I, Load);
4568 }
4569
visitMaskedGather(const CallInst & I)4570 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4571 SDLoc sdl = getCurSDLoc();
4572
4573 // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4574 const Value *Ptr = I.getArgOperand(0);
4575 SDValue Src0 = getValue(I.getArgOperand(3));
4576 SDValue Mask = getValue(I.getArgOperand(2));
4577
4578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4579 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4580 Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4581 ->getMaybeAlignValue()
4582 .value_or(DAG.getEVTAlign(VT.getScalarType()));
4583
4584 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4585
4586 SDValue Root = DAG.getRoot();
4587 SDValue Base;
4588 SDValue Index;
4589 ISD::MemIndexType IndexType;
4590 SDValue Scale;
4591 bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4592 I.getParent(), VT.getScalarStoreSize());
4593 unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4594 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4595 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4596 // TODO: Make MachineMemOperands aware of scalable
4597 // vectors.
4598 MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4599
4600 if (!UniformBase) {
4601 Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4602 Index = getValue(Ptr);
4603 IndexType = ISD::SIGNED_SCALED;
4604 Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4605 }
4606
4607 EVT IdxVT = Index.getValueType();
4608 EVT EltTy = IdxVT.getVectorElementType();
4609 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4610 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4611 Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4612 }
4613
4614 SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4615 SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4616 Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4617
4618 PendingLoads.push_back(Gather.getValue(1));
4619 setValue(&I, Gather);
4620 }
4621
visitAtomicCmpXchg(const AtomicCmpXchgInst & I)4622 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4623 SDLoc dl = getCurSDLoc();
4624 AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4625 AtomicOrdering FailureOrdering = I.getFailureOrdering();
4626 SyncScope::ID SSID = I.getSyncScopeID();
4627
4628 SDValue InChain = getRoot();
4629
4630 MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4631 SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4632
4633 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4634 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4635
4636 MachineFunction &MF = DAG.getMachineFunction();
4637 MachineMemOperand *MMO = MF.getMachineMemOperand(
4638 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4639 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4640 FailureOrdering);
4641
4642 SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4643 dl, MemVT, VTs, InChain,
4644 getValue(I.getPointerOperand()),
4645 getValue(I.getCompareOperand()),
4646 getValue(I.getNewValOperand()), MMO);
4647
4648 SDValue OutChain = L.getValue(2);
4649
4650 setValue(&I, L);
4651 DAG.setRoot(OutChain);
4652 }
4653
visitAtomicRMW(const AtomicRMWInst & I)4654 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4655 SDLoc dl = getCurSDLoc();
4656 ISD::NodeType NT;
4657 switch (I.getOperation()) {
4658 default: llvm_unreachable("Unknown atomicrmw operation");
4659 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4660 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
4661 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
4662 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
4663 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4664 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
4665 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
4666 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
4667 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
4668 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4669 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4670 case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4671 case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4672 case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4673 case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4674 case AtomicRMWInst::UIncWrap:
4675 NT = ISD::ATOMIC_LOAD_UINC_WRAP;
4676 break;
4677 case AtomicRMWInst::UDecWrap:
4678 NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
4679 break;
4680 }
4681 AtomicOrdering Ordering = I.getOrdering();
4682 SyncScope::ID SSID = I.getSyncScopeID();
4683
4684 SDValue InChain = getRoot();
4685
4686 auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4687 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4688 auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4689
4690 MachineFunction &MF = DAG.getMachineFunction();
4691 MachineMemOperand *MMO = MF.getMachineMemOperand(
4692 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4693 DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4694
4695 SDValue L =
4696 DAG.getAtomic(NT, dl, MemVT, InChain,
4697 getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4698 MMO);
4699
4700 SDValue OutChain = L.getValue(1);
4701
4702 setValue(&I, L);
4703 DAG.setRoot(OutChain);
4704 }
4705
visitFence(const FenceInst & I)4706 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4707 SDLoc dl = getCurSDLoc();
4708 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4709 SDValue Ops[3];
4710 Ops[0] = getRoot();
4711 Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4712 TLI.getFenceOperandTy(DAG.getDataLayout()));
4713 Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4714 TLI.getFenceOperandTy(DAG.getDataLayout()));
4715 SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4716 setValue(&I, N);
4717 DAG.setRoot(N);
4718 }
4719
visitAtomicLoad(const LoadInst & I)4720 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4721 SDLoc dl = getCurSDLoc();
4722 AtomicOrdering Order = I.getOrdering();
4723 SyncScope::ID SSID = I.getSyncScopeID();
4724
4725 SDValue InChain = getRoot();
4726
4727 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4728 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4729 EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4730
4731 if (!TLI.supportsUnalignedAtomics() &&
4732 I.getAlign().value() < MemVT.getSizeInBits() / 8)
4733 report_fatal_error("Cannot generate unaligned atomic load");
4734
4735 auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4736
4737 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4738 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4739 I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4740
4741 InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4742
4743 SDValue Ptr = getValue(I.getPointerOperand());
4744
4745 if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4746 // TODO: Once this is better exercised by tests, it should be merged with
4747 // the normal path for loads to prevent future divergence.
4748 SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4749 if (MemVT != VT)
4750 L = DAG.getPtrExtOrTrunc(L, dl, VT);
4751
4752 setValue(&I, L);
4753 SDValue OutChain = L.getValue(1);
4754 if (!I.isUnordered())
4755 DAG.setRoot(OutChain);
4756 else
4757 PendingLoads.push_back(OutChain);
4758 return;
4759 }
4760
4761 SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4762 Ptr, MMO);
4763
4764 SDValue OutChain = L.getValue(1);
4765 if (MemVT != VT)
4766 L = DAG.getPtrExtOrTrunc(L, dl, VT);
4767
4768 setValue(&I, L);
4769 DAG.setRoot(OutChain);
4770 }
4771
visitAtomicStore(const StoreInst & I)4772 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4773 SDLoc dl = getCurSDLoc();
4774
4775 AtomicOrdering Ordering = I.getOrdering();
4776 SyncScope::ID SSID = I.getSyncScopeID();
4777
4778 SDValue InChain = getRoot();
4779
4780 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4781 EVT MemVT =
4782 TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4783
4784 if (!TLI.supportsUnalignedAtomics() &&
4785 I.getAlign().value() < MemVT.getSizeInBits() / 8)
4786 report_fatal_error("Cannot generate unaligned atomic store");
4787
4788 auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4789
4790 MachineFunction &MF = DAG.getMachineFunction();
4791 MachineMemOperand *MMO = MF.getMachineMemOperand(
4792 MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4793 I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4794
4795 SDValue Val = getValue(I.getValueOperand());
4796 if (Val.getValueType() != MemVT)
4797 Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4798 SDValue Ptr = getValue(I.getPointerOperand());
4799
4800 if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4801 // TODO: Once this is better exercised by tests, it should be merged with
4802 // the normal path for stores to prevent future divergence.
4803 SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4804 setValue(&I, S);
4805 DAG.setRoot(S);
4806 return;
4807 }
4808 SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4809 Ptr, Val, MMO);
4810
4811 setValue(&I, OutChain);
4812 DAG.setRoot(OutChain);
4813 }
4814
4815 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4816 /// node.
visitTargetIntrinsic(const CallInst & I,unsigned Intrinsic)4817 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4818 unsigned Intrinsic) {
4819 // Ignore the callsite's attributes. A specific call site may be marked with
4820 // readnone, but the lowering code will expect the chain based on the
4821 // definition.
4822 const Function *F = I.getCalledFunction();
4823 bool HasChain = !F->doesNotAccessMemory();
4824 bool OnlyLoad = HasChain && F->onlyReadsMemory();
4825
4826 // Build the operand list.
4827 SmallVector<SDValue, 8> Ops;
4828 if (HasChain) { // If this intrinsic has side-effects, chainify it.
4829 if (OnlyLoad) {
4830 // We don't need to serialize loads against other loads.
4831 Ops.push_back(DAG.getRoot());
4832 } else {
4833 Ops.push_back(getRoot());
4834 }
4835 }
4836
4837 // Info is set by getTgtMemIntrinsic
4838 TargetLowering::IntrinsicInfo Info;
4839 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4840 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4841 DAG.getMachineFunction(),
4842 Intrinsic);
4843
4844 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4845 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4846 Info.opc == ISD::INTRINSIC_W_CHAIN)
4847 Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4848 TLI.getPointerTy(DAG.getDataLayout())));
4849
4850 // Add all operands of the call to the operand list.
4851 for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4852 const Value *Arg = I.getArgOperand(i);
4853 if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4854 Ops.push_back(getValue(Arg));
4855 continue;
4856 }
4857
4858 // Use TargetConstant instead of a regular constant for immarg.
4859 EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4860 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4861 assert(CI->getBitWidth() <= 64 &&
4862 "large intrinsic immediates not handled");
4863 Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4864 } else {
4865 Ops.push_back(
4866 DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4867 }
4868 }
4869
4870 SmallVector<EVT, 4> ValueVTs;
4871 ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4872
4873 if (HasChain)
4874 ValueVTs.push_back(MVT::Other);
4875
4876 SDVTList VTs = DAG.getVTList(ValueVTs);
4877
4878 // Propagate fast-math-flags from IR to node(s).
4879 SDNodeFlags Flags;
4880 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4881 Flags.copyFMF(*FPMO);
4882 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4883
4884 // Create the node.
4885 SDValue Result;
4886 // In some cases, custom collection of operands from CallInst I may be needed.
4887 TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4888 if (IsTgtIntrinsic) {
4889 // This is target intrinsic that touches memory
4890 //
4891 // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
4892 // didn't yield anything useful.
4893 MachinePointerInfo MPI;
4894 if (Info.ptrVal)
4895 MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
4896 else if (Info.fallbackAddressSpace)
4897 MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
4898 Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
4899 Info.memVT, MPI, Info.align, Info.flags,
4900 Info.size, I.getAAMetadata());
4901 } else if (!HasChain) {
4902 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4903 } else if (!I.getType()->isVoidTy()) {
4904 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4905 } else {
4906 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4907 }
4908
4909 if (HasChain) {
4910 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4911 if (OnlyLoad)
4912 PendingLoads.push_back(Chain);
4913 else
4914 DAG.setRoot(Chain);
4915 }
4916
4917 if (!I.getType()->isVoidTy()) {
4918 if (!isa<VectorType>(I.getType()))
4919 Result = lowerRangeToAssertZExt(DAG, I, Result);
4920
4921 MaybeAlign Alignment = I.getRetAlign();
4922 if (!Alignment)
4923 Alignment = F->getAttributes().getRetAlignment();
4924 // Insert `assertalign` node if there's an alignment.
4925 if (InsertAssertAlign && Alignment) {
4926 Result =
4927 DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4928 }
4929
4930 setValue(&I, Result);
4931 }
4932 }
4933
4934 /// GetSignificand - Get the significand and build it into a floating-point
4935 /// number with exponent of 1:
4936 ///
4937 /// Op = (Op & 0x007fffff) | 0x3f800000;
4938 ///
4939 /// where Op is the hexadecimal representation of floating point value.
GetSignificand(SelectionDAG & DAG,SDValue Op,const SDLoc & dl)4940 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4941 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4942 DAG.getConstant(0x007fffff, dl, MVT::i32));
4943 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4944 DAG.getConstant(0x3f800000, dl, MVT::i32));
4945 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4946 }
4947
4948 /// GetExponent - Get the exponent:
4949 ///
4950 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4951 ///
4952 /// where Op is the hexadecimal representation of floating point value.
GetExponent(SelectionDAG & DAG,SDValue Op,const TargetLowering & TLI,const SDLoc & dl)4953 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4954 const TargetLowering &TLI, const SDLoc &dl) {
4955 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4956 DAG.getConstant(0x7f800000, dl, MVT::i32));
4957 SDValue t1 = DAG.getNode(
4958 ISD::SRL, dl, MVT::i32, t0,
4959 DAG.getConstant(23, dl,
4960 TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4961 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4962 DAG.getConstant(127, dl, MVT::i32));
4963 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4964 }
4965
4966 /// getF32Constant - Get 32-bit floating point constant.
getF32Constant(SelectionDAG & DAG,unsigned Flt,const SDLoc & dl)4967 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4968 const SDLoc &dl) {
4969 return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4970 MVT::f32);
4971 }
4972
getLimitedPrecisionExp2(SDValue t0,const SDLoc & dl,SelectionDAG & DAG)4973 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4974 SelectionDAG &DAG) {
4975 // TODO: What fast-math-flags should be set on the floating-point nodes?
4976
4977 // IntegerPartOfX = ((int32_t)(t0);
4978 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4979
4980 // FractionalPartOfX = t0 - (float)IntegerPartOfX;
4981 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4982 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4983
4984 // IntegerPartOfX <<= 23;
4985 IntegerPartOfX =
4986 DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4987 DAG.getConstant(23, dl,
4988 DAG.getTargetLoweringInfo().getShiftAmountTy(
4989 MVT::i32, DAG.getDataLayout())));
4990
4991 SDValue TwoToFractionalPartOfX;
4992 if (LimitFloatPrecision <= 6) {
4993 // For floating-point precision of 6:
4994 //
4995 // TwoToFractionalPartOfX =
4996 // 0.997535578f +
4997 // (0.735607626f + 0.252464424f * x) * x;
4998 //
4999 // error 0.0144103317, which is 6 bits
5000 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5001 getF32Constant(DAG, 0x3e814304, dl));
5002 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5003 getF32Constant(DAG, 0x3f3c50c8, dl));
5004 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5005 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5006 getF32Constant(DAG, 0x3f7f5e7e, dl));
5007 } else if (LimitFloatPrecision <= 12) {
5008 // For floating-point precision of 12:
5009 //
5010 // TwoToFractionalPartOfX =
5011 // 0.999892986f +
5012 // (0.696457318f +
5013 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
5014 //
5015 // error 0.000107046256, which is 13 to 14 bits
5016 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5017 getF32Constant(DAG, 0x3da235e3, dl));
5018 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5019 getF32Constant(DAG, 0x3e65b8f3, dl));
5020 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5021 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5022 getF32Constant(DAG, 0x3f324b07, dl));
5023 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5024 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5025 getF32Constant(DAG, 0x3f7ff8fd, dl));
5026 } else { // LimitFloatPrecision <= 18
5027 // For floating-point precision of 18:
5028 //
5029 // TwoToFractionalPartOfX =
5030 // 0.999999982f +
5031 // (0.693148872f +
5032 // (0.240227044f +
5033 // (0.554906021e-1f +
5034 // (0.961591928e-2f +
5035 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5036 // error 2.47208000*10^(-7), which is better than 18 bits
5037 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5038 getF32Constant(DAG, 0x3924b03e, dl));
5039 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5040 getF32Constant(DAG, 0x3ab24b87, dl));
5041 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5042 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5043 getF32Constant(DAG, 0x3c1d8c17, dl));
5044 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5045 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5046 getF32Constant(DAG, 0x3d634a1d, dl));
5047 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5048 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5049 getF32Constant(DAG, 0x3e75fe14, dl));
5050 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5051 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5052 getF32Constant(DAG, 0x3f317234, dl));
5053 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5054 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5055 getF32Constant(DAG, 0x3f800000, dl));
5056 }
5057
5058 // Add the exponent into the result in integer domain.
5059 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5060 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5061 DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5062 }
5063
5064 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5065 /// limited-precision mode.
expandExp(const SDLoc & dl,SDValue Op,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5066 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5067 const TargetLowering &TLI, SDNodeFlags Flags) {
5068 if (Op.getValueType() == MVT::f32 &&
5069 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5070
5071 // Put the exponent in the right bit position for later addition to the
5072 // final result:
5073 //
5074 // t0 = Op * log2(e)
5075
5076 // TODO: What fast-math-flags should be set here?
5077 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5078 DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5079 return getLimitedPrecisionExp2(t0, dl, DAG);
5080 }
5081
5082 // No special expansion.
5083 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5084 }
5085
5086 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5087 /// limited-precision mode.
expandLog(const SDLoc & dl,SDValue Op,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5088 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5089 const TargetLowering &TLI, SDNodeFlags Flags) {
5090 // TODO: What fast-math-flags should be set on the floating-point nodes?
5091
5092 if (Op.getValueType() == MVT::f32 &&
5093 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5094 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5095
5096 // Scale the exponent by log(2).
5097 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5098 SDValue LogOfExponent =
5099 DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5100 DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5101
5102 // Get the significand and build it into a floating-point number with
5103 // exponent of 1.
5104 SDValue X = GetSignificand(DAG, Op1, dl);
5105
5106 SDValue LogOfMantissa;
5107 if (LimitFloatPrecision <= 6) {
5108 // For floating-point precision of 6:
5109 //
5110 // LogofMantissa =
5111 // -1.1609546f +
5112 // (1.4034025f - 0.23903021f * x) * x;
5113 //
5114 // error 0.0034276066, which is better than 8 bits
5115 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5116 getF32Constant(DAG, 0xbe74c456, dl));
5117 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5118 getF32Constant(DAG, 0x3fb3a2b1, dl));
5119 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5120 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5121 getF32Constant(DAG, 0x3f949a29, dl));
5122 } else if (LimitFloatPrecision <= 12) {
5123 // For floating-point precision of 12:
5124 //
5125 // LogOfMantissa =
5126 // -1.7417939f +
5127 // (2.8212026f +
5128 // (-1.4699568f +
5129 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5130 //
5131 // error 0.000061011436, which is 14 bits
5132 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5133 getF32Constant(DAG, 0xbd67b6d6, dl));
5134 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5135 getF32Constant(DAG, 0x3ee4f4b8, dl));
5136 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5137 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5138 getF32Constant(DAG, 0x3fbc278b, dl));
5139 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5140 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5141 getF32Constant(DAG, 0x40348e95, dl));
5142 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5143 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5144 getF32Constant(DAG, 0x3fdef31a, dl));
5145 } else { // LimitFloatPrecision <= 18
5146 // For floating-point precision of 18:
5147 //
5148 // LogOfMantissa =
5149 // -2.1072184f +
5150 // (4.2372794f +
5151 // (-3.7029485f +
5152 // (2.2781945f +
5153 // (-0.87823314f +
5154 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5155 //
5156 // error 0.0000023660568, which is better than 18 bits
5157 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5158 getF32Constant(DAG, 0xbc91e5ac, dl));
5159 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5160 getF32Constant(DAG, 0x3e4350aa, dl));
5161 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5162 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5163 getF32Constant(DAG, 0x3f60d3e3, dl));
5164 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5165 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5166 getF32Constant(DAG, 0x4011cdf0, dl));
5167 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5168 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5169 getF32Constant(DAG, 0x406cfd1c, dl));
5170 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5171 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5172 getF32Constant(DAG, 0x408797cb, dl));
5173 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5174 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5175 getF32Constant(DAG, 0x4006dcab, dl));
5176 }
5177
5178 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5179 }
5180
5181 // No special expansion.
5182 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5183 }
5184
5185 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5186 /// limited-precision mode.
expandLog2(const SDLoc & dl,SDValue Op,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5187 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5188 const TargetLowering &TLI, SDNodeFlags Flags) {
5189 // TODO: What fast-math-flags should be set on the floating-point nodes?
5190
5191 if (Op.getValueType() == MVT::f32 &&
5192 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5193 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5194
5195 // Get the exponent.
5196 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5197
5198 // Get the significand and build it into a floating-point number with
5199 // exponent of 1.
5200 SDValue X = GetSignificand(DAG, Op1, dl);
5201
5202 // Different possible minimax approximations of significand in
5203 // floating-point for various degrees of accuracy over [1,2].
5204 SDValue Log2ofMantissa;
5205 if (LimitFloatPrecision <= 6) {
5206 // For floating-point precision of 6:
5207 //
5208 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5209 //
5210 // error 0.0049451742, which is more than 7 bits
5211 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5212 getF32Constant(DAG, 0xbeb08fe0, dl));
5213 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5214 getF32Constant(DAG, 0x40019463, dl));
5215 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5216 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5217 getF32Constant(DAG, 0x3fd6633d, dl));
5218 } else if (LimitFloatPrecision <= 12) {
5219 // For floating-point precision of 12:
5220 //
5221 // Log2ofMantissa =
5222 // -2.51285454f +
5223 // (4.07009056f +
5224 // (-2.12067489f +
5225 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5226 //
5227 // error 0.0000876136000, which is better than 13 bits
5228 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5229 getF32Constant(DAG, 0xbda7262e, dl));
5230 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5231 getF32Constant(DAG, 0x3f25280b, dl));
5232 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5233 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5234 getF32Constant(DAG, 0x4007b923, dl));
5235 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5236 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5237 getF32Constant(DAG, 0x40823e2f, dl));
5238 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5239 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5240 getF32Constant(DAG, 0x4020d29c, dl));
5241 } else { // LimitFloatPrecision <= 18
5242 // For floating-point precision of 18:
5243 //
5244 // Log2ofMantissa =
5245 // -3.0400495f +
5246 // (6.1129976f +
5247 // (-5.3420409f +
5248 // (3.2865683f +
5249 // (-1.2669343f +
5250 // (0.27515199f -
5251 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5252 //
5253 // error 0.0000018516, which is better than 18 bits
5254 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5255 getF32Constant(DAG, 0xbcd2769e, dl));
5256 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5257 getF32Constant(DAG, 0x3e8ce0b9, dl));
5258 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5259 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5260 getF32Constant(DAG, 0x3fa22ae7, dl));
5261 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5262 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5263 getF32Constant(DAG, 0x40525723, dl));
5264 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5265 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5266 getF32Constant(DAG, 0x40aaf200, dl));
5267 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5268 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5269 getF32Constant(DAG, 0x40c39dad, dl));
5270 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5271 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5272 getF32Constant(DAG, 0x4042902c, dl));
5273 }
5274
5275 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5276 }
5277
5278 // No special expansion.
5279 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5280 }
5281
5282 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5283 /// limited-precision mode.
expandLog10(const SDLoc & dl,SDValue Op,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5284 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5285 const TargetLowering &TLI, SDNodeFlags Flags) {
5286 // TODO: What fast-math-flags should be set on the floating-point nodes?
5287
5288 if (Op.getValueType() == MVT::f32 &&
5289 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5290 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5291
5292 // Scale the exponent by log10(2) [0.30102999f].
5293 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5294 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5295 getF32Constant(DAG, 0x3e9a209a, dl));
5296
5297 // Get the significand and build it into a floating-point number with
5298 // exponent of 1.
5299 SDValue X = GetSignificand(DAG, Op1, dl);
5300
5301 SDValue Log10ofMantissa;
5302 if (LimitFloatPrecision <= 6) {
5303 // For floating-point precision of 6:
5304 //
5305 // Log10ofMantissa =
5306 // -0.50419619f +
5307 // (0.60948995f - 0.10380950f * x) * x;
5308 //
5309 // error 0.0014886165, which is 6 bits
5310 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5311 getF32Constant(DAG, 0xbdd49a13, dl));
5312 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5313 getF32Constant(DAG, 0x3f1c0789, dl));
5314 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5315 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5316 getF32Constant(DAG, 0x3f011300, dl));
5317 } else if (LimitFloatPrecision <= 12) {
5318 // For floating-point precision of 12:
5319 //
5320 // Log10ofMantissa =
5321 // -0.64831180f +
5322 // (0.91751397f +
5323 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5324 //
5325 // error 0.00019228036, which is better than 12 bits
5326 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5327 getF32Constant(DAG, 0x3d431f31, dl));
5328 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5329 getF32Constant(DAG, 0x3ea21fb2, dl));
5330 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5331 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5332 getF32Constant(DAG, 0x3f6ae232, dl));
5333 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5334 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5335 getF32Constant(DAG, 0x3f25f7c3, dl));
5336 } else { // LimitFloatPrecision <= 18
5337 // For floating-point precision of 18:
5338 //
5339 // Log10ofMantissa =
5340 // -0.84299375f +
5341 // (1.5327582f +
5342 // (-1.0688956f +
5343 // (0.49102474f +
5344 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5345 //
5346 // error 0.0000037995730, which is better than 18 bits
5347 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5348 getF32Constant(DAG, 0x3c5d51ce, dl));
5349 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5350 getF32Constant(DAG, 0x3e00685a, dl));
5351 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5352 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5353 getF32Constant(DAG, 0x3efb6798, dl));
5354 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5355 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5356 getF32Constant(DAG, 0x3f88d192, dl));
5357 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5358 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5359 getF32Constant(DAG, 0x3fc4316c, dl));
5360 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5361 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5362 getF32Constant(DAG, 0x3f57ce70, dl));
5363 }
5364
5365 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5366 }
5367
5368 // No special expansion.
5369 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5370 }
5371
5372 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5373 /// limited-precision mode.
expandExp2(const SDLoc & dl,SDValue Op,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5374 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5375 const TargetLowering &TLI, SDNodeFlags Flags) {
5376 if (Op.getValueType() == MVT::f32 &&
5377 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5378 return getLimitedPrecisionExp2(Op, dl, DAG);
5379
5380 // No special expansion.
5381 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5382 }
5383
5384 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5385 /// limited-precision mode with x == 10.0f.
expandPow(const SDLoc & dl,SDValue LHS,SDValue RHS,SelectionDAG & DAG,const TargetLowering & TLI,SDNodeFlags Flags)5386 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5387 SelectionDAG &DAG, const TargetLowering &TLI,
5388 SDNodeFlags Flags) {
5389 bool IsExp10 = false;
5390 if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5391 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5392 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5393 APFloat Ten(10.0f);
5394 IsExp10 = LHSC->isExactlyValue(Ten);
5395 }
5396 }
5397
5398 // TODO: What fast-math-flags should be set on the FMUL node?
5399 if (IsExp10) {
5400 // Put the exponent in the right bit position for later addition to the
5401 // final result:
5402 //
5403 // #define LOG2OF10 3.3219281f
5404 // t0 = Op * LOG2OF10;
5405 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5406 getF32Constant(DAG, 0x40549a78, dl));
5407 return getLimitedPrecisionExp2(t0, dl, DAG);
5408 }
5409
5410 // No special expansion.
5411 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5412 }
5413
5414 /// ExpandPowI - Expand a llvm.powi intrinsic.
ExpandPowI(const SDLoc & DL,SDValue LHS,SDValue RHS,SelectionDAG & DAG)5415 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5416 SelectionDAG &DAG) {
5417 // If RHS is a constant, we can expand this out to a multiplication tree if
5418 // it's beneficial on the target, otherwise we end up lowering to a call to
5419 // __powidf2 (for example).
5420 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5421 unsigned Val = RHSC->getSExtValue();
5422
5423 // powi(x, 0) -> 1.0
5424 if (Val == 0)
5425 return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5426
5427 if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5428 Val, DAG.shouldOptForSize())) {
5429 // Get the exponent as a positive value.
5430 if ((int)Val < 0)
5431 Val = -Val;
5432 // We use the simple binary decomposition method to generate the multiply
5433 // sequence. There are more optimal ways to do this (for example,
5434 // powi(x,15) generates one more multiply than it should), but this has
5435 // the benefit of being both really simple and much better than a libcall.
5436 SDValue Res; // Logically starts equal to 1.0
5437 SDValue CurSquare = LHS;
5438 // TODO: Intrinsics should have fast-math-flags that propagate to these
5439 // nodes.
5440 while (Val) {
5441 if (Val & 1) {
5442 if (Res.getNode())
5443 Res =
5444 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5445 else
5446 Res = CurSquare; // 1.0*CurSquare.
5447 }
5448
5449 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5450 CurSquare, CurSquare);
5451 Val >>= 1;
5452 }
5453
5454 // If the original was negative, invert the result, producing 1/(x*x*x).
5455 if (RHSC->getSExtValue() < 0)
5456 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5457 DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5458 return Res;
5459 }
5460 }
5461
5462 // Otherwise, expand to a libcall.
5463 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5464 }
5465
expandDivFix(unsigned Opcode,const SDLoc & DL,SDValue LHS,SDValue RHS,SDValue Scale,SelectionDAG & DAG,const TargetLowering & TLI)5466 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5467 SDValue LHS, SDValue RHS, SDValue Scale,
5468 SelectionDAG &DAG, const TargetLowering &TLI) {
5469 EVT VT = LHS.getValueType();
5470 bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5471 bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5472 LLVMContext &Ctx = *DAG.getContext();
5473
5474 // If the type is legal but the operation isn't, this node might survive all
5475 // the way to operation legalization. If we end up there and we do not have
5476 // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5477 // node.
5478
5479 // Coax the legalizer into expanding the node during type legalization instead
5480 // by bumping the size by one bit. This will force it to Promote, enabling the
5481 // early expansion and avoiding the need to expand later.
5482
5483 // We don't have to do this if Scale is 0; that can always be expanded, unless
5484 // it's a saturating signed operation. Those can experience true integer
5485 // division overflow, a case which we must avoid.
5486
5487 // FIXME: We wouldn't have to do this (or any of the early
5488 // expansion/promotion) if it was possible to expand a libcall of an
5489 // illegal type during operation legalization. But it's not, so things
5490 // get a bit hacky.
5491 unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5492 if ((ScaleInt > 0 || (Saturating && Signed)) &&
5493 (TLI.isTypeLegal(VT) ||
5494 (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5495 TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5496 Opcode, VT, ScaleInt);
5497 if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5498 EVT PromVT;
5499 if (VT.isScalarInteger())
5500 PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5501 else if (VT.isVector()) {
5502 PromVT = VT.getVectorElementType();
5503 PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5504 PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5505 } else
5506 llvm_unreachable("Wrong VT for DIVFIX?");
5507 if (Signed) {
5508 LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5509 RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5510 } else {
5511 LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5512 RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5513 }
5514 EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5515 // For saturating operations, we need to shift up the LHS to get the
5516 // proper saturation width, and then shift down again afterwards.
5517 if (Saturating)
5518 LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5519 DAG.getConstant(1, DL, ShiftTy));
5520 SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5521 if (Saturating)
5522 Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5523 DAG.getConstant(1, DL, ShiftTy));
5524 return DAG.getZExtOrTrunc(Res, DL, VT);
5525 }
5526 }
5527
5528 return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5529 }
5530
5531 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5532 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5533 static void
getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned,TypeSize>> & Regs,const SDValue & N)5534 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5535 const SDValue &N) {
5536 switch (N.getOpcode()) {
5537 case ISD::CopyFromReg: {
5538 SDValue Op = N.getOperand(1);
5539 Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5540 Op.getValueType().getSizeInBits());
5541 return;
5542 }
5543 case ISD::BITCAST:
5544 case ISD::AssertZext:
5545 case ISD::AssertSext:
5546 case ISD::TRUNCATE:
5547 getUnderlyingArgRegs(Regs, N.getOperand(0));
5548 return;
5549 case ISD::BUILD_PAIR:
5550 case ISD::BUILD_VECTOR:
5551 case ISD::CONCAT_VECTORS:
5552 for (SDValue Op : N->op_values())
5553 getUnderlyingArgRegs(Regs, Op);
5554 return;
5555 default:
5556 return;
5557 }
5558 }
5559
5560 /// If the DbgValueInst is a dbg_value of a function argument, create the
5561 /// corresponding DBG_VALUE machine instruction for it now. At the end of
5562 /// instruction selection, they will be inserted to the entry BB.
5563 /// We don't currently support this for variadic dbg_values, as they shouldn't
5564 /// appear for function arguments or in the prologue.
EmitFuncArgumentDbgValue(const Value * V,DILocalVariable * Variable,DIExpression * Expr,DILocation * DL,FuncArgumentDbgValueKind Kind,const SDValue & N)5565 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5566 const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5567 DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5568 const Argument *Arg = dyn_cast<Argument>(V);
5569 if (!Arg)
5570 return false;
5571
5572 MachineFunction &MF = DAG.getMachineFunction();
5573 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5574
5575 // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5576 // we've been asked to pursue.
5577 auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5578 bool Indirect) {
5579 if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5580 // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5581 // pointing at the VReg, which will be patched up later.
5582 auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5583 SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5584 /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5585 /* isKill */ false, /* isDead */ false,
5586 /* isUndef */ false, /* isEarlyClobber */ false,
5587 /* SubReg */ 0, /* isDebug */ true)});
5588
5589 auto *NewDIExpr = FragExpr;
5590 // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5591 // the DIExpression.
5592 if (Indirect)
5593 NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5594 SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5595 NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5596 return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5597 } else {
5598 // Create a completely standard DBG_VALUE.
5599 auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5600 return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5601 }
5602 };
5603
5604 if (Kind == FuncArgumentDbgValueKind::Value) {
5605 // ArgDbgValues are hoisted to the beginning of the entry block. So we
5606 // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5607 // the entry block.
5608 bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5609 if (!IsInEntryBlock)
5610 return false;
5611
5612 // ArgDbgValues are hoisted to the beginning of the entry block. So we
5613 // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5614 // variable that also is a param.
5615 //
5616 // Although, if we are at the top of the entry block already, we can still
5617 // emit using ArgDbgValue. This might catch some situations when the
5618 // dbg.value refers to an argument that isn't used in the entry block, so
5619 // any CopyToReg node would be optimized out and the only way to express
5620 // this DBG_VALUE is by using the physical reg (or FI) as done in this
5621 // method. ArgDbgValues are hoisted to the beginning of the entry block. So
5622 // we should only emit as ArgDbgValue if the Variable is an argument to the
5623 // current function, and the dbg.value intrinsic is found in the entry
5624 // block.
5625 bool VariableIsFunctionInputArg = Variable->isParameter() &&
5626 !DL->getInlinedAt();
5627 bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5628 if (!IsInPrologue && !VariableIsFunctionInputArg)
5629 return false;
5630
5631 // Here we assume that a function argument on IR level only can be used to
5632 // describe one input parameter on source level. If we for example have
5633 // source code like this
5634 //
5635 // struct A { long x, y; };
5636 // void foo(struct A a, long b) {
5637 // ...
5638 // b = a.x;
5639 // ...
5640 // }
5641 //
5642 // and IR like this
5643 //
5644 // define void @foo(i32 %a1, i32 %a2, i32 %b) {
5645 // entry:
5646 // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5647 // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5648 // call void @llvm.dbg.value(metadata i32 %b, "b",
5649 // ...
5650 // call void @llvm.dbg.value(metadata i32 %a1, "b"
5651 // ...
5652 //
5653 // then the last dbg.value is describing a parameter "b" using a value that
5654 // is an argument. But since we already has used %a1 to describe a parameter
5655 // we should not handle that last dbg.value here (that would result in an
5656 // incorrect hoisting of the DBG_VALUE to the function entry).
5657 // Notice that we allow one dbg.value per IR level argument, to accommodate
5658 // for the situation with fragments above.
5659 if (VariableIsFunctionInputArg) {
5660 unsigned ArgNo = Arg->getArgNo();
5661 if (ArgNo >= FuncInfo.DescribedArgs.size())
5662 FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5663 else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5664 return false;
5665 FuncInfo.DescribedArgs.set(ArgNo);
5666 }
5667 }
5668
5669 bool IsIndirect = false;
5670 std::optional<MachineOperand> Op;
5671 // Some arguments' frame index is recorded during argument lowering.
5672 int FI = FuncInfo.getArgumentFrameIndex(Arg);
5673 if (FI != std::numeric_limits<int>::max())
5674 Op = MachineOperand::CreateFI(FI);
5675
5676 SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5677 if (!Op && N.getNode()) {
5678 getUnderlyingArgRegs(ArgRegsAndSizes, N);
5679 Register Reg;
5680 if (ArgRegsAndSizes.size() == 1)
5681 Reg = ArgRegsAndSizes.front().first;
5682
5683 if (Reg && Reg.isVirtual()) {
5684 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5685 Register PR = RegInfo.getLiveInPhysReg(Reg);
5686 if (PR)
5687 Reg = PR;
5688 }
5689 if (Reg) {
5690 Op = MachineOperand::CreateReg(Reg, false);
5691 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5692 }
5693 }
5694
5695 if (!Op && N.getNode()) {
5696 // Check if frame index is available.
5697 SDValue LCandidate = peekThroughBitcasts(N);
5698 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5699 if (FrameIndexSDNode *FINode =
5700 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5701 Op = MachineOperand::CreateFI(FINode->getIndex());
5702 }
5703
5704 if (!Op) {
5705 // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5706 auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5707 SplitRegs) {
5708 unsigned Offset = 0;
5709 for (const auto &RegAndSize : SplitRegs) {
5710 // If the expression is already a fragment, the current register
5711 // offset+size might extend beyond the fragment. In this case, only
5712 // the register bits that are inside the fragment are relevant.
5713 int RegFragmentSizeInBits = RegAndSize.second;
5714 if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5715 uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5716 // The register is entirely outside the expression fragment,
5717 // so is irrelevant for debug info.
5718 if (Offset >= ExprFragmentSizeInBits)
5719 break;
5720 // The register is partially outside the expression fragment, only
5721 // the low bits within the fragment are relevant for debug info.
5722 if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5723 RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5724 }
5725 }
5726
5727 auto FragmentExpr = DIExpression::createFragmentExpression(
5728 Expr, Offset, RegFragmentSizeInBits);
5729 Offset += RegAndSize.second;
5730 // If a valid fragment expression cannot be created, the variable's
5731 // correct value cannot be determined and so it is set as Undef.
5732 if (!FragmentExpr) {
5733 SDDbgValue *SDV = DAG.getConstantDbgValue(
5734 Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5735 DAG.AddDbgValue(SDV, false);
5736 continue;
5737 }
5738 MachineInstr *NewMI =
5739 MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5740 Kind != FuncArgumentDbgValueKind::Value);
5741 FuncInfo.ArgDbgValues.push_back(NewMI);
5742 }
5743 };
5744
5745 // Check if ValueMap has reg number.
5746 DenseMap<const Value *, Register>::const_iterator
5747 VMI = FuncInfo.ValueMap.find(V);
5748 if (VMI != FuncInfo.ValueMap.end()) {
5749 const auto &TLI = DAG.getTargetLoweringInfo();
5750 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5751 V->getType(), std::nullopt);
5752 if (RFV.occupiesMultipleRegs()) {
5753 splitMultiRegDbgValue(RFV.getRegsAndSizes());
5754 return true;
5755 }
5756
5757 Op = MachineOperand::CreateReg(VMI->second, false);
5758 IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5759 } else if (ArgRegsAndSizes.size() > 1) {
5760 // This was split due to the calling convention, and no virtual register
5761 // mapping exists for the value.
5762 splitMultiRegDbgValue(ArgRegsAndSizes);
5763 return true;
5764 }
5765 }
5766
5767 if (!Op)
5768 return false;
5769
5770 assert(Variable->isValidLocationForIntrinsic(DL) &&
5771 "Expected inlined-at fields to agree");
5772 MachineInstr *NewMI = nullptr;
5773
5774 if (Op->isReg())
5775 NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5776 else
5777 NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5778 Variable, Expr);
5779
5780 // Otherwise, use ArgDbgValues.
5781 FuncInfo.ArgDbgValues.push_back(NewMI);
5782 return true;
5783 }
5784
5785 /// Return the appropriate SDDbgValue based on N.
getDbgValue(SDValue N,DILocalVariable * Variable,DIExpression * Expr,const DebugLoc & dl,unsigned DbgSDNodeOrder)5786 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5787 DILocalVariable *Variable,
5788 DIExpression *Expr,
5789 const DebugLoc &dl,
5790 unsigned DbgSDNodeOrder) {
5791 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5792 // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5793 // stack slot locations.
5794 //
5795 // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5796 // debug values here after optimization:
5797 //
5798 // dbg.value(i32* %px, !"int *px", !DIExpression()), and
5799 // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5800 //
5801 // Both describe the direct values of their associated variables.
5802 return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5803 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5804 }
5805 return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5806 /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5807 }
5808
FixedPointIntrinsicToOpcode(unsigned Intrinsic)5809 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5810 switch (Intrinsic) {
5811 case Intrinsic::smul_fix:
5812 return ISD::SMULFIX;
5813 case Intrinsic::umul_fix:
5814 return ISD::UMULFIX;
5815 case Intrinsic::smul_fix_sat:
5816 return ISD::SMULFIXSAT;
5817 case Intrinsic::umul_fix_sat:
5818 return ISD::UMULFIXSAT;
5819 case Intrinsic::sdiv_fix:
5820 return ISD::SDIVFIX;
5821 case Intrinsic::udiv_fix:
5822 return ISD::UDIVFIX;
5823 case Intrinsic::sdiv_fix_sat:
5824 return ISD::SDIVFIXSAT;
5825 case Intrinsic::udiv_fix_sat:
5826 return ISD::UDIVFIXSAT;
5827 default:
5828 llvm_unreachable("Unhandled fixed point intrinsic");
5829 }
5830 }
5831
lowerCallToExternalSymbol(const CallInst & I,const char * FunctionName)5832 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5833 const char *FunctionName) {
5834 assert(FunctionName && "FunctionName must not be nullptr");
5835 SDValue Callee = DAG.getExternalSymbol(
5836 FunctionName,
5837 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5838 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5839 }
5840
5841 /// Given a @llvm.call.preallocated.setup, return the corresponding
5842 /// preallocated call.
FindPreallocatedCall(const Value * PreallocatedSetup)5843 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5844 assert(cast<CallBase>(PreallocatedSetup)
5845 ->getCalledFunction()
5846 ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5847 "expected call_preallocated_setup Value");
5848 for (const auto *U : PreallocatedSetup->users()) {
5849 auto *UseCall = cast<CallBase>(U);
5850 const Function *Fn = UseCall->getCalledFunction();
5851 if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5852 return UseCall;
5853 }
5854 }
5855 llvm_unreachable("expected corresponding call to preallocated setup/arg");
5856 }
5857
5858 /// Lower the call to the specified intrinsic function.
visitIntrinsicCall(const CallInst & I,unsigned Intrinsic)5859 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5860 unsigned Intrinsic) {
5861 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5862 SDLoc sdl = getCurSDLoc();
5863 DebugLoc dl = getCurDebugLoc();
5864 SDValue Res;
5865
5866 SDNodeFlags Flags;
5867 if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5868 Flags.copyFMF(*FPOp);
5869
5870 switch (Intrinsic) {
5871 default:
5872 // By default, turn this into a target intrinsic node.
5873 visitTargetIntrinsic(I, Intrinsic);
5874 return;
5875 case Intrinsic::vscale: {
5876 match(&I, m_VScale(DAG.getDataLayout()));
5877 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5878 setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5879 return;
5880 }
5881 case Intrinsic::vastart: visitVAStart(I); return;
5882 case Intrinsic::vaend: visitVAEnd(I); return;
5883 case Intrinsic::vacopy: visitVACopy(I); return;
5884 case Intrinsic::returnaddress:
5885 setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5886 TLI.getValueType(DAG.getDataLayout(), I.getType()),
5887 getValue(I.getArgOperand(0))));
5888 return;
5889 case Intrinsic::addressofreturnaddress:
5890 setValue(&I,
5891 DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5892 TLI.getValueType(DAG.getDataLayout(), I.getType())));
5893 return;
5894 case Intrinsic::sponentry:
5895 setValue(&I,
5896 DAG.getNode(ISD::SPONENTRY, sdl,
5897 TLI.getValueType(DAG.getDataLayout(), I.getType())));
5898 return;
5899 case Intrinsic::frameaddress:
5900 setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5901 TLI.getFrameIndexTy(DAG.getDataLayout()),
5902 getValue(I.getArgOperand(0))));
5903 return;
5904 case Intrinsic::read_volatile_register:
5905 case Intrinsic::read_register: {
5906 Value *Reg = I.getArgOperand(0);
5907 SDValue Chain = getRoot();
5908 SDValue RegName =
5909 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5910 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5911 Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5912 DAG.getVTList(VT, MVT::Other), Chain, RegName);
5913 setValue(&I, Res);
5914 DAG.setRoot(Res.getValue(1));
5915 return;
5916 }
5917 case Intrinsic::write_register: {
5918 Value *Reg = I.getArgOperand(0);
5919 Value *RegValue = I.getArgOperand(1);
5920 SDValue Chain = getRoot();
5921 SDValue RegName =
5922 DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5923 DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5924 RegName, getValue(RegValue)));
5925 return;
5926 }
5927 case Intrinsic::memcpy: {
5928 const auto &MCI = cast<MemCpyInst>(I);
5929 SDValue Op1 = getValue(I.getArgOperand(0));
5930 SDValue Op2 = getValue(I.getArgOperand(1));
5931 SDValue Op3 = getValue(I.getArgOperand(2));
5932 // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5933 Align DstAlign = MCI.getDestAlign().valueOrOne();
5934 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5935 Align Alignment = std::min(DstAlign, SrcAlign);
5936 bool isVol = MCI.isVolatile();
5937 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5938 // FIXME: Support passing different dest/src alignments to the memcpy DAG
5939 // node.
5940 SDValue Root = isVol ? getRoot() : getMemoryRoot();
5941 SDValue MC = DAG.getMemcpy(
5942 Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5943 /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
5944 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5945 updateDAGForMaybeTailCall(MC);
5946 return;
5947 }
5948 case Intrinsic::memcpy_inline: {
5949 const auto &MCI = cast<MemCpyInlineInst>(I);
5950 SDValue Dst = getValue(I.getArgOperand(0));
5951 SDValue Src = getValue(I.getArgOperand(1));
5952 SDValue Size = getValue(I.getArgOperand(2));
5953 assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5954 // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5955 Align DstAlign = MCI.getDestAlign().valueOrOne();
5956 Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5957 Align Alignment = std::min(DstAlign, SrcAlign);
5958 bool isVol = MCI.isVolatile();
5959 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5960 // FIXME: Support passing different dest/src alignments to the memcpy DAG
5961 // node.
5962 SDValue MC = DAG.getMemcpy(
5963 getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5964 /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
5965 MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5966 updateDAGForMaybeTailCall(MC);
5967 return;
5968 }
5969 case Intrinsic::memset: {
5970 const auto &MSI = cast<MemSetInst>(I);
5971 SDValue Op1 = getValue(I.getArgOperand(0));
5972 SDValue Op2 = getValue(I.getArgOperand(1));
5973 SDValue Op3 = getValue(I.getArgOperand(2));
5974 // @llvm.memset defines 0 and 1 to both mean no alignment.
5975 Align Alignment = MSI.getDestAlign().valueOrOne();
5976 bool isVol = MSI.isVolatile();
5977 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5978 SDValue Root = isVol ? getRoot() : getMemoryRoot();
5979 SDValue MS = DAG.getMemset(
5980 Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
5981 isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
5982 updateDAGForMaybeTailCall(MS);
5983 return;
5984 }
5985 case Intrinsic::memset_inline: {
5986 const auto &MSII = cast<MemSetInlineInst>(I);
5987 SDValue Dst = getValue(I.getArgOperand(0));
5988 SDValue Value = getValue(I.getArgOperand(1));
5989 SDValue Size = getValue(I.getArgOperand(2));
5990 assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
5991 // @llvm.memset defines 0 and 1 to both mean no alignment.
5992 Align DstAlign = MSII.getDestAlign().valueOrOne();
5993 bool isVol = MSII.isVolatile();
5994 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5995 SDValue Root = isVol ? getRoot() : getMemoryRoot();
5996 SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
5997 /* AlwaysInline */ true, isTC,
5998 MachinePointerInfo(I.getArgOperand(0)),
5999 I.getAAMetadata());
6000 updateDAGForMaybeTailCall(MC);
6001 return;
6002 }
6003 case Intrinsic::memmove: {
6004 const auto &MMI = cast<MemMoveInst>(I);
6005 SDValue Op1 = getValue(I.getArgOperand(0));
6006 SDValue Op2 = getValue(I.getArgOperand(1));
6007 SDValue Op3 = getValue(I.getArgOperand(2));
6008 // @llvm.memmove defines 0 and 1 to both mean no alignment.
6009 Align DstAlign = MMI.getDestAlign().valueOrOne();
6010 Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6011 Align Alignment = std::min(DstAlign, SrcAlign);
6012 bool isVol = MMI.isVolatile();
6013 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6014 // FIXME: Support passing different dest/src alignments to the memmove DAG
6015 // node.
6016 SDValue Root = isVol ? getRoot() : getMemoryRoot();
6017 SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6018 isTC, MachinePointerInfo(I.getArgOperand(0)),
6019 MachinePointerInfo(I.getArgOperand(1)),
6020 I.getAAMetadata(), AA);
6021 updateDAGForMaybeTailCall(MM);
6022 return;
6023 }
6024 case Intrinsic::memcpy_element_unordered_atomic: {
6025 const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6026 SDValue Dst = getValue(MI.getRawDest());
6027 SDValue Src = getValue(MI.getRawSource());
6028 SDValue Length = getValue(MI.getLength());
6029
6030 Type *LengthTy = MI.getLength()->getType();
6031 unsigned ElemSz = MI.getElementSizeInBytes();
6032 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6033 SDValue MC =
6034 DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6035 isTC, MachinePointerInfo(MI.getRawDest()),
6036 MachinePointerInfo(MI.getRawSource()));
6037 updateDAGForMaybeTailCall(MC);
6038 return;
6039 }
6040 case Intrinsic::memmove_element_unordered_atomic: {
6041 auto &MI = cast<AtomicMemMoveInst>(I);
6042 SDValue Dst = getValue(MI.getRawDest());
6043 SDValue Src = getValue(MI.getRawSource());
6044 SDValue Length = getValue(MI.getLength());
6045
6046 Type *LengthTy = MI.getLength()->getType();
6047 unsigned ElemSz = MI.getElementSizeInBytes();
6048 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6049 SDValue MC =
6050 DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6051 isTC, MachinePointerInfo(MI.getRawDest()),
6052 MachinePointerInfo(MI.getRawSource()));
6053 updateDAGForMaybeTailCall(MC);
6054 return;
6055 }
6056 case Intrinsic::memset_element_unordered_atomic: {
6057 auto &MI = cast<AtomicMemSetInst>(I);
6058 SDValue Dst = getValue(MI.getRawDest());
6059 SDValue Val = getValue(MI.getValue());
6060 SDValue Length = getValue(MI.getLength());
6061
6062 Type *LengthTy = MI.getLength()->getType();
6063 unsigned ElemSz = MI.getElementSizeInBytes();
6064 bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6065 SDValue MC =
6066 DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6067 isTC, MachinePointerInfo(MI.getRawDest()));
6068 updateDAGForMaybeTailCall(MC);
6069 return;
6070 }
6071 case Intrinsic::call_preallocated_setup: {
6072 const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6073 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6074 SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6075 getRoot(), SrcValue);
6076 setValue(&I, Res);
6077 DAG.setRoot(Res);
6078 return;
6079 }
6080 case Intrinsic::call_preallocated_arg: {
6081 const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6082 SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6083 SDValue Ops[3];
6084 Ops[0] = getRoot();
6085 Ops[1] = SrcValue;
6086 Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6087 MVT::i32); // arg index
6088 SDValue Res = DAG.getNode(
6089 ISD::PREALLOCATED_ARG, sdl,
6090 DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6091 setValue(&I, Res);
6092 DAG.setRoot(Res.getValue(1));
6093 return;
6094 }
6095 case Intrinsic::dbg_addr:
6096 case Intrinsic::dbg_declare: {
6097 // Debug intrinsics are handled seperately in assignment tracking mode.
6098 if (isAssignmentTrackingEnabled(*I.getFunction()->getParent()))
6099 return;
6100 // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6101 // they are non-variadic.
6102 const auto &DI = cast<DbgVariableIntrinsic>(I);
6103 assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6104 DILocalVariable *Variable = DI.getVariable();
6105 DIExpression *Expression = DI.getExpression();
6106 dropDanglingDebugInfo(Variable, Expression);
6107 assert(Variable && "Missing variable");
6108 LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6109 << "\n");
6110 // Check if address has undef value.
6111 const Value *Address = DI.getVariableLocationOp(0);
6112 if (!Address || isa<UndefValue>(Address) ||
6113 (Address->use_empty() && !isa<Argument>(Address))) {
6114 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6115 << " (bad/undef/unused-arg address)\n");
6116 return;
6117 }
6118
6119 bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6120
6121 // Check if this variable can be described by a frame index, typically
6122 // either as a static alloca or a byval parameter.
6123 int FI = std::numeric_limits<int>::max();
6124 if (const auto *AI =
6125 dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6126 if (AI->isStaticAlloca()) {
6127 auto I = FuncInfo.StaticAllocaMap.find(AI);
6128 if (I != FuncInfo.StaticAllocaMap.end())
6129 FI = I->second;
6130 }
6131 } else if (const auto *Arg = dyn_cast<Argument>(
6132 Address->stripInBoundsConstantOffsets())) {
6133 FI = FuncInfo.getArgumentFrameIndex(Arg);
6134 }
6135
6136 // llvm.dbg.addr is control dependent and always generates indirect
6137 // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6138 // the MachineFunction variable table.
6139 if (FI != std::numeric_limits<int>::max()) {
6140 if (Intrinsic == Intrinsic::dbg_addr) {
6141 SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6142 Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6143 dl, SDNodeOrder);
6144 DAG.AddDbgValue(SDV, isParameter);
6145 } else {
6146 LLVM_DEBUG(dbgs() << "Skipping " << DI
6147 << " (variable info stashed in MF side table)\n");
6148 }
6149 return;
6150 }
6151
6152 SDValue &N = NodeMap[Address];
6153 if (!N.getNode() && isa<Argument>(Address))
6154 // Check unused arguments map.
6155 N = UnusedArgNodeMap[Address];
6156 SDDbgValue *SDV;
6157 if (N.getNode()) {
6158 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6159 Address = BCI->getOperand(0);
6160 // Parameters are handled specially.
6161 auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6162 if (isParameter && FINode) {
6163 // Byval parameter. We have a frame index at this point.
6164 SDV =
6165 DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6166 /*IsIndirect*/ true, dl, SDNodeOrder);
6167 } else if (isa<Argument>(Address)) {
6168 // Address is an argument, so try to emit its dbg value using
6169 // virtual register info from the FuncInfo.ValueMap.
6170 EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6171 FuncArgumentDbgValueKind::Declare, N);
6172 return;
6173 } else {
6174 SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6175 true, dl, SDNodeOrder);
6176 }
6177 DAG.AddDbgValue(SDV, isParameter);
6178 } else {
6179 // If Address is an argument then try to emit its dbg value using
6180 // virtual register info from the FuncInfo.ValueMap.
6181 if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6182 FuncArgumentDbgValueKind::Declare, N)) {
6183 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6184 << " (could not emit func-arg dbg_value)\n");
6185 }
6186 }
6187 return;
6188 }
6189 case Intrinsic::dbg_label: {
6190 const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6191 DILabel *Label = DI.getLabel();
6192 assert(Label && "Missing label");
6193
6194 SDDbgLabel *SDV;
6195 SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6196 DAG.AddDbgLabel(SDV);
6197 return;
6198 }
6199 case Intrinsic::dbg_assign: {
6200 // Debug intrinsics are handled seperately in assignment tracking mode.
6201 assert(isAssignmentTrackingEnabled(*I.getFunction()->getParent()) &&
6202 "expected assignment tracking to be enabled");
6203 return;
6204 }
6205 case Intrinsic::dbg_value: {
6206 // Debug intrinsics are handled seperately in assignment tracking mode.
6207 if (isAssignmentTrackingEnabled(*I.getFunction()->getParent()))
6208 return;
6209 const DbgValueInst &DI = cast<DbgValueInst>(I);
6210 assert(DI.getVariable() && "Missing variable");
6211
6212 DILocalVariable *Variable = DI.getVariable();
6213 DIExpression *Expression = DI.getExpression();
6214 dropDanglingDebugInfo(Variable, Expression);
6215 SmallVector<Value *, 4> Values(DI.getValues());
6216 if (Values.empty())
6217 return;
6218
6219 if (llvm::is_contained(Values, nullptr))
6220 return;
6221
6222 bool IsVariadic = DI.hasArgList();
6223 if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6224 SDNodeOrder, IsVariadic))
6225 addDanglingDebugInfo(&DI, SDNodeOrder);
6226 return;
6227 }
6228
6229 case Intrinsic::eh_typeid_for: {
6230 // Find the type id for the given typeinfo.
6231 GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6232 unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6233 Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6234 setValue(&I, Res);
6235 return;
6236 }
6237
6238 case Intrinsic::eh_return_i32:
6239 case Intrinsic::eh_return_i64:
6240 DAG.getMachineFunction().setCallsEHReturn(true);
6241 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6242 MVT::Other,
6243 getControlRoot(),
6244 getValue(I.getArgOperand(0)),
6245 getValue(I.getArgOperand(1))));
6246 return;
6247 case Intrinsic::eh_unwind_init:
6248 DAG.getMachineFunction().setCallsUnwindInit(true);
6249 return;
6250 case Intrinsic::eh_dwarf_cfa:
6251 setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6252 TLI.getPointerTy(DAG.getDataLayout()),
6253 getValue(I.getArgOperand(0))));
6254 return;
6255 case Intrinsic::eh_sjlj_callsite: {
6256 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6257 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6258 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6259
6260 MMI.setCurrentCallSite(CI->getZExtValue());
6261 return;
6262 }
6263 case Intrinsic::eh_sjlj_functioncontext: {
6264 // Get and store the index of the function context.
6265 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6266 AllocaInst *FnCtx =
6267 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6268 int FI = FuncInfo.StaticAllocaMap[FnCtx];
6269 MFI.setFunctionContextIndex(FI);
6270 return;
6271 }
6272 case Intrinsic::eh_sjlj_setjmp: {
6273 SDValue Ops[2];
6274 Ops[0] = getRoot();
6275 Ops[1] = getValue(I.getArgOperand(0));
6276 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6277 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6278 setValue(&I, Op.getValue(0));
6279 DAG.setRoot(Op.getValue(1));
6280 return;
6281 }
6282 case Intrinsic::eh_sjlj_longjmp:
6283 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6284 getRoot(), getValue(I.getArgOperand(0))));
6285 return;
6286 case Intrinsic::eh_sjlj_setup_dispatch:
6287 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6288 getRoot()));
6289 return;
6290 case Intrinsic::masked_gather:
6291 visitMaskedGather(I);
6292 return;
6293 case Intrinsic::masked_load:
6294 visitMaskedLoad(I);
6295 return;
6296 case Intrinsic::masked_scatter:
6297 visitMaskedScatter(I);
6298 return;
6299 case Intrinsic::masked_store:
6300 visitMaskedStore(I);
6301 return;
6302 case Intrinsic::masked_expandload:
6303 visitMaskedLoad(I, true /* IsExpanding */);
6304 return;
6305 case Intrinsic::masked_compressstore:
6306 visitMaskedStore(I, true /* IsCompressing */);
6307 return;
6308 case Intrinsic::powi:
6309 setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6310 getValue(I.getArgOperand(1)), DAG));
6311 return;
6312 case Intrinsic::log:
6313 setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6314 return;
6315 case Intrinsic::log2:
6316 setValue(&I,
6317 expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6318 return;
6319 case Intrinsic::log10:
6320 setValue(&I,
6321 expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6322 return;
6323 case Intrinsic::exp:
6324 setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6325 return;
6326 case Intrinsic::exp2:
6327 setValue(&I,
6328 expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6329 return;
6330 case Intrinsic::pow:
6331 setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6332 getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6333 return;
6334 case Intrinsic::sqrt:
6335 case Intrinsic::fabs:
6336 case Intrinsic::sin:
6337 case Intrinsic::cos:
6338 case Intrinsic::floor:
6339 case Intrinsic::ceil:
6340 case Intrinsic::trunc:
6341 case Intrinsic::rint:
6342 case Intrinsic::nearbyint:
6343 case Intrinsic::round:
6344 case Intrinsic::roundeven:
6345 case Intrinsic::canonicalize: {
6346 unsigned Opcode;
6347 switch (Intrinsic) {
6348 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6349 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
6350 case Intrinsic::fabs: Opcode = ISD::FABS; break;
6351 case Intrinsic::sin: Opcode = ISD::FSIN; break;
6352 case Intrinsic::cos: Opcode = ISD::FCOS; break;
6353 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
6354 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
6355 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
6356 case Intrinsic::rint: Opcode = ISD::FRINT; break;
6357 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6358 case Intrinsic::round: Opcode = ISD::FROUND; break;
6359 case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6360 case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6361 }
6362
6363 setValue(&I, DAG.getNode(Opcode, sdl,
6364 getValue(I.getArgOperand(0)).getValueType(),
6365 getValue(I.getArgOperand(0)), Flags));
6366 return;
6367 }
6368 case Intrinsic::lround:
6369 case Intrinsic::llround:
6370 case Intrinsic::lrint:
6371 case Intrinsic::llrint: {
6372 unsigned Opcode;
6373 switch (Intrinsic) {
6374 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6375 case Intrinsic::lround: Opcode = ISD::LROUND; break;
6376 case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6377 case Intrinsic::lrint: Opcode = ISD::LRINT; break;
6378 case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
6379 }
6380
6381 EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6382 setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6383 getValue(I.getArgOperand(0))));
6384 return;
6385 }
6386 case Intrinsic::minnum:
6387 setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6388 getValue(I.getArgOperand(0)).getValueType(),
6389 getValue(I.getArgOperand(0)),
6390 getValue(I.getArgOperand(1)), Flags));
6391 return;
6392 case Intrinsic::maxnum:
6393 setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6394 getValue(I.getArgOperand(0)).getValueType(),
6395 getValue(I.getArgOperand(0)),
6396 getValue(I.getArgOperand(1)), Flags));
6397 return;
6398 case Intrinsic::minimum:
6399 setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6400 getValue(I.getArgOperand(0)).getValueType(),
6401 getValue(I.getArgOperand(0)),
6402 getValue(I.getArgOperand(1)), Flags));
6403 return;
6404 case Intrinsic::maximum:
6405 setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6406 getValue(I.getArgOperand(0)).getValueType(),
6407 getValue(I.getArgOperand(0)),
6408 getValue(I.getArgOperand(1)), Flags));
6409 return;
6410 case Intrinsic::copysign:
6411 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6412 getValue(I.getArgOperand(0)).getValueType(),
6413 getValue(I.getArgOperand(0)),
6414 getValue(I.getArgOperand(1)), Flags));
6415 return;
6416 case Intrinsic::arithmetic_fence: {
6417 setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6418 getValue(I.getArgOperand(0)).getValueType(),
6419 getValue(I.getArgOperand(0)), Flags));
6420 return;
6421 }
6422 case Intrinsic::fma:
6423 setValue(&I, DAG.getNode(
6424 ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6425 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6426 getValue(I.getArgOperand(2)), Flags));
6427 return;
6428 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
6429 case Intrinsic::INTRINSIC:
6430 #include "llvm/IR/ConstrainedOps.def"
6431 visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6432 return;
6433 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6434 #include "llvm/IR/VPIntrinsics.def"
6435 visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6436 return;
6437 case Intrinsic::fptrunc_round: {
6438 // Get the last argument, the metadata and convert it to an integer in the
6439 // call
6440 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6441 std::optional<RoundingMode> RoundMode =
6442 convertStrToRoundingMode(cast<MDString>(MD)->getString());
6443
6444 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6445
6446 // Propagate fast-math-flags from IR to node(s).
6447 SDNodeFlags Flags;
6448 Flags.copyFMF(*cast<FPMathOperator>(&I));
6449 SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6450
6451 SDValue Result;
6452 Result = DAG.getNode(
6453 ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6454 DAG.getTargetConstant((int)*RoundMode, sdl,
6455 TLI.getPointerTy(DAG.getDataLayout())));
6456 setValue(&I, Result);
6457
6458 return;
6459 }
6460 case Intrinsic::fmuladd: {
6461 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6462 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6463 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6464 setValue(&I, DAG.getNode(ISD::FMA, sdl,
6465 getValue(I.getArgOperand(0)).getValueType(),
6466 getValue(I.getArgOperand(0)),
6467 getValue(I.getArgOperand(1)),
6468 getValue(I.getArgOperand(2)), Flags));
6469 } else {
6470 // TODO: Intrinsic calls should have fast-math-flags.
6471 SDValue Mul = DAG.getNode(
6472 ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6473 getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6474 SDValue Add = DAG.getNode(ISD::FADD, sdl,
6475 getValue(I.getArgOperand(0)).getValueType(),
6476 Mul, getValue(I.getArgOperand(2)), Flags);
6477 setValue(&I, Add);
6478 }
6479 return;
6480 }
6481 case Intrinsic::convert_to_fp16:
6482 setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6483 DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6484 getValue(I.getArgOperand(0)),
6485 DAG.getTargetConstant(0, sdl,
6486 MVT::i32))));
6487 return;
6488 case Intrinsic::convert_from_fp16:
6489 setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6490 TLI.getValueType(DAG.getDataLayout(), I.getType()),
6491 DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6492 getValue(I.getArgOperand(0)))));
6493 return;
6494 case Intrinsic::fptosi_sat: {
6495 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6496 setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6497 getValue(I.getArgOperand(0)),
6498 DAG.getValueType(VT.getScalarType())));
6499 return;
6500 }
6501 case Intrinsic::fptoui_sat: {
6502 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6503 setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6504 getValue(I.getArgOperand(0)),
6505 DAG.getValueType(VT.getScalarType())));
6506 return;
6507 }
6508 case Intrinsic::set_rounding:
6509 Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6510 {getRoot(), getValue(I.getArgOperand(0))});
6511 setValue(&I, Res);
6512 DAG.setRoot(Res.getValue(0));
6513 return;
6514 case Intrinsic::is_fpclass: {
6515 const DataLayout DLayout = DAG.getDataLayout();
6516 EVT DestVT = TLI.getValueType(DLayout, I.getType());
6517 EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6518 unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6519 MachineFunction &MF = DAG.getMachineFunction();
6520 const Function &F = MF.getFunction();
6521 SDValue Op = getValue(I.getArgOperand(0));
6522 SDNodeFlags Flags;
6523 Flags.setNoFPExcept(
6524 !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6525 // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6526 // expansion can use illegal types. Making expansion early allows
6527 // legalizing these types prior to selection.
6528 if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6529 SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6530 setValue(&I, Result);
6531 return;
6532 }
6533
6534 SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6535 SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6536 setValue(&I, V);
6537 return;
6538 }
6539 case Intrinsic::pcmarker: {
6540 SDValue Tmp = getValue(I.getArgOperand(0));
6541 DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6542 return;
6543 }
6544 case Intrinsic::readcyclecounter: {
6545 SDValue Op = getRoot();
6546 Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6547 DAG.getVTList(MVT::i64, MVT::Other), Op);
6548 setValue(&I, Res);
6549 DAG.setRoot(Res.getValue(1));
6550 return;
6551 }
6552 case Intrinsic::bitreverse:
6553 setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6554 getValue(I.getArgOperand(0)).getValueType(),
6555 getValue(I.getArgOperand(0))));
6556 return;
6557 case Intrinsic::bswap:
6558 setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6559 getValue(I.getArgOperand(0)).getValueType(),
6560 getValue(I.getArgOperand(0))));
6561 return;
6562 case Intrinsic::cttz: {
6563 SDValue Arg = getValue(I.getArgOperand(0));
6564 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6565 EVT Ty = Arg.getValueType();
6566 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6567 sdl, Ty, Arg));
6568 return;
6569 }
6570 case Intrinsic::ctlz: {
6571 SDValue Arg = getValue(I.getArgOperand(0));
6572 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6573 EVT Ty = Arg.getValueType();
6574 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6575 sdl, Ty, Arg));
6576 return;
6577 }
6578 case Intrinsic::ctpop: {
6579 SDValue Arg = getValue(I.getArgOperand(0));
6580 EVT Ty = Arg.getValueType();
6581 setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6582 return;
6583 }
6584 case Intrinsic::fshl:
6585 case Intrinsic::fshr: {
6586 bool IsFSHL = Intrinsic == Intrinsic::fshl;
6587 SDValue X = getValue(I.getArgOperand(0));
6588 SDValue Y = getValue(I.getArgOperand(1));
6589 SDValue Z = getValue(I.getArgOperand(2));
6590 EVT VT = X.getValueType();
6591
6592 if (X == Y) {
6593 auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6594 setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6595 } else {
6596 auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6597 setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6598 }
6599 return;
6600 }
6601 case Intrinsic::sadd_sat: {
6602 SDValue Op1 = getValue(I.getArgOperand(0));
6603 SDValue Op2 = getValue(I.getArgOperand(1));
6604 setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6605 return;
6606 }
6607 case Intrinsic::uadd_sat: {
6608 SDValue Op1 = getValue(I.getArgOperand(0));
6609 SDValue Op2 = getValue(I.getArgOperand(1));
6610 setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6611 return;
6612 }
6613 case Intrinsic::ssub_sat: {
6614 SDValue Op1 = getValue(I.getArgOperand(0));
6615 SDValue Op2 = getValue(I.getArgOperand(1));
6616 setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6617 return;
6618 }
6619 case Intrinsic::usub_sat: {
6620 SDValue Op1 = getValue(I.getArgOperand(0));
6621 SDValue Op2 = getValue(I.getArgOperand(1));
6622 setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6623 return;
6624 }
6625 case Intrinsic::sshl_sat: {
6626 SDValue Op1 = getValue(I.getArgOperand(0));
6627 SDValue Op2 = getValue(I.getArgOperand(1));
6628 setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6629 return;
6630 }
6631 case Intrinsic::ushl_sat: {
6632 SDValue Op1 = getValue(I.getArgOperand(0));
6633 SDValue Op2 = getValue(I.getArgOperand(1));
6634 setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6635 return;
6636 }
6637 case Intrinsic::smul_fix:
6638 case Intrinsic::umul_fix:
6639 case Intrinsic::smul_fix_sat:
6640 case Intrinsic::umul_fix_sat: {
6641 SDValue Op1 = getValue(I.getArgOperand(0));
6642 SDValue Op2 = getValue(I.getArgOperand(1));
6643 SDValue Op3 = getValue(I.getArgOperand(2));
6644 setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6645 Op1.getValueType(), Op1, Op2, Op3));
6646 return;
6647 }
6648 case Intrinsic::sdiv_fix:
6649 case Intrinsic::udiv_fix:
6650 case Intrinsic::sdiv_fix_sat:
6651 case Intrinsic::udiv_fix_sat: {
6652 SDValue Op1 = getValue(I.getArgOperand(0));
6653 SDValue Op2 = getValue(I.getArgOperand(1));
6654 SDValue Op3 = getValue(I.getArgOperand(2));
6655 setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6656 Op1, Op2, Op3, DAG, TLI));
6657 return;
6658 }
6659 case Intrinsic::smax: {
6660 SDValue Op1 = getValue(I.getArgOperand(0));
6661 SDValue Op2 = getValue(I.getArgOperand(1));
6662 setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6663 return;
6664 }
6665 case Intrinsic::smin: {
6666 SDValue Op1 = getValue(I.getArgOperand(0));
6667 SDValue Op2 = getValue(I.getArgOperand(1));
6668 setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6669 return;
6670 }
6671 case Intrinsic::umax: {
6672 SDValue Op1 = getValue(I.getArgOperand(0));
6673 SDValue Op2 = getValue(I.getArgOperand(1));
6674 setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6675 return;
6676 }
6677 case Intrinsic::umin: {
6678 SDValue Op1 = getValue(I.getArgOperand(0));
6679 SDValue Op2 = getValue(I.getArgOperand(1));
6680 setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6681 return;
6682 }
6683 case Intrinsic::abs: {
6684 // TODO: Preserve "int min is poison" arg in SDAG?
6685 SDValue Op1 = getValue(I.getArgOperand(0));
6686 setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6687 return;
6688 }
6689 case Intrinsic::stacksave: {
6690 SDValue Op = getRoot();
6691 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6692 Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6693 setValue(&I, Res);
6694 DAG.setRoot(Res.getValue(1));
6695 return;
6696 }
6697 case Intrinsic::stackrestore:
6698 Res = getValue(I.getArgOperand(0));
6699 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6700 return;
6701 case Intrinsic::get_dynamic_area_offset: {
6702 SDValue Op = getRoot();
6703 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6704 EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6705 // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6706 // target.
6707 if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6708 report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6709 " intrinsic!");
6710 Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6711 Op);
6712 DAG.setRoot(Op);
6713 setValue(&I, Res);
6714 return;
6715 }
6716 case Intrinsic::stackguard: {
6717 MachineFunction &MF = DAG.getMachineFunction();
6718 const Module &M = *MF.getFunction().getParent();
6719 SDValue Chain = getRoot();
6720 if (TLI.useLoadStackGuardNode()) {
6721 Res = getLoadStackGuard(DAG, sdl, Chain);
6722 } else {
6723 EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6724 const Value *Global = TLI.getSDagStackGuard(M);
6725 Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6726 Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6727 MachinePointerInfo(Global, 0), Align,
6728 MachineMemOperand::MOVolatile);
6729 }
6730 if (TLI.useStackGuardXorFP())
6731 Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6732 DAG.setRoot(Chain);
6733 setValue(&I, Res);
6734 return;
6735 }
6736 case Intrinsic::stackprotector: {
6737 // Emit code into the DAG to store the stack guard onto the stack.
6738 MachineFunction &MF = DAG.getMachineFunction();
6739 MachineFrameInfo &MFI = MF.getFrameInfo();
6740 SDValue Src, Chain = getRoot();
6741
6742 if (TLI.useLoadStackGuardNode())
6743 Src = getLoadStackGuard(DAG, sdl, Chain);
6744 else
6745 Src = getValue(I.getArgOperand(0)); // The guard's value.
6746
6747 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6748
6749 int FI = FuncInfo.StaticAllocaMap[Slot];
6750 MFI.setStackProtectorIndex(FI);
6751 EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6752
6753 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6754
6755 // Store the stack protector onto the stack.
6756 Res = DAG.getStore(
6757 Chain, sdl, Src, FIN,
6758 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6759 MaybeAlign(), MachineMemOperand::MOVolatile);
6760 setValue(&I, Res);
6761 DAG.setRoot(Res);
6762 return;
6763 }
6764 case Intrinsic::objectsize:
6765 llvm_unreachable("llvm.objectsize.* should have been lowered already");
6766
6767 case Intrinsic::is_constant:
6768 llvm_unreachable("llvm.is.constant.* should have been lowered already");
6769
6770 case Intrinsic::annotation:
6771 case Intrinsic::ptr_annotation:
6772 case Intrinsic::launder_invariant_group:
6773 case Intrinsic::strip_invariant_group:
6774 // Drop the intrinsic, but forward the value
6775 setValue(&I, getValue(I.getOperand(0)));
6776 return;
6777
6778 case Intrinsic::assume:
6779 case Intrinsic::experimental_noalias_scope_decl:
6780 case Intrinsic::var_annotation:
6781 case Intrinsic::sideeffect:
6782 // Discard annotate attributes, noalias scope declarations, assumptions, and
6783 // artificial side-effects.
6784 return;
6785
6786 case Intrinsic::codeview_annotation: {
6787 // Emit a label associated with this metadata.
6788 MachineFunction &MF = DAG.getMachineFunction();
6789 MCSymbol *Label =
6790 MF.getMMI().getContext().createTempSymbol("annotation", true);
6791 Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6792 MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6793 Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6794 DAG.setRoot(Res);
6795 return;
6796 }
6797
6798 case Intrinsic::init_trampoline: {
6799 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6800
6801 SDValue Ops[6];
6802 Ops[0] = getRoot();
6803 Ops[1] = getValue(I.getArgOperand(0));
6804 Ops[2] = getValue(I.getArgOperand(1));
6805 Ops[3] = getValue(I.getArgOperand(2));
6806 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6807 Ops[5] = DAG.getSrcValue(F);
6808
6809 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6810
6811 DAG.setRoot(Res);
6812 return;
6813 }
6814 case Intrinsic::adjust_trampoline:
6815 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6816 TLI.getPointerTy(DAG.getDataLayout()),
6817 getValue(I.getArgOperand(0))));
6818 return;
6819 case Intrinsic::gcroot: {
6820 assert(DAG.getMachineFunction().getFunction().hasGC() &&
6821 "only valid in functions with gc specified, enforced by Verifier");
6822 assert(GFI && "implied by previous");
6823 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6824 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6825
6826 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6827 GFI->addStackRoot(FI->getIndex(), TypeMap);
6828 return;
6829 }
6830 case Intrinsic::gcread:
6831 case Intrinsic::gcwrite:
6832 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6833 case Intrinsic::get_rounding:
6834 Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
6835 setValue(&I, Res);
6836 DAG.setRoot(Res.getValue(1));
6837 return;
6838
6839 case Intrinsic::expect:
6840 // Just replace __builtin_expect(exp, c) with EXP.
6841 setValue(&I, getValue(I.getArgOperand(0)));
6842 return;
6843
6844 case Intrinsic::ubsantrap:
6845 case Intrinsic::debugtrap:
6846 case Intrinsic::trap: {
6847 StringRef TrapFuncName =
6848 I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6849 if (TrapFuncName.empty()) {
6850 switch (Intrinsic) {
6851 case Intrinsic::trap:
6852 DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6853 break;
6854 case Intrinsic::debugtrap:
6855 DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6856 break;
6857 case Intrinsic::ubsantrap:
6858 DAG.setRoot(DAG.getNode(
6859 ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6860 DAG.getTargetConstant(
6861 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6862 MVT::i32)));
6863 break;
6864 default: llvm_unreachable("unknown trap intrinsic");
6865 }
6866 return;
6867 }
6868 TargetLowering::ArgListTy Args;
6869 if (Intrinsic == Intrinsic::ubsantrap) {
6870 Args.push_back(TargetLoweringBase::ArgListEntry());
6871 Args[0].Val = I.getArgOperand(0);
6872 Args[0].Node = getValue(Args[0].Val);
6873 Args[0].Ty = Args[0].Val->getType();
6874 }
6875
6876 TargetLowering::CallLoweringInfo CLI(DAG);
6877 CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6878 CallingConv::C, I.getType(),
6879 DAG.getExternalSymbol(TrapFuncName.data(),
6880 TLI.getPointerTy(DAG.getDataLayout())),
6881 std::move(Args));
6882
6883 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6884 DAG.setRoot(Result.second);
6885 return;
6886 }
6887
6888 case Intrinsic::uadd_with_overflow:
6889 case Intrinsic::sadd_with_overflow:
6890 case Intrinsic::usub_with_overflow:
6891 case Intrinsic::ssub_with_overflow:
6892 case Intrinsic::umul_with_overflow:
6893 case Intrinsic::smul_with_overflow: {
6894 ISD::NodeType Op;
6895 switch (Intrinsic) {
6896 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6897 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6898 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6899 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6900 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6901 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6902 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6903 }
6904 SDValue Op1 = getValue(I.getArgOperand(0));
6905 SDValue Op2 = getValue(I.getArgOperand(1));
6906
6907 EVT ResultVT = Op1.getValueType();
6908 EVT OverflowVT = MVT::i1;
6909 if (ResultVT.isVector())
6910 OverflowVT = EVT::getVectorVT(
6911 *Context, OverflowVT, ResultVT.getVectorElementCount());
6912
6913 SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6914 setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6915 return;
6916 }
6917 case Intrinsic::prefetch: {
6918 SDValue Ops[5];
6919 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6920 auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6921 Ops[0] = DAG.getRoot();
6922 Ops[1] = getValue(I.getArgOperand(0));
6923 Ops[2] = getValue(I.getArgOperand(1));
6924 Ops[3] = getValue(I.getArgOperand(2));
6925 Ops[4] = getValue(I.getArgOperand(3));
6926 SDValue Result = DAG.getMemIntrinsicNode(
6927 ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6928 EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6929 /* align */ std::nullopt, Flags);
6930
6931 // Chain the prefetch in parallell with any pending loads, to stay out of
6932 // the way of later optimizations.
6933 PendingLoads.push_back(Result);
6934 Result = getRoot();
6935 DAG.setRoot(Result);
6936 return;
6937 }
6938 case Intrinsic::lifetime_start:
6939 case Intrinsic::lifetime_end: {
6940 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6941 // Stack coloring is not enabled in O0, discard region information.
6942 if (TM.getOptLevel() == CodeGenOpt::None)
6943 return;
6944
6945 const int64_t ObjectSize =
6946 cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6947 Value *const ObjectPtr = I.getArgOperand(1);
6948 SmallVector<const Value *, 4> Allocas;
6949 getUnderlyingObjects(ObjectPtr, Allocas);
6950
6951 for (const Value *Alloca : Allocas) {
6952 const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6953
6954 // Could not find an Alloca.
6955 if (!LifetimeObject)
6956 continue;
6957
6958 // First check that the Alloca is static, otherwise it won't have a
6959 // valid frame index.
6960 auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6961 if (SI == FuncInfo.StaticAllocaMap.end())
6962 return;
6963
6964 const int FrameIndex = SI->second;
6965 int64_t Offset;
6966 if (GetPointerBaseWithConstantOffset(
6967 ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6968 Offset = -1; // Cannot determine offset from alloca to lifetime object.
6969 Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6970 Offset);
6971 DAG.setRoot(Res);
6972 }
6973 return;
6974 }
6975 case Intrinsic::pseudoprobe: {
6976 auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6977 auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6978 auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6979 Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6980 DAG.setRoot(Res);
6981 return;
6982 }
6983 case Intrinsic::invariant_start:
6984 // Discard region information.
6985 setValue(&I,
6986 DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
6987 return;
6988 case Intrinsic::invariant_end:
6989 // Discard region information.
6990 return;
6991 case Intrinsic::clear_cache:
6992 /// FunctionName may be null.
6993 if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6994 lowerCallToExternalSymbol(I, FunctionName);
6995 return;
6996 case Intrinsic::donothing:
6997 case Intrinsic::seh_try_begin:
6998 case Intrinsic::seh_scope_begin:
6999 case Intrinsic::seh_try_end:
7000 case Intrinsic::seh_scope_end:
7001 // ignore
7002 return;
7003 case Intrinsic::experimental_stackmap:
7004 visitStackmap(I);
7005 return;
7006 case Intrinsic::experimental_patchpoint_void:
7007 case Intrinsic::experimental_patchpoint_i64:
7008 visitPatchpoint(I);
7009 return;
7010 case Intrinsic::experimental_gc_statepoint:
7011 LowerStatepoint(cast<GCStatepointInst>(I));
7012 return;
7013 case Intrinsic::experimental_gc_result:
7014 visitGCResult(cast<GCResultInst>(I));
7015 return;
7016 case Intrinsic::experimental_gc_relocate:
7017 visitGCRelocate(cast<GCRelocateInst>(I));
7018 return;
7019 case Intrinsic::instrprof_cover:
7020 llvm_unreachable("instrprof failed to lower a cover");
7021 case Intrinsic::instrprof_increment:
7022 llvm_unreachable("instrprof failed to lower an increment");
7023 case Intrinsic::instrprof_value_profile:
7024 llvm_unreachable("instrprof failed to lower a value profiling call");
7025 case Intrinsic::localescape: {
7026 MachineFunction &MF = DAG.getMachineFunction();
7027 const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7028
7029 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7030 // is the same on all targets.
7031 for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7032 Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7033 if (isa<ConstantPointerNull>(Arg))
7034 continue; // Skip null pointers. They represent a hole in index space.
7035 AllocaInst *Slot = cast<AllocaInst>(Arg);
7036 assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7037 "can only escape static allocas");
7038 int FI = FuncInfo.StaticAllocaMap[Slot];
7039 MCSymbol *FrameAllocSym =
7040 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7041 GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7042 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7043 TII->get(TargetOpcode::LOCAL_ESCAPE))
7044 .addSym(FrameAllocSym)
7045 .addFrameIndex(FI);
7046 }
7047
7048 return;
7049 }
7050
7051 case Intrinsic::localrecover: {
7052 // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7053 MachineFunction &MF = DAG.getMachineFunction();
7054
7055 // Get the symbol that defines the frame offset.
7056 auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7057 auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7058 unsigned IdxVal =
7059 unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7060 MCSymbol *FrameAllocSym =
7061 MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7062 GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7063
7064 Value *FP = I.getArgOperand(1);
7065 SDValue FPVal = getValue(FP);
7066 EVT PtrVT = FPVal.getValueType();
7067
7068 // Create a MCSymbol for the label to avoid any target lowering
7069 // that would make this PC relative.
7070 SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7071 SDValue OffsetVal =
7072 DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7073
7074 // Add the offset to the FP.
7075 SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7076 setValue(&I, Add);
7077
7078 return;
7079 }
7080
7081 case Intrinsic::eh_exceptionpointer:
7082 case Intrinsic::eh_exceptioncode: {
7083 // Get the exception pointer vreg, copy from it, and resize it to fit.
7084 const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7085 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7086 const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7087 unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7088 SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7089 if (Intrinsic == Intrinsic::eh_exceptioncode)
7090 N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7091 setValue(&I, N);
7092 return;
7093 }
7094 case Intrinsic::xray_customevent: {
7095 // Here we want to make sure that the intrinsic behaves as if it has a
7096 // specific calling convention, and only for x86_64.
7097 // FIXME: Support other platforms later.
7098 const auto &Triple = DAG.getTarget().getTargetTriple();
7099 if (Triple.getArch() != Triple::x86_64)
7100 return;
7101
7102 SmallVector<SDValue, 8> Ops;
7103
7104 // We want to say that we always want the arguments in registers.
7105 SDValue LogEntryVal = getValue(I.getArgOperand(0));
7106 SDValue StrSizeVal = getValue(I.getArgOperand(1));
7107 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7108 SDValue Chain = getRoot();
7109 Ops.push_back(LogEntryVal);
7110 Ops.push_back(StrSizeVal);
7111 Ops.push_back(Chain);
7112
7113 // We need to enforce the calling convention for the callsite, so that
7114 // argument ordering is enforced correctly, and that register allocation can
7115 // see that some registers may be assumed clobbered and have to preserve
7116 // them across calls to the intrinsic.
7117 MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7118 sdl, NodeTys, Ops);
7119 SDValue patchableNode = SDValue(MN, 0);
7120 DAG.setRoot(patchableNode);
7121 setValue(&I, patchableNode);
7122 return;
7123 }
7124 case Intrinsic::xray_typedevent: {
7125 // Here we want to make sure that the intrinsic behaves as if it has a
7126 // specific calling convention, and only for x86_64.
7127 // FIXME: Support other platforms later.
7128 const auto &Triple = DAG.getTarget().getTargetTriple();
7129 if (Triple.getArch() != Triple::x86_64)
7130 return;
7131
7132 SmallVector<SDValue, 8> Ops;
7133
7134 // We want to say that we always want the arguments in registers.
7135 // It's unclear to me how manipulating the selection DAG here forces callers
7136 // to provide arguments in registers instead of on the stack.
7137 SDValue LogTypeId = getValue(I.getArgOperand(0));
7138 SDValue LogEntryVal = getValue(I.getArgOperand(1));
7139 SDValue StrSizeVal = getValue(I.getArgOperand(2));
7140 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7141 SDValue Chain = getRoot();
7142 Ops.push_back(LogTypeId);
7143 Ops.push_back(LogEntryVal);
7144 Ops.push_back(StrSizeVal);
7145 Ops.push_back(Chain);
7146
7147 // We need to enforce the calling convention for the callsite, so that
7148 // argument ordering is enforced correctly, and that register allocation can
7149 // see that some registers may be assumed clobbered and have to preserve
7150 // them across calls to the intrinsic.
7151 MachineSDNode *MN = DAG.getMachineNode(
7152 TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7153 SDValue patchableNode = SDValue(MN, 0);
7154 DAG.setRoot(patchableNode);
7155 setValue(&I, patchableNode);
7156 return;
7157 }
7158 case Intrinsic::experimental_deoptimize:
7159 LowerDeoptimizeCall(&I);
7160 return;
7161 case Intrinsic::experimental_stepvector:
7162 visitStepVector(I);
7163 return;
7164 case Intrinsic::vector_reduce_fadd:
7165 case Intrinsic::vector_reduce_fmul:
7166 case Intrinsic::vector_reduce_add:
7167 case Intrinsic::vector_reduce_mul:
7168 case Intrinsic::vector_reduce_and:
7169 case Intrinsic::vector_reduce_or:
7170 case Intrinsic::vector_reduce_xor:
7171 case Intrinsic::vector_reduce_smax:
7172 case Intrinsic::vector_reduce_smin:
7173 case Intrinsic::vector_reduce_umax:
7174 case Intrinsic::vector_reduce_umin:
7175 case Intrinsic::vector_reduce_fmax:
7176 case Intrinsic::vector_reduce_fmin:
7177 visitVectorReduce(I, Intrinsic);
7178 return;
7179
7180 case Intrinsic::icall_branch_funnel: {
7181 SmallVector<SDValue, 16> Ops;
7182 Ops.push_back(getValue(I.getArgOperand(0)));
7183
7184 int64_t Offset;
7185 auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7186 I.getArgOperand(1), Offset, DAG.getDataLayout()));
7187 if (!Base)
7188 report_fatal_error(
7189 "llvm.icall.branch.funnel operand must be a GlobalValue");
7190 Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7191
7192 struct BranchFunnelTarget {
7193 int64_t Offset;
7194 SDValue Target;
7195 };
7196 SmallVector<BranchFunnelTarget, 8> Targets;
7197
7198 for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7199 auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7200 I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7201 if (ElemBase != Base)
7202 report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7203 "to the same GlobalValue");
7204
7205 SDValue Val = getValue(I.getArgOperand(Op + 1));
7206 auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7207 if (!GA)
7208 report_fatal_error(
7209 "llvm.icall.branch.funnel operand must be a GlobalValue");
7210 Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7211 GA->getGlobal(), sdl, Val.getValueType(),
7212 GA->getOffset())});
7213 }
7214 llvm::sort(Targets,
7215 [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7216 return T1.Offset < T2.Offset;
7217 });
7218
7219 for (auto &T : Targets) {
7220 Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7221 Ops.push_back(T.Target);
7222 }
7223
7224 Ops.push_back(DAG.getRoot()); // Chain
7225 SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7226 MVT::Other, Ops),
7227 0);
7228 DAG.setRoot(N);
7229 setValue(&I, N);
7230 HasTailCall = true;
7231 return;
7232 }
7233
7234 case Intrinsic::wasm_landingpad_index:
7235 // Information this intrinsic contained has been transferred to
7236 // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7237 // delete it now.
7238 return;
7239
7240 case Intrinsic::aarch64_settag:
7241 case Intrinsic::aarch64_settag_zero: {
7242 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7243 bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7244 SDValue Val = TSI.EmitTargetCodeForSetTag(
7245 DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7246 getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7247 ZeroMemory);
7248 DAG.setRoot(Val);
7249 setValue(&I, Val);
7250 return;
7251 }
7252 case Intrinsic::ptrmask: {
7253 SDValue Ptr = getValue(I.getOperand(0));
7254 SDValue Const = getValue(I.getOperand(1));
7255
7256 EVT PtrVT = Ptr.getValueType();
7257 setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7258 DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7259 return;
7260 }
7261 case Intrinsic::threadlocal_address: {
7262 setValue(&I, getValue(I.getOperand(0)));
7263 return;
7264 }
7265 case Intrinsic::get_active_lane_mask: {
7266 EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7267 SDValue Index = getValue(I.getOperand(0));
7268 EVT ElementVT = Index.getValueType();
7269
7270 if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7271 visitTargetIntrinsic(I, Intrinsic);
7272 return;
7273 }
7274
7275 SDValue TripCount = getValue(I.getOperand(1));
7276 auto VecTy = CCVT.changeVectorElementType(ElementVT);
7277
7278 SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7279 SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7280 SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7281 SDValue VectorInduction = DAG.getNode(
7282 ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7283 SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7284 VectorTripCount, ISD::CondCode::SETULT);
7285 setValue(&I, SetCC);
7286 return;
7287 }
7288 case Intrinsic::vector_insert: {
7289 SDValue Vec = getValue(I.getOperand(0));
7290 SDValue SubVec = getValue(I.getOperand(1));
7291 SDValue Index = getValue(I.getOperand(2));
7292
7293 // The intrinsic's index type is i64, but the SDNode requires an index type
7294 // suitable for the target. Convert the index as required.
7295 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7296 if (Index.getValueType() != VectorIdxTy)
7297 Index = DAG.getVectorIdxConstant(
7298 cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7299
7300 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7301 setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7302 Index));
7303 return;
7304 }
7305 case Intrinsic::vector_extract: {
7306 SDValue Vec = getValue(I.getOperand(0));
7307 SDValue Index = getValue(I.getOperand(1));
7308 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7309
7310 // The intrinsic's index type is i64, but the SDNode requires an index type
7311 // suitable for the target. Convert the index as required.
7312 MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7313 if (Index.getValueType() != VectorIdxTy)
7314 Index = DAG.getVectorIdxConstant(
7315 cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7316
7317 setValue(&I,
7318 DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7319 return;
7320 }
7321 case Intrinsic::experimental_vector_reverse:
7322 visitVectorReverse(I);
7323 return;
7324 case Intrinsic::experimental_vector_splice:
7325 visitVectorSplice(I);
7326 return;
7327 }
7328 }
7329
visitConstrainedFPIntrinsic(const ConstrainedFPIntrinsic & FPI)7330 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7331 const ConstrainedFPIntrinsic &FPI) {
7332 SDLoc sdl = getCurSDLoc();
7333
7334 // We do not need to serialize constrained FP intrinsics against
7335 // each other or against (nonvolatile) loads, so they can be
7336 // chained like loads.
7337 SDValue Chain = DAG.getRoot();
7338 SmallVector<SDValue, 4> Opers;
7339 Opers.push_back(Chain);
7340 if (FPI.isUnaryOp()) {
7341 Opers.push_back(getValue(FPI.getArgOperand(0)));
7342 } else if (FPI.isTernaryOp()) {
7343 Opers.push_back(getValue(FPI.getArgOperand(0)));
7344 Opers.push_back(getValue(FPI.getArgOperand(1)));
7345 Opers.push_back(getValue(FPI.getArgOperand(2)));
7346 } else {
7347 Opers.push_back(getValue(FPI.getArgOperand(0)));
7348 Opers.push_back(getValue(FPI.getArgOperand(1)));
7349 }
7350
7351 auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7352 assert(Result.getNode()->getNumValues() == 2);
7353
7354 // Push node to the appropriate list so that future instructions can be
7355 // chained up correctly.
7356 SDValue OutChain = Result.getValue(1);
7357 switch (EB) {
7358 case fp::ExceptionBehavior::ebIgnore:
7359 // The only reason why ebIgnore nodes still need to be chained is that
7360 // they might depend on the current rounding mode, and therefore must
7361 // not be moved across instruction that may change that mode.
7362 [[fallthrough]];
7363 case fp::ExceptionBehavior::ebMayTrap:
7364 // These must not be moved across calls or instructions that may change
7365 // floating-point exception masks.
7366 PendingConstrainedFP.push_back(OutChain);
7367 break;
7368 case fp::ExceptionBehavior::ebStrict:
7369 // These must not be moved across calls or instructions that may change
7370 // floating-point exception masks or read floating-point exception flags.
7371 // In addition, they cannot be optimized out even if unused.
7372 PendingConstrainedFPStrict.push_back(OutChain);
7373 break;
7374 }
7375 };
7376
7377 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7378 EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7379 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7380 fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7381
7382 SDNodeFlags Flags;
7383 if (EB == fp::ExceptionBehavior::ebIgnore)
7384 Flags.setNoFPExcept(true);
7385
7386 if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7387 Flags.copyFMF(*FPOp);
7388
7389 unsigned Opcode;
7390 switch (FPI.getIntrinsicID()) {
7391 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7392 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
7393 case Intrinsic::INTRINSIC: \
7394 Opcode = ISD::STRICT_##DAGN; \
7395 break;
7396 #include "llvm/IR/ConstrainedOps.def"
7397 case Intrinsic::experimental_constrained_fmuladd: {
7398 Opcode = ISD::STRICT_FMA;
7399 // Break fmuladd into fmul and fadd.
7400 if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7401 !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7402 Opers.pop_back();
7403 SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7404 pushOutChain(Mul, EB);
7405 Opcode = ISD::STRICT_FADD;
7406 Opers.clear();
7407 Opers.push_back(Mul.getValue(1));
7408 Opers.push_back(Mul.getValue(0));
7409 Opers.push_back(getValue(FPI.getArgOperand(2)));
7410 }
7411 break;
7412 }
7413 }
7414
7415 // A few strict DAG nodes carry additional operands that are not
7416 // set up by the default code above.
7417 switch (Opcode) {
7418 default: break;
7419 case ISD::STRICT_FP_ROUND:
7420 Opers.push_back(
7421 DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7422 break;
7423 case ISD::STRICT_FSETCC:
7424 case ISD::STRICT_FSETCCS: {
7425 auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7426 ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7427 if (TM.Options.NoNaNsFPMath)
7428 Condition = getFCmpCodeWithoutNaN(Condition);
7429 Opers.push_back(DAG.getCondCode(Condition));
7430 break;
7431 }
7432 }
7433
7434 SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7435 pushOutChain(Result, EB);
7436
7437 SDValue FPResult = Result.getValue(0);
7438 setValue(&FPI, FPResult);
7439 }
7440
getISDForVPIntrinsic(const VPIntrinsic & VPIntrin)7441 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7442 std::optional<unsigned> ResOPC;
7443 switch (VPIntrin.getIntrinsicID()) {
7444 case Intrinsic::vp_ctlz: {
7445 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(3))->isOne();
7446 ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
7447 break;
7448 }
7449 case Intrinsic::vp_cttz: {
7450 bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(3))->isOne();
7451 ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
7452 break;
7453 }
7454 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD) \
7455 case Intrinsic::VPID: \
7456 ResOPC = ISD::VPSD; \
7457 break;
7458 #include "llvm/IR/VPIntrinsics.def"
7459 }
7460
7461 if (!ResOPC)
7462 llvm_unreachable(
7463 "Inconsistency: no SDNode available for this VPIntrinsic!");
7464
7465 if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7466 *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7467 if (VPIntrin.getFastMathFlags().allowReassoc())
7468 return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7469 : ISD::VP_REDUCE_FMUL;
7470 }
7471
7472 return *ResOPC;
7473 }
7474
visitVPLoad(const VPIntrinsic & VPIntrin,EVT VT,SmallVector<SDValue,7> & OpValues)7475 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT,
7476 SmallVector<SDValue, 7> &OpValues) {
7477 SDLoc DL = getCurSDLoc();
7478 Value *PtrOperand = VPIntrin.getArgOperand(0);
7479 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7480 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7481 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7482 SDValue LD;
7483 bool AddToChain = true;
7484 // Do not serialize variable-length loads of constant memory with
7485 // anything.
7486 if (!Alignment)
7487 Alignment = DAG.getEVTAlign(VT);
7488 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7489 AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7490 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7491 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7492 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7493 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7494 LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7495 MMO, false /*IsExpanding */);
7496 if (AddToChain)
7497 PendingLoads.push_back(LD.getValue(1));
7498 setValue(&VPIntrin, LD);
7499 }
7500
visitVPGather(const VPIntrinsic & VPIntrin,EVT VT,SmallVector<SDValue,7> & OpValues)7501 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT,
7502 SmallVector<SDValue, 7> &OpValues) {
7503 SDLoc DL = getCurSDLoc();
7504 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7505 Value *PtrOperand = VPIntrin.getArgOperand(0);
7506 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7507 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7508 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7509 SDValue LD;
7510 if (!Alignment)
7511 Alignment = DAG.getEVTAlign(VT.getScalarType());
7512 unsigned AS =
7513 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7514 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7515 MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7516 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7517 SDValue Base, Index, Scale;
7518 ISD::MemIndexType IndexType;
7519 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7520 this, VPIntrin.getParent(),
7521 VT.getScalarStoreSize());
7522 if (!UniformBase) {
7523 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7524 Index = getValue(PtrOperand);
7525 IndexType = ISD::SIGNED_SCALED;
7526 Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7527 }
7528 EVT IdxVT = Index.getValueType();
7529 EVT EltTy = IdxVT.getVectorElementType();
7530 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7531 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7532 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7533 }
7534 LD = DAG.getGatherVP(
7535 DAG.getVTList(VT, MVT::Other), VT, DL,
7536 {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7537 IndexType);
7538 PendingLoads.push_back(LD.getValue(1));
7539 setValue(&VPIntrin, LD);
7540 }
7541
visitVPStore(const VPIntrinsic & VPIntrin,SmallVector<SDValue,7> & OpValues)7542 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin,
7543 SmallVector<SDValue, 7> &OpValues) {
7544 SDLoc DL = getCurSDLoc();
7545 Value *PtrOperand = VPIntrin.getArgOperand(1);
7546 EVT VT = OpValues[0].getValueType();
7547 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7548 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7549 SDValue ST;
7550 if (!Alignment)
7551 Alignment = DAG.getEVTAlign(VT);
7552 SDValue Ptr = OpValues[1];
7553 SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7554 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7555 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7556 MemoryLocation::UnknownSize, *Alignment, AAInfo);
7557 ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7558 OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7559 /* IsTruncating */ false, /*IsCompressing*/ false);
7560 DAG.setRoot(ST);
7561 setValue(&VPIntrin, ST);
7562 }
7563
visitVPScatter(const VPIntrinsic & VPIntrin,SmallVector<SDValue,7> & OpValues)7564 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin,
7565 SmallVector<SDValue, 7> &OpValues) {
7566 SDLoc DL = getCurSDLoc();
7567 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7568 Value *PtrOperand = VPIntrin.getArgOperand(1);
7569 EVT VT = OpValues[0].getValueType();
7570 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7571 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7572 SDValue ST;
7573 if (!Alignment)
7574 Alignment = DAG.getEVTAlign(VT.getScalarType());
7575 unsigned AS =
7576 PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7577 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7578 MachinePointerInfo(AS), MachineMemOperand::MOStore,
7579 MemoryLocation::UnknownSize, *Alignment, AAInfo);
7580 SDValue Base, Index, Scale;
7581 ISD::MemIndexType IndexType;
7582 bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7583 this, VPIntrin.getParent(),
7584 VT.getScalarStoreSize());
7585 if (!UniformBase) {
7586 Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7587 Index = getValue(PtrOperand);
7588 IndexType = ISD::SIGNED_SCALED;
7589 Scale =
7590 DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7591 }
7592 EVT IdxVT = Index.getValueType();
7593 EVT EltTy = IdxVT.getVectorElementType();
7594 if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7595 EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7596 Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7597 }
7598 ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7599 {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7600 OpValues[2], OpValues[3]},
7601 MMO, IndexType);
7602 DAG.setRoot(ST);
7603 setValue(&VPIntrin, ST);
7604 }
7605
visitVPStridedLoad(const VPIntrinsic & VPIntrin,EVT VT,SmallVectorImpl<SDValue> & OpValues)7606 void SelectionDAGBuilder::visitVPStridedLoad(
7607 const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
7608 SDLoc DL = getCurSDLoc();
7609 Value *PtrOperand = VPIntrin.getArgOperand(0);
7610 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7611 if (!Alignment)
7612 Alignment = DAG.getEVTAlign(VT.getScalarType());
7613 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7614 const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7615 MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7616 bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7617 SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7618 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7619 MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7620 MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7621
7622 SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7623 OpValues[2], OpValues[3], MMO,
7624 false /*IsExpanding*/);
7625
7626 if (AddToChain)
7627 PendingLoads.push_back(LD.getValue(1));
7628 setValue(&VPIntrin, LD);
7629 }
7630
visitVPStridedStore(const VPIntrinsic & VPIntrin,SmallVectorImpl<SDValue> & OpValues)7631 void SelectionDAGBuilder::visitVPStridedStore(
7632 const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
7633 SDLoc DL = getCurSDLoc();
7634 Value *PtrOperand = VPIntrin.getArgOperand(1);
7635 EVT VT = OpValues[0].getValueType();
7636 MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7637 if (!Alignment)
7638 Alignment = DAG.getEVTAlign(VT.getScalarType());
7639 AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7640 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7641 MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7642 MemoryLocation::UnknownSize, *Alignment, AAInfo);
7643
7644 SDValue ST = DAG.getStridedStoreVP(
7645 getMemoryRoot(), DL, OpValues[0], OpValues[1],
7646 DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7647 OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7648 /*IsCompressing*/ false);
7649
7650 DAG.setRoot(ST);
7651 setValue(&VPIntrin, ST);
7652 }
7653
visitVPCmp(const VPCmpIntrinsic & VPIntrin)7654 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7655 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7656 SDLoc DL = getCurSDLoc();
7657
7658 ISD::CondCode Condition;
7659 CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7660 bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7661 if (IsFP) {
7662 // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7663 // flags, but calls that don't return floating-point types can't be
7664 // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7665 Condition = getFCmpCondCode(CondCode);
7666 if (TM.Options.NoNaNsFPMath)
7667 Condition = getFCmpCodeWithoutNaN(Condition);
7668 } else {
7669 Condition = getICmpCondCode(CondCode);
7670 }
7671
7672 SDValue Op1 = getValue(VPIntrin.getOperand(0));
7673 SDValue Op2 = getValue(VPIntrin.getOperand(1));
7674 // #2 is the condition code
7675 SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7676 SDValue EVL = getValue(VPIntrin.getOperand(4));
7677 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7678 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7679 "Unexpected target EVL type");
7680 EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7681
7682 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7683 VPIntrin.getType());
7684 setValue(&VPIntrin,
7685 DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7686 }
7687
visitVectorPredicationIntrinsic(const VPIntrinsic & VPIntrin)7688 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7689 const VPIntrinsic &VPIntrin) {
7690 SDLoc DL = getCurSDLoc();
7691 unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7692
7693 auto IID = VPIntrin.getIntrinsicID();
7694
7695 if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7696 return visitVPCmp(*CmpI);
7697
7698 SmallVector<EVT, 4> ValueVTs;
7699 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7700 ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7701 SDVTList VTs = DAG.getVTList(ValueVTs);
7702
7703 auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7704
7705 MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7706 assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7707 "Unexpected target EVL type");
7708
7709 // Request operands.
7710 SmallVector<SDValue, 7> OpValues;
7711 for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7712 auto Op = getValue(VPIntrin.getArgOperand(I));
7713 if (I == EVLParamPos)
7714 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7715 OpValues.push_back(Op);
7716 }
7717
7718 switch (Opcode) {
7719 default: {
7720 SDNodeFlags SDFlags;
7721 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7722 SDFlags.copyFMF(*FPMO);
7723 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7724 setValue(&VPIntrin, Result);
7725 break;
7726 }
7727 case ISD::VP_LOAD:
7728 visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7729 break;
7730 case ISD::VP_GATHER:
7731 visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7732 break;
7733 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7734 visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7735 break;
7736 case ISD::VP_STORE:
7737 visitVPStore(VPIntrin, OpValues);
7738 break;
7739 case ISD::VP_SCATTER:
7740 visitVPScatter(VPIntrin, OpValues);
7741 break;
7742 case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7743 visitVPStridedStore(VPIntrin, OpValues);
7744 break;
7745 case ISD::VP_FMULADD: {
7746 assert(OpValues.size() == 5 && "Unexpected number of operands");
7747 SDNodeFlags SDFlags;
7748 if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7749 SDFlags.copyFMF(*FPMO);
7750 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7751 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7752 setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7753 } else {
7754 SDValue Mul = DAG.getNode(
7755 ISD::VP_FMUL, DL, VTs,
7756 {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7757 SDValue Add =
7758 DAG.getNode(ISD::VP_FADD, DL, VTs,
7759 {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7760 setValue(&VPIntrin, Add);
7761 }
7762 break;
7763 }
7764 case ISD::VP_INTTOPTR: {
7765 SDValue N = OpValues[0];
7766 EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
7767 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
7768 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7769 OpValues[2]);
7770 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7771 OpValues[2]);
7772 setValue(&VPIntrin, N);
7773 break;
7774 }
7775 case ISD::VP_PTRTOINT: {
7776 SDValue N = OpValues[0];
7777 EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7778 VPIntrin.getType());
7779 EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
7780 VPIntrin.getOperand(0)->getType());
7781 N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
7782 OpValues[2]);
7783 N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
7784 OpValues[2]);
7785 setValue(&VPIntrin, N);
7786 break;
7787 }
7788 case ISD::VP_ABS:
7789 case ISD::VP_CTLZ:
7790 case ISD::VP_CTLZ_ZERO_UNDEF:
7791 case ISD::VP_CTTZ:
7792 case ISD::VP_CTTZ_ZERO_UNDEF: {
7793 // Pop is_zero_poison operand for cp.ctlz/cttz or
7794 // is_int_min_poison operand for vp.abs.
7795 OpValues.pop_back();
7796 SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7797 setValue(&VPIntrin, Result);
7798 break;
7799 }
7800 }
7801 }
7802
lowerStartEH(SDValue Chain,const BasicBlock * EHPadBB,MCSymbol * & BeginLabel)7803 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7804 const BasicBlock *EHPadBB,
7805 MCSymbol *&BeginLabel) {
7806 MachineFunction &MF = DAG.getMachineFunction();
7807 MachineModuleInfo &MMI = MF.getMMI();
7808
7809 // Insert a label before the invoke call to mark the try range. This can be
7810 // used to detect deletion of the invoke via the MachineModuleInfo.
7811 BeginLabel = MMI.getContext().createTempSymbol();
7812
7813 // For SjLj, keep track of which landing pads go with which invokes
7814 // so as to maintain the ordering of pads in the LSDA.
7815 unsigned CallSiteIndex = MMI.getCurrentCallSite();
7816 if (CallSiteIndex) {
7817 MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7818 LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7819
7820 // Now that the call site is handled, stop tracking it.
7821 MMI.setCurrentCallSite(0);
7822 }
7823
7824 return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7825 }
7826
lowerEndEH(SDValue Chain,const InvokeInst * II,const BasicBlock * EHPadBB,MCSymbol * BeginLabel)7827 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7828 const BasicBlock *EHPadBB,
7829 MCSymbol *BeginLabel) {
7830 assert(BeginLabel && "BeginLabel should've been set");
7831
7832 MachineFunction &MF = DAG.getMachineFunction();
7833 MachineModuleInfo &MMI = MF.getMMI();
7834
7835 // Insert a label at the end of the invoke call to mark the try range. This
7836 // can be used to detect deletion of the invoke via the MachineModuleInfo.
7837 MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7838 Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7839
7840 // Inform MachineModuleInfo of range.
7841 auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7842 // There is a platform (e.g. wasm) that uses funclet style IR but does not
7843 // actually use outlined funclets and their LSDA info style.
7844 if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7845 assert(II && "II should've been set");
7846 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7847 EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7848 } else if (!isScopedEHPersonality(Pers)) {
7849 assert(EHPadBB);
7850 MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7851 }
7852
7853 return Chain;
7854 }
7855
7856 std::pair<SDValue, SDValue>
lowerInvokable(TargetLowering::CallLoweringInfo & CLI,const BasicBlock * EHPadBB)7857 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7858 const BasicBlock *EHPadBB) {
7859 MCSymbol *BeginLabel = nullptr;
7860
7861 if (EHPadBB) {
7862 // Both PendingLoads and PendingExports must be flushed here;
7863 // this call might not return.
7864 (void)getRoot();
7865 DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7866 CLI.setChain(getRoot());
7867 }
7868
7869 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7870 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7871
7872 assert((CLI.IsTailCall || Result.second.getNode()) &&
7873 "Non-null chain expected with non-tail call!");
7874 assert((Result.second.getNode() || !Result.first.getNode()) &&
7875 "Null value expected with tail call!");
7876
7877 if (!Result.second.getNode()) {
7878 // As a special case, a null chain means that a tail call has been emitted
7879 // and the DAG root is already updated.
7880 HasTailCall = true;
7881
7882 // Since there's no actual continuation from this block, nothing can be
7883 // relying on us setting vregs for them.
7884 PendingExports.clear();
7885 } else {
7886 DAG.setRoot(Result.second);
7887 }
7888
7889 if (EHPadBB) {
7890 DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7891 BeginLabel));
7892 }
7893
7894 return Result;
7895 }
7896
LowerCallTo(const CallBase & CB,SDValue Callee,bool isTailCall,bool isMustTailCall,const BasicBlock * EHPadBB)7897 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7898 bool isTailCall,
7899 bool isMustTailCall,
7900 const BasicBlock *EHPadBB) {
7901 auto &DL = DAG.getDataLayout();
7902 FunctionType *FTy = CB.getFunctionType();
7903 Type *RetTy = CB.getType();
7904
7905 TargetLowering::ArgListTy Args;
7906 Args.reserve(CB.arg_size());
7907
7908 const Value *SwiftErrorVal = nullptr;
7909 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7910
7911 if (isTailCall) {
7912 // Avoid emitting tail calls in functions with the disable-tail-calls
7913 // attribute.
7914 auto *Caller = CB.getParent()->getParent();
7915 if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7916 "true" && !isMustTailCall)
7917 isTailCall = false;
7918
7919 // We can't tail call inside a function with a swifterror argument. Lowering
7920 // does not support this yet. It would have to move into the swifterror
7921 // register before the call.
7922 if (TLI.supportSwiftError() &&
7923 Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7924 isTailCall = false;
7925 }
7926
7927 for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7928 TargetLowering::ArgListEntry Entry;
7929 const Value *V = *I;
7930
7931 // Skip empty types
7932 if (V->getType()->isEmptyTy())
7933 continue;
7934
7935 SDValue ArgNode = getValue(V);
7936 Entry.Node = ArgNode; Entry.Ty = V->getType();
7937
7938 Entry.setAttributes(&CB, I - CB.arg_begin());
7939
7940 // Use swifterror virtual register as input to the call.
7941 if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7942 SwiftErrorVal = V;
7943 // We find the virtual register for the actual swifterror argument.
7944 // Instead of using the Value, we use the virtual register instead.
7945 Entry.Node =
7946 DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7947 EVT(TLI.getPointerTy(DL)));
7948 }
7949
7950 Args.push_back(Entry);
7951
7952 // If we have an explicit sret argument that is an Instruction, (i.e., it
7953 // might point to function-local memory), we can't meaningfully tail-call.
7954 if (Entry.IsSRet && isa<Instruction>(V))
7955 isTailCall = false;
7956 }
7957
7958 // If call site has a cfguardtarget operand bundle, create and add an
7959 // additional ArgListEntry.
7960 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7961 TargetLowering::ArgListEntry Entry;
7962 Value *V = Bundle->Inputs[0];
7963 SDValue ArgNode = getValue(V);
7964 Entry.Node = ArgNode;
7965 Entry.Ty = V->getType();
7966 Entry.IsCFGuardTarget = true;
7967 Args.push_back(Entry);
7968 }
7969
7970 // Check if target-independent constraints permit a tail call here.
7971 // Target-dependent constraints are checked within TLI->LowerCallTo.
7972 if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7973 isTailCall = false;
7974
7975 // Disable tail calls if there is an swifterror argument. Targets have not
7976 // been updated to support tail calls.
7977 if (TLI.supportSwiftError() && SwiftErrorVal)
7978 isTailCall = false;
7979
7980 ConstantInt *CFIType = nullptr;
7981 if (CB.isIndirectCall()) {
7982 if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
7983 if (!TLI.supportKCFIBundles())
7984 report_fatal_error(
7985 "Target doesn't support calls with kcfi operand bundles.");
7986 CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
7987 assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
7988 }
7989 }
7990
7991 TargetLowering::CallLoweringInfo CLI(DAG);
7992 CLI.setDebugLoc(getCurSDLoc())
7993 .setChain(getRoot())
7994 .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7995 .setTailCall(isTailCall)
7996 .setConvergent(CB.isConvergent())
7997 .setIsPreallocated(
7998 CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
7999 .setCFIType(CFIType);
8000 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8001
8002 if (Result.first.getNode()) {
8003 Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8004 setValue(&CB, Result.first);
8005 }
8006
8007 // The last element of CLI.InVals has the SDValue for swifterror return.
8008 // Here we copy it to a virtual register and update SwiftErrorMap for
8009 // book-keeping.
8010 if (SwiftErrorVal && TLI.supportSwiftError()) {
8011 // Get the last element of InVals.
8012 SDValue Src = CLI.InVals.back();
8013 Register VReg =
8014 SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8015 SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8016 DAG.setRoot(CopyNode);
8017 }
8018 }
8019
getMemCmpLoad(const Value * PtrVal,MVT LoadVT,SelectionDAGBuilder & Builder)8020 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8021 SelectionDAGBuilder &Builder) {
8022 // Check to see if this load can be trivially constant folded, e.g. if the
8023 // input is from a string literal.
8024 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8025 // Cast pointer to the type we really want to load.
8026 Type *LoadTy =
8027 Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8028 if (LoadVT.isVector())
8029 LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8030
8031 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8032 PointerType::getUnqual(LoadTy));
8033
8034 if (const Constant *LoadCst =
8035 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8036 LoadTy, Builder.DAG.getDataLayout()))
8037 return Builder.getValue(LoadCst);
8038 }
8039
8040 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
8041 // still constant memory, the input chain can be the entry node.
8042 SDValue Root;
8043 bool ConstantMemory = false;
8044
8045 // Do not serialize (non-volatile) loads of constant memory with anything.
8046 if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8047 Root = Builder.DAG.getEntryNode();
8048 ConstantMemory = true;
8049 } else {
8050 // Do not serialize non-volatile loads against each other.
8051 Root = Builder.DAG.getRoot();
8052 }
8053
8054 SDValue Ptr = Builder.getValue(PtrVal);
8055 SDValue LoadVal =
8056 Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8057 MachinePointerInfo(PtrVal), Align(1));
8058
8059 if (!ConstantMemory)
8060 Builder.PendingLoads.push_back(LoadVal.getValue(1));
8061 return LoadVal;
8062 }
8063
8064 /// Record the value for an instruction that produces an integer result,
8065 /// converting the type where necessary.
processIntegerCallValue(const Instruction & I,SDValue Value,bool IsSigned)8066 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8067 SDValue Value,
8068 bool IsSigned) {
8069 EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8070 I.getType(), true);
8071 if (IsSigned)
8072 Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
8073 else
8074 Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
8075 setValue(&I, Value);
8076 }
8077
8078 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8079 /// true and lower it. Otherwise return false, and it will be lowered like a
8080 /// normal call.
8081 /// The caller already checked that \p I calls the appropriate LibFunc with a
8082 /// correct prototype.
visitMemCmpBCmpCall(const CallInst & I)8083 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8084 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8085 const Value *Size = I.getArgOperand(2);
8086 const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8087 if (CSize && CSize->getZExtValue() == 0) {
8088 EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8089 I.getType(), true);
8090 setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8091 return true;
8092 }
8093
8094 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8095 std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8096 DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8097 getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8098 if (Res.first.getNode()) {
8099 processIntegerCallValue(I, Res.first, true);
8100 PendingLoads.push_back(Res.second);
8101 return true;
8102 }
8103
8104 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
8105 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
8106 if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8107 return false;
8108
8109 // If the target has a fast compare for the given size, it will return a
8110 // preferred load type for that size. Require that the load VT is legal and
8111 // that the target supports unaligned loads of that type. Otherwise, return
8112 // INVALID.
8113 auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8114 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8115 MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8116 if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8117 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8118 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8119 // TODO: Check alignment of src and dest ptrs.
8120 unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8121 unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8122 if (!TLI.isTypeLegal(LVT) ||
8123 !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8124 !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8125 LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8126 }
8127
8128 return LVT;
8129 };
8130
8131 // This turns into unaligned loads. We only do this if the target natively
8132 // supports the MVT we'll be loading or if it is small enough (<= 4) that
8133 // we'll only produce a small number of byte loads.
8134 MVT LoadVT;
8135 unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8136 switch (NumBitsToCompare) {
8137 default:
8138 return false;
8139 case 16:
8140 LoadVT = MVT::i16;
8141 break;
8142 case 32:
8143 LoadVT = MVT::i32;
8144 break;
8145 case 64:
8146 case 128:
8147 case 256:
8148 LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8149 break;
8150 }
8151
8152 if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8153 return false;
8154
8155 SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8156 SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8157
8158 // Bitcast to a wide integer type if the loads are vectors.
8159 if (LoadVT.isVector()) {
8160 EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8161 LoadL = DAG.getBitcast(CmpVT, LoadL);
8162 LoadR = DAG.getBitcast(CmpVT, LoadR);
8163 }
8164
8165 SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8166 processIntegerCallValue(I, Cmp, false);
8167 return true;
8168 }
8169
8170 /// See if we can lower a memchr call into an optimized form. If so, return
8171 /// true and lower it. Otherwise return false, and it will be lowered like a
8172 /// normal call.
8173 /// The caller already checked that \p I calls the appropriate LibFunc with a
8174 /// correct prototype.
visitMemChrCall(const CallInst & I)8175 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8176 const Value *Src = I.getArgOperand(0);
8177 const Value *Char = I.getArgOperand(1);
8178 const Value *Length = I.getArgOperand(2);
8179
8180 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8181 std::pair<SDValue, SDValue> Res =
8182 TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8183 getValue(Src), getValue(Char), getValue(Length),
8184 MachinePointerInfo(Src));
8185 if (Res.first.getNode()) {
8186 setValue(&I, Res.first);
8187 PendingLoads.push_back(Res.second);
8188 return true;
8189 }
8190
8191 return false;
8192 }
8193
8194 /// See if we can lower a mempcpy call into an optimized form. If so, return
8195 /// true and lower it. Otherwise return false, and it will be lowered like a
8196 /// normal call.
8197 /// The caller already checked that \p I calls the appropriate LibFunc with a
8198 /// correct prototype.
visitMemPCpyCall(const CallInst & I)8199 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8200 SDValue Dst = getValue(I.getArgOperand(0));
8201 SDValue Src = getValue(I.getArgOperand(1));
8202 SDValue Size = getValue(I.getArgOperand(2));
8203
8204 Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8205 Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8206 // DAG::getMemcpy needs Alignment to be defined.
8207 Align Alignment = std::min(DstAlign, SrcAlign);
8208
8209 bool isVol = false;
8210 SDLoc sdl = getCurSDLoc();
8211
8212 // In the mempcpy context we need to pass in a false value for isTailCall
8213 // because the return pointer needs to be adjusted by the size of
8214 // the copied memory.
8215 SDValue Root = isVol ? getRoot() : getMemoryRoot();
8216 SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8217 /*isTailCall=*/false,
8218 MachinePointerInfo(I.getArgOperand(0)),
8219 MachinePointerInfo(I.getArgOperand(1)),
8220 I.getAAMetadata());
8221 assert(MC.getNode() != nullptr &&
8222 "** memcpy should not be lowered as TailCall in mempcpy context **");
8223 DAG.setRoot(MC);
8224
8225 // Check if Size needs to be truncated or extended.
8226 Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8227
8228 // Adjust return pointer to point just past the last dst byte.
8229 SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8230 Dst, Size);
8231 setValue(&I, DstPlusSize);
8232 return true;
8233 }
8234
8235 /// See if we can lower a strcpy call into an optimized form. If so, return
8236 /// true and lower it, otherwise return false and it will be lowered like a
8237 /// normal call.
8238 /// The caller already checked that \p I calls the appropriate LibFunc with a
8239 /// correct prototype.
visitStrCpyCall(const CallInst & I,bool isStpcpy)8240 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8241 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8242
8243 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8244 std::pair<SDValue, SDValue> Res =
8245 TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8246 getValue(Arg0), getValue(Arg1),
8247 MachinePointerInfo(Arg0),
8248 MachinePointerInfo(Arg1), isStpcpy);
8249 if (Res.first.getNode()) {
8250 setValue(&I, Res.first);
8251 DAG.setRoot(Res.second);
8252 return true;
8253 }
8254
8255 return false;
8256 }
8257
8258 /// See if we can lower a strcmp call into an optimized form. If so, return
8259 /// true and lower it, otherwise return false and it will be lowered like a
8260 /// normal call.
8261 /// The caller already checked that \p I calls the appropriate LibFunc with a
8262 /// correct prototype.
visitStrCmpCall(const CallInst & I)8263 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8264 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8265
8266 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8267 std::pair<SDValue, SDValue> Res =
8268 TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8269 getValue(Arg0), getValue(Arg1),
8270 MachinePointerInfo(Arg0),
8271 MachinePointerInfo(Arg1));
8272 if (Res.first.getNode()) {
8273 processIntegerCallValue(I, Res.first, true);
8274 PendingLoads.push_back(Res.second);
8275 return true;
8276 }
8277
8278 return false;
8279 }
8280
8281 /// See if we can lower a strlen call into an optimized form. If so, return
8282 /// true and lower it, otherwise return false and it will be lowered like a
8283 /// normal call.
8284 /// The caller already checked that \p I calls the appropriate LibFunc with a
8285 /// correct prototype.
visitStrLenCall(const CallInst & I)8286 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8287 const Value *Arg0 = I.getArgOperand(0);
8288
8289 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8290 std::pair<SDValue, SDValue> Res =
8291 TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8292 getValue(Arg0), MachinePointerInfo(Arg0));
8293 if (Res.first.getNode()) {
8294 processIntegerCallValue(I, Res.first, false);
8295 PendingLoads.push_back(Res.second);
8296 return true;
8297 }
8298
8299 return false;
8300 }
8301
8302 /// See if we can lower a strnlen call into an optimized form. If so, return
8303 /// true and lower it, otherwise return false and it will be lowered like a
8304 /// normal call.
8305 /// The caller already checked that \p I calls the appropriate LibFunc with a
8306 /// correct prototype.
visitStrNLenCall(const CallInst & I)8307 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8308 const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8309
8310 const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8311 std::pair<SDValue, SDValue> Res =
8312 TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8313 getValue(Arg0), getValue(Arg1),
8314 MachinePointerInfo(Arg0));
8315 if (Res.first.getNode()) {
8316 processIntegerCallValue(I, Res.first, false);
8317 PendingLoads.push_back(Res.second);
8318 return true;
8319 }
8320
8321 return false;
8322 }
8323
8324 /// See if we can lower a unary floating-point operation into an SDNode with
8325 /// the specified Opcode. If so, return true and lower it, otherwise return
8326 /// false and it will be lowered like a normal call.
8327 /// The caller already checked that \p I calls the appropriate LibFunc with a
8328 /// correct prototype.
visitUnaryFloatCall(const CallInst & I,unsigned Opcode)8329 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8330 unsigned Opcode) {
8331 // We already checked this call's prototype; verify it doesn't modify errno.
8332 if (!I.onlyReadsMemory())
8333 return false;
8334
8335 SDNodeFlags Flags;
8336 Flags.copyFMF(cast<FPMathOperator>(I));
8337
8338 SDValue Tmp = getValue(I.getArgOperand(0));
8339 setValue(&I,
8340 DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8341 return true;
8342 }
8343
8344 /// See if we can lower a binary floating-point operation into an SDNode with
8345 /// the specified Opcode. If so, return true and lower it. Otherwise return
8346 /// false, and it will be lowered like a normal call.
8347 /// The caller already checked that \p I calls the appropriate LibFunc with a
8348 /// correct prototype.
visitBinaryFloatCall(const CallInst & I,unsigned Opcode)8349 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8350 unsigned Opcode) {
8351 // We already checked this call's prototype; verify it doesn't modify errno.
8352 if (!I.onlyReadsMemory())
8353 return false;
8354
8355 SDNodeFlags Flags;
8356 Flags.copyFMF(cast<FPMathOperator>(I));
8357
8358 SDValue Tmp0 = getValue(I.getArgOperand(0));
8359 SDValue Tmp1 = getValue(I.getArgOperand(1));
8360 EVT VT = Tmp0.getValueType();
8361 setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8362 return true;
8363 }
8364
visitCall(const CallInst & I)8365 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8366 // Handle inline assembly differently.
8367 if (I.isInlineAsm()) {
8368 visitInlineAsm(I);
8369 return;
8370 }
8371
8372 diagnoseDontCall(I);
8373
8374 if (Function *F = I.getCalledFunction()) {
8375 if (F->isDeclaration()) {
8376 // Is this an LLVM intrinsic or a target-specific intrinsic?
8377 unsigned IID = F->getIntrinsicID();
8378 if (!IID)
8379 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8380 IID = II->getIntrinsicID(F);
8381
8382 if (IID) {
8383 visitIntrinsicCall(I, IID);
8384 return;
8385 }
8386 }
8387
8388 // Check for well-known libc/libm calls. If the function is internal, it
8389 // can't be a library call. Don't do the check if marked as nobuiltin for
8390 // some reason or the call site requires strict floating point semantics.
8391 LibFunc Func;
8392 if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8393 F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8394 LibInfo->hasOptimizedCodeGen(Func)) {
8395 switch (Func) {
8396 default: break;
8397 case LibFunc_bcmp:
8398 if (visitMemCmpBCmpCall(I))
8399 return;
8400 break;
8401 case LibFunc_copysign:
8402 case LibFunc_copysignf:
8403 case LibFunc_copysignl:
8404 // We already checked this call's prototype; verify it doesn't modify
8405 // errno.
8406 if (I.onlyReadsMemory()) {
8407 SDValue LHS = getValue(I.getArgOperand(0));
8408 SDValue RHS = getValue(I.getArgOperand(1));
8409 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8410 LHS.getValueType(), LHS, RHS));
8411 return;
8412 }
8413 break;
8414 case LibFunc_fabs:
8415 case LibFunc_fabsf:
8416 case LibFunc_fabsl:
8417 if (visitUnaryFloatCall(I, ISD::FABS))
8418 return;
8419 break;
8420 case LibFunc_fmin:
8421 case LibFunc_fminf:
8422 case LibFunc_fminl:
8423 if (visitBinaryFloatCall(I, ISD::FMINNUM))
8424 return;
8425 break;
8426 case LibFunc_fmax:
8427 case LibFunc_fmaxf:
8428 case LibFunc_fmaxl:
8429 if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8430 return;
8431 break;
8432 case LibFunc_sin:
8433 case LibFunc_sinf:
8434 case LibFunc_sinl:
8435 if (visitUnaryFloatCall(I, ISD::FSIN))
8436 return;
8437 break;
8438 case LibFunc_cos:
8439 case LibFunc_cosf:
8440 case LibFunc_cosl:
8441 if (visitUnaryFloatCall(I, ISD::FCOS))
8442 return;
8443 break;
8444 case LibFunc_sqrt:
8445 case LibFunc_sqrtf:
8446 case LibFunc_sqrtl:
8447 case LibFunc_sqrt_finite:
8448 case LibFunc_sqrtf_finite:
8449 case LibFunc_sqrtl_finite:
8450 if (visitUnaryFloatCall(I, ISD::FSQRT))
8451 return;
8452 break;
8453 case LibFunc_floor:
8454 case LibFunc_floorf:
8455 case LibFunc_floorl:
8456 if (visitUnaryFloatCall(I, ISD::FFLOOR))
8457 return;
8458 break;
8459 case LibFunc_nearbyint:
8460 case LibFunc_nearbyintf:
8461 case LibFunc_nearbyintl:
8462 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8463 return;
8464 break;
8465 case LibFunc_ceil:
8466 case LibFunc_ceilf:
8467 case LibFunc_ceill:
8468 if (visitUnaryFloatCall(I, ISD::FCEIL))
8469 return;
8470 break;
8471 case LibFunc_rint:
8472 case LibFunc_rintf:
8473 case LibFunc_rintl:
8474 if (visitUnaryFloatCall(I, ISD::FRINT))
8475 return;
8476 break;
8477 case LibFunc_round:
8478 case LibFunc_roundf:
8479 case LibFunc_roundl:
8480 if (visitUnaryFloatCall(I, ISD::FROUND))
8481 return;
8482 break;
8483 case LibFunc_trunc:
8484 case LibFunc_truncf:
8485 case LibFunc_truncl:
8486 if (visitUnaryFloatCall(I, ISD::FTRUNC))
8487 return;
8488 break;
8489 case LibFunc_log2:
8490 case LibFunc_log2f:
8491 case LibFunc_log2l:
8492 if (visitUnaryFloatCall(I, ISD::FLOG2))
8493 return;
8494 break;
8495 case LibFunc_exp2:
8496 case LibFunc_exp2f:
8497 case LibFunc_exp2l:
8498 if (visitUnaryFloatCall(I, ISD::FEXP2))
8499 return;
8500 break;
8501 case LibFunc_memcmp:
8502 if (visitMemCmpBCmpCall(I))
8503 return;
8504 break;
8505 case LibFunc_mempcpy:
8506 if (visitMemPCpyCall(I))
8507 return;
8508 break;
8509 case LibFunc_memchr:
8510 if (visitMemChrCall(I))
8511 return;
8512 break;
8513 case LibFunc_strcpy:
8514 if (visitStrCpyCall(I, false))
8515 return;
8516 break;
8517 case LibFunc_stpcpy:
8518 if (visitStrCpyCall(I, true))
8519 return;
8520 break;
8521 case LibFunc_strcmp:
8522 if (visitStrCmpCall(I))
8523 return;
8524 break;
8525 case LibFunc_strlen:
8526 if (visitStrLenCall(I))
8527 return;
8528 break;
8529 case LibFunc_strnlen:
8530 if (visitStrNLenCall(I))
8531 return;
8532 break;
8533 }
8534 }
8535 }
8536
8537 // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8538 // have to do anything here to lower funclet bundles.
8539 // CFGuardTarget bundles are lowered in LowerCallTo.
8540 assert(!I.hasOperandBundlesOtherThan(
8541 {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8542 LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8543 LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8544 "Cannot lower calls with arbitrary operand bundles!");
8545
8546 SDValue Callee = getValue(I.getCalledOperand());
8547
8548 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8549 LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8550 else
8551 // Check if we can potentially perform a tail call. More detailed checking
8552 // is be done within LowerCallTo, after more information about the call is
8553 // known.
8554 LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8555 }
8556
8557 namespace {
8558
8559 /// AsmOperandInfo - This contains information for each constraint that we are
8560 /// lowering.
8561 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8562 public:
8563 /// CallOperand - If this is the result output operand or a clobber
8564 /// this is null, otherwise it is the incoming operand to the CallInst.
8565 /// This gets modified as the asm is processed.
8566 SDValue CallOperand;
8567
8568 /// AssignedRegs - If this is a register or register class operand, this
8569 /// contains the set of register corresponding to the operand.
8570 RegsForValue AssignedRegs;
8571
SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo & info)8572 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8573 : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8574 }
8575
8576 /// Whether or not this operand accesses memory
hasMemory(const TargetLowering & TLI) const8577 bool hasMemory(const TargetLowering &TLI) const {
8578 // Indirect operand accesses access memory.
8579 if (isIndirect)
8580 return true;
8581
8582 for (const auto &Code : Codes)
8583 if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8584 return true;
8585
8586 return false;
8587 }
8588 };
8589
8590
8591 } // end anonymous namespace
8592
8593 /// Make sure that the output operand \p OpInfo and its corresponding input
8594 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8595 /// out).
patchMatchingInput(const SDISelAsmOperandInfo & OpInfo,SDISelAsmOperandInfo & MatchingOpInfo,SelectionDAG & DAG)8596 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8597 SDISelAsmOperandInfo &MatchingOpInfo,
8598 SelectionDAG &DAG) {
8599 if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8600 return;
8601
8602 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8603 const auto &TLI = DAG.getTargetLoweringInfo();
8604
8605 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8606 TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8607 OpInfo.ConstraintVT);
8608 std::pair<unsigned, const TargetRegisterClass *> InputRC =
8609 TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8610 MatchingOpInfo.ConstraintVT);
8611 if ((OpInfo.ConstraintVT.isInteger() !=
8612 MatchingOpInfo.ConstraintVT.isInteger()) ||
8613 (MatchRC.second != InputRC.second)) {
8614 // FIXME: error out in a more elegant fashion
8615 report_fatal_error("Unsupported asm: input constraint"
8616 " with a matching output constraint of"
8617 " incompatible type!");
8618 }
8619 MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8620 }
8621
8622 /// Get a direct memory input to behave well as an indirect operand.
8623 /// This may introduce stores, hence the need for a \p Chain.
8624 /// \return The (possibly updated) chain.
getAddressForMemoryInput(SDValue Chain,const SDLoc & Location,SDISelAsmOperandInfo & OpInfo,SelectionDAG & DAG)8625 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8626 SDISelAsmOperandInfo &OpInfo,
8627 SelectionDAG &DAG) {
8628 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8629
8630 // If we don't have an indirect input, put it in the constpool if we can,
8631 // otherwise spill it to a stack slot.
8632 // TODO: This isn't quite right. We need to handle these according to
8633 // the addressing mode that the constraint wants. Also, this may take
8634 // an additional register for the computation and we don't want that
8635 // either.
8636
8637 // If the operand is a float, integer, or vector constant, spill to a
8638 // constant pool entry to get its address.
8639 const Value *OpVal = OpInfo.CallOperandVal;
8640 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8641 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8642 OpInfo.CallOperand = DAG.getConstantPool(
8643 cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8644 return Chain;
8645 }
8646
8647 // Otherwise, create a stack slot and emit a store to it before the asm.
8648 Type *Ty = OpVal->getType();
8649 auto &DL = DAG.getDataLayout();
8650 uint64_t TySize = DL.getTypeAllocSize(Ty);
8651 MachineFunction &MF = DAG.getMachineFunction();
8652 int SSFI = MF.getFrameInfo().CreateStackObject(
8653 TySize, DL.getPrefTypeAlign(Ty), false);
8654 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8655 Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8656 MachinePointerInfo::getFixedStack(MF, SSFI),
8657 TLI.getMemValueType(DL, Ty));
8658 OpInfo.CallOperand = StackSlot;
8659
8660 return Chain;
8661 }
8662
8663 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8664 /// specified operand. We prefer to assign virtual registers, to allow the
8665 /// register allocator to handle the assignment process. However, if the asm
8666 /// uses features that we can't model on machineinstrs, we have SDISel do the
8667 /// allocation. This produces generally horrible, but correct, code.
8668 ///
8669 /// OpInfo describes the operand
8670 /// RefOpInfo describes the matching operand if any, the operand otherwise
8671 static std::optional<unsigned>
getRegistersForValue(SelectionDAG & DAG,const SDLoc & DL,SDISelAsmOperandInfo & OpInfo,SDISelAsmOperandInfo & RefOpInfo)8672 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8673 SDISelAsmOperandInfo &OpInfo,
8674 SDISelAsmOperandInfo &RefOpInfo) {
8675 LLVMContext &Context = *DAG.getContext();
8676 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8677
8678 MachineFunction &MF = DAG.getMachineFunction();
8679 SmallVector<unsigned, 4> Regs;
8680 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8681
8682 // No work to do for memory/address operands.
8683 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8684 OpInfo.ConstraintType == TargetLowering::C_Address)
8685 return std::nullopt;
8686
8687 // If this is a constraint for a single physreg, or a constraint for a
8688 // register class, find it.
8689 unsigned AssignedReg;
8690 const TargetRegisterClass *RC;
8691 std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8692 &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8693 // RC is unset only on failure. Return immediately.
8694 if (!RC)
8695 return std::nullopt;
8696
8697 // Get the actual register value type. This is important, because the user
8698 // may have asked for (e.g.) the AX register in i32 type. We need to
8699 // remember that AX is actually i16 to get the right extension.
8700 const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8701
8702 if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8703 // If this is an FP operand in an integer register (or visa versa), or more
8704 // generally if the operand value disagrees with the register class we plan
8705 // to stick it in, fix the operand type.
8706 //
8707 // If this is an input value, the bitcast to the new type is done now.
8708 // Bitcast for output value is done at the end of visitInlineAsm().
8709 if ((OpInfo.Type == InlineAsm::isOutput ||
8710 OpInfo.Type == InlineAsm::isInput) &&
8711 !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8712 // Try to convert to the first EVT that the reg class contains. If the
8713 // types are identical size, use a bitcast to convert (e.g. two differing
8714 // vector types). Note: output bitcast is done at the end of
8715 // visitInlineAsm().
8716 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8717 // Exclude indirect inputs while they are unsupported because the code
8718 // to perform the load is missing and thus OpInfo.CallOperand still
8719 // refers to the input address rather than the pointed-to value.
8720 if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8721 OpInfo.CallOperand =
8722 DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8723 OpInfo.ConstraintVT = RegVT;
8724 // If the operand is an FP value and we want it in integer registers,
8725 // use the corresponding integer type. This turns an f64 value into
8726 // i64, which can be passed with two i32 values on a 32-bit machine.
8727 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8728 MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8729 if (OpInfo.Type == InlineAsm::isInput)
8730 OpInfo.CallOperand =
8731 DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8732 OpInfo.ConstraintVT = VT;
8733 }
8734 }
8735 }
8736
8737 // No need to allocate a matching input constraint since the constraint it's
8738 // matching to has already been allocated.
8739 if (OpInfo.isMatchingInputConstraint())
8740 return std::nullopt;
8741
8742 EVT ValueVT = OpInfo.ConstraintVT;
8743 if (OpInfo.ConstraintVT == MVT::Other)
8744 ValueVT = RegVT;
8745
8746 // Initialize NumRegs.
8747 unsigned NumRegs = 1;
8748 if (OpInfo.ConstraintVT != MVT::Other)
8749 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8750
8751 // If this is a constraint for a specific physical register, like {r17},
8752 // assign it now.
8753
8754 // If this associated to a specific register, initialize iterator to correct
8755 // place. If virtual, make sure we have enough registers
8756
8757 // Initialize iterator if necessary
8758 TargetRegisterClass::iterator I = RC->begin();
8759 MachineRegisterInfo &RegInfo = MF.getRegInfo();
8760
8761 // Do not check for single registers.
8762 if (AssignedReg) {
8763 I = std::find(I, RC->end(), AssignedReg);
8764 if (I == RC->end()) {
8765 // RC does not contain the selected register, which indicates a
8766 // mismatch between the register and the required type/bitwidth.
8767 return {AssignedReg};
8768 }
8769 }
8770
8771 for (; NumRegs; --NumRegs, ++I) {
8772 assert(I != RC->end() && "Ran out of registers to allocate!");
8773 Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8774 Regs.push_back(R);
8775 }
8776
8777 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8778 return std::nullopt;
8779 }
8780
8781 static unsigned
findMatchingInlineAsmOperand(unsigned OperandNo,const std::vector<SDValue> & AsmNodeOperands)8782 findMatchingInlineAsmOperand(unsigned OperandNo,
8783 const std::vector<SDValue> &AsmNodeOperands) {
8784 // Scan until we find the definition we already emitted of this operand.
8785 unsigned CurOp = InlineAsm::Op_FirstOperand;
8786 for (; OperandNo; --OperandNo) {
8787 // Advance to the next operand.
8788 unsigned OpFlag =
8789 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8790 assert((InlineAsm::isRegDefKind(OpFlag) ||
8791 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8792 InlineAsm::isMemKind(OpFlag)) &&
8793 "Skipped past definitions?");
8794 CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8795 }
8796 return CurOp;
8797 }
8798
8799 namespace {
8800
8801 class ExtraFlags {
8802 unsigned Flags = 0;
8803
8804 public:
ExtraFlags(const CallBase & Call)8805 explicit ExtraFlags(const CallBase &Call) {
8806 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8807 if (IA->hasSideEffects())
8808 Flags |= InlineAsm::Extra_HasSideEffects;
8809 if (IA->isAlignStack())
8810 Flags |= InlineAsm::Extra_IsAlignStack;
8811 if (Call.isConvergent())
8812 Flags |= InlineAsm::Extra_IsConvergent;
8813 Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8814 }
8815
update(const TargetLowering::AsmOperandInfo & OpInfo)8816 void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8817 // Ideally, we would only check against memory constraints. However, the
8818 // meaning of an Other constraint can be target-specific and we can't easily
8819 // reason about it. Therefore, be conservative and set MayLoad/MayStore
8820 // for Other constraints as well.
8821 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8822 OpInfo.ConstraintType == TargetLowering::C_Other) {
8823 if (OpInfo.Type == InlineAsm::isInput)
8824 Flags |= InlineAsm::Extra_MayLoad;
8825 else if (OpInfo.Type == InlineAsm::isOutput)
8826 Flags |= InlineAsm::Extra_MayStore;
8827 else if (OpInfo.Type == InlineAsm::isClobber)
8828 Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8829 }
8830 }
8831
get() const8832 unsigned get() const { return Flags; }
8833 };
8834
8835 } // end anonymous namespace
8836
isFunction(SDValue Op)8837 static bool isFunction(SDValue Op) {
8838 if (Op && Op.getOpcode() == ISD::GlobalAddress) {
8839 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8840 auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
8841
8842 // In normal "call dllimport func" instruction (non-inlineasm) it force
8843 // indirect access by specifing call opcode. And usually specially print
8844 // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
8845 // not do in this way now. (In fact, this is similar with "Data Access"
8846 // action). So here we ignore dllimport function.
8847 if (Fn && !Fn->hasDLLImportStorageClass())
8848 return true;
8849 }
8850 }
8851 return false;
8852 }
8853
8854 /// visitInlineAsm - Handle a call to an InlineAsm object.
visitInlineAsm(const CallBase & Call,const BasicBlock * EHPadBB)8855 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8856 const BasicBlock *EHPadBB) {
8857 const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8858
8859 /// ConstraintOperands - Information about all of the constraints.
8860 SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8861
8862 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8863 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8864 DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8865
8866 // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8867 // AsmDialect, MayLoad, MayStore).
8868 bool HasSideEffect = IA->hasSideEffects();
8869 ExtraFlags ExtraInfo(Call);
8870
8871 for (auto &T : TargetConstraints) {
8872 ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8873 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8874
8875 if (OpInfo.CallOperandVal)
8876 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8877
8878 if (!HasSideEffect)
8879 HasSideEffect = OpInfo.hasMemory(TLI);
8880
8881 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8882 // FIXME: Could we compute this on OpInfo rather than T?
8883
8884 // Compute the constraint code and ConstraintType to use.
8885 TLI.ComputeConstraintToUse(T, SDValue());
8886
8887 if (T.ConstraintType == TargetLowering::C_Immediate &&
8888 OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8889 // We've delayed emitting a diagnostic like the "n" constraint because
8890 // inlining could cause an integer showing up.
8891 return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8892 "' expects an integer constant "
8893 "expression");
8894
8895 ExtraInfo.update(T);
8896 }
8897
8898 // We won't need to flush pending loads if this asm doesn't touch
8899 // memory and is nonvolatile.
8900 SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8901
8902 bool EmitEHLabels = isa<InvokeInst>(Call);
8903 if (EmitEHLabels) {
8904 assert(EHPadBB && "InvokeInst must have an EHPadBB");
8905 }
8906 bool IsCallBr = isa<CallBrInst>(Call);
8907
8908 if (IsCallBr || EmitEHLabels) {
8909 // If this is a callbr or invoke we need to flush pending exports since
8910 // inlineasm_br and invoke are terminators.
8911 // We need to do this before nodes are glued to the inlineasm_br node.
8912 Chain = getControlRoot();
8913 }
8914
8915 MCSymbol *BeginLabel = nullptr;
8916 if (EmitEHLabels) {
8917 Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8918 }
8919
8920 int OpNo = -1;
8921 SmallVector<StringRef> AsmStrs;
8922 IA->collectAsmStrs(AsmStrs);
8923
8924 // Second pass over the constraints: compute which constraint option to use.
8925 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8926 if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
8927 OpNo++;
8928
8929 // If this is an output operand with a matching input operand, look up the
8930 // matching input. If their types mismatch, e.g. one is an integer, the
8931 // other is floating point, or their sizes are different, flag it as an
8932 // error.
8933 if (OpInfo.hasMatchingInput()) {
8934 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8935 patchMatchingInput(OpInfo, Input, DAG);
8936 }
8937
8938 // Compute the constraint code and ConstraintType to use.
8939 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8940
8941 if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8942 OpInfo.Type == InlineAsm::isClobber) ||
8943 OpInfo.ConstraintType == TargetLowering::C_Address)
8944 continue;
8945
8946 // In Linux PIC model, there are 4 cases about value/label addressing:
8947 //
8948 // 1: Function call or Label jmp inside the module.
8949 // 2: Data access (such as global variable, static variable) inside module.
8950 // 3: Function call or Label jmp outside the module.
8951 // 4: Data access (such as global variable) outside the module.
8952 //
8953 // Due to current llvm inline asm architecture designed to not "recognize"
8954 // the asm code, there are quite troubles for us to treat mem addressing
8955 // differently for same value/adress used in different instuctions.
8956 // For example, in pic model, call a func may in plt way or direclty
8957 // pc-related, but lea/mov a function adress may use got.
8958 //
8959 // Here we try to "recognize" function call for the case 1 and case 3 in
8960 // inline asm. And try to adjust the constraint for them.
8961 //
8962 // TODO: Due to current inline asm didn't encourage to jmp to the outsider
8963 // label, so here we don't handle jmp function label now, but we need to
8964 // enhance it (especilly in PIC model) if we meet meaningful requirements.
8965 if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
8966 TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
8967 TM.getCodeModel() != CodeModel::Large) {
8968 OpInfo.isIndirect = false;
8969 OpInfo.ConstraintType = TargetLowering::C_Address;
8970 }
8971
8972 // If this is a memory input, and if the operand is not indirect, do what we
8973 // need to provide an address for the memory input.
8974 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8975 !OpInfo.isIndirect) {
8976 assert((OpInfo.isMultipleAlternative ||
8977 (OpInfo.Type == InlineAsm::isInput)) &&
8978 "Can only indirectify direct input operands!");
8979
8980 // Memory operands really want the address of the value.
8981 Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8982
8983 // There is no longer a Value* corresponding to this operand.
8984 OpInfo.CallOperandVal = nullptr;
8985
8986 // It is now an indirect operand.
8987 OpInfo.isIndirect = true;
8988 }
8989
8990 }
8991
8992 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8993 std::vector<SDValue> AsmNodeOperands;
8994 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
8995 AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8996 IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8997
8998 // If we have a !srcloc metadata node associated with it, we want to attach
8999 // this to the ultimately generated inline asm machineinstr. To do this, we
9000 // pass in the third operand as this (potentially null) inline asm MDNode.
9001 const MDNode *SrcLoc = Call.getMetadata("srcloc");
9002 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9003
9004 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9005 // bits as operand 3.
9006 AsmNodeOperands.push_back(DAG.getTargetConstant(
9007 ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9008
9009 // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9010 // this, assign virtual and physical registers for inputs and otput.
9011 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9012 // Assign Registers.
9013 SDISelAsmOperandInfo &RefOpInfo =
9014 OpInfo.isMatchingInputConstraint()
9015 ? ConstraintOperands[OpInfo.getMatchedOperand()]
9016 : OpInfo;
9017 const auto RegError =
9018 getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9019 if (RegError) {
9020 const MachineFunction &MF = DAG.getMachineFunction();
9021 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9022 const char *RegName = TRI.getName(*RegError);
9023 emitInlineAsmError(Call, "register '" + Twine(RegName) +
9024 "' allocated for constraint '" +
9025 Twine(OpInfo.ConstraintCode) +
9026 "' does not match required type");
9027 return;
9028 }
9029
9030 auto DetectWriteToReservedRegister = [&]() {
9031 const MachineFunction &MF = DAG.getMachineFunction();
9032 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9033 for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9034 if (Register::isPhysicalRegister(Reg) &&
9035 TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9036 const char *RegName = TRI.getName(Reg);
9037 emitInlineAsmError(Call, "write to reserved register '" +
9038 Twine(RegName) + "'");
9039 return true;
9040 }
9041 }
9042 return false;
9043 };
9044 assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9045 (OpInfo.Type == InlineAsm::isInput &&
9046 !OpInfo.isMatchingInputConstraint())) &&
9047 "Only address as input operand is allowed.");
9048
9049 switch (OpInfo.Type) {
9050 case InlineAsm::isOutput:
9051 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9052 unsigned ConstraintID =
9053 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9054 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9055 "Failed to convert memory constraint code to constraint id.");
9056
9057 // Add information to the INLINEASM node to know about this output.
9058 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9059 OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
9060 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9061 MVT::i32));
9062 AsmNodeOperands.push_back(OpInfo.CallOperand);
9063 } else {
9064 // Otherwise, this outputs to a register (directly for C_Register /
9065 // C_RegisterClass, and a target-defined fashion for
9066 // C_Immediate/C_Other). Find a register that we can use.
9067 if (OpInfo.AssignedRegs.Regs.empty()) {
9068 emitInlineAsmError(
9069 Call, "couldn't allocate output register for constraint '" +
9070 Twine(OpInfo.ConstraintCode) + "'");
9071 return;
9072 }
9073
9074 if (DetectWriteToReservedRegister())
9075 return;
9076
9077 // Add information to the INLINEASM node to know that this register is
9078 // set.
9079 OpInfo.AssignedRegs.AddInlineAsmOperands(
9080 OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
9081 : InlineAsm::Kind_RegDef,
9082 false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9083 }
9084 break;
9085
9086 case InlineAsm::isInput:
9087 case InlineAsm::isLabel: {
9088 SDValue InOperandVal = OpInfo.CallOperand;
9089
9090 if (OpInfo.isMatchingInputConstraint()) {
9091 // If this is required to match an output register we have already set,
9092 // just use its register.
9093 auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9094 AsmNodeOperands);
9095 unsigned OpFlag =
9096 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9097 if (InlineAsm::isRegDefKind(OpFlag) ||
9098 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
9099 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
9100 if (OpInfo.isIndirect) {
9101 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9102 emitInlineAsmError(Call, "inline asm not supported yet: "
9103 "don't know how to handle tied "
9104 "indirect register inputs");
9105 return;
9106 }
9107
9108 SmallVector<unsigned, 4> Regs;
9109 MachineFunction &MF = DAG.getMachineFunction();
9110 MachineRegisterInfo &MRI = MF.getRegInfo();
9111 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9112 auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9113 Register TiedReg = R->getReg();
9114 MVT RegVT = R->getSimpleValueType(0);
9115 const TargetRegisterClass *RC =
9116 TiedReg.isVirtual() ? MRI.getRegClass(TiedReg)
9117 : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9118 : TRI.getMinimalPhysRegClass(TiedReg);
9119 unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
9120 for (unsigned i = 0; i != NumRegs; ++i)
9121 Regs.push_back(MRI.createVirtualRegister(RC));
9122
9123 RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9124
9125 SDLoc dl = getCurSDLoc();
9126 // Use the produced MatchedRegs object to
9127 MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
9128 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
9129 true, OpInfo.getMatchedOperand(), dl,
9130 DAG, AsmNodeOperands);
9131 break;
9132 }
9133
9134 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9135 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9136 "Unexpected number of operands");
9137 // Add information to the INLINEASM node to know about this input.
9138 // See InlineAsm.h isUseOperandTiedToDef.
9139 OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9140 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9141 OpInfo.getMatchedOperand());
9142 AsmNodeOperands.push_back(DAG.getTargetConstant(
9143 OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9144 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9145 break;
9146 }
9147
9148 // Treat indirect 'X' constraint as memory.
9149 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9150 OpInfo.isIndirect)
9151 OpInfo.ConstraintType = TargetLowering::C_Memory;
9152
9153 if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9154 OpInfo.ConstraintType == TargetLowering::C_Other) {
9155 std::vector<SDValue> Ops;
9156 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9157 Ops, DAG);
9158 if (Ops.empty()) {
9159 if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9160 if (isa<ConstantSDNode>(InOperandVal)) {
9161 emitInlineAsmError(Call, "value out of range for constraint '" +
9162 Twine(OpInfo.ConstraintCode) + "'");
9163 return;
9164 }
9165
9166 emitInlineAsmError(Call,
9167 "invalid operand for inline asm constraint '" +
9168 Twine(OpInfo.ConstraintCode) + "'");
9169 return;
9170 }
9171
9172 // Add information to the INLINEASM node to know about this input.
9173 unsigned ResOpType =
9174 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9175 AsmNodeOperands.push_back(DAG.getTargetConstant(
9176 ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9177 llvm::append_range(AsmNodeOperands, Ops);
9178 break;
9179 }
9180
9181 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9182 assert((OpInfo.isIndirect ||
9183 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9184 "Operand must be indirect to be a mem!");
9185 assert(InOperandVal.getValueType() ==
9186 TLI.getPointerTy(DAG.getDataLayout()) &&
9187 "Memory operands expect pointer values");
9188
9189 unsigned ConstraintID =
9190 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9191 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9192 "Failed to convert memory constraint code to constraint id.");
9193
9194 // Add information to the INLINEASM node to know about this input.
9195 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9196 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9197 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9198 getCurSDLoc(),
9199 MVT::i32));
9200 AsmNodeOperands.push_back(InOperandVal);
9201 break;
9202 }
9203
9204 if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9205 assert(InOperandVal.getValueType() ==
9206 TLI.getPointerTy(DAG.getDataLayout()) &&
9207 "Address operands expect pointer values");
9208
9209 unsigned ConstraintID =
9210 TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9211 assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9212 "Failed to convert memory constraint code to constraint id.");
9213
9214 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9215
9216 SDValue AsmOp = InOperandVal;
9217 if (isFunction(InOperandVal)) {
9218 auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9219 ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1);
9220 AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9221 InOperandVal.getValueType(),
9222 GA->getOffset());
9223 }
9224
9225 // Add information to the INLINEASM node to know about this input.
9226 ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9227
9228 AsmNodeOperands.push_back(
9229 DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9230
9231 AsmNodeOperands.push_back(AsmOp);
9232 break;
9233 }
9234
9235 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9236 OpInfo.ConstraintType == TargetLowering::C_Register) &&
9237 "Unknown constraint type!");
9238
9239 // TODO: Support this.
9240 if (OpInfo.isIndirect) {
9241 emitInlineAsmError(
9242 Call, "Don't know how to handle indirect register inputs yet "
9243 "for constraint '" +
9244 Twine(OpInfo.ConstraintCode) + "'");
9245 return;
9246 }
9247
9248 // Copy the input into the appropriate registers.
9249 if (OpInfo.AssignedRegs.Regs.empty()) {
9250 emitInlineAsmError(Call,
9251 "couldn't allocate input reg for constraint '" +
9252 Twine(OpInfo.ConstraintCode) + "'");
9253 return;
9254 }
9255
9256 if (DetectWriteToReservedRegister())
9257 return;
9258
9259 SDLoc dl = getCurSDLoc();
9260
9261 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
9262 &Call);
9263
9264 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9265 dl, DAG, AsmNodeOperands);
9266 break;
9267 }
9268 case InlineAsm::isClobber:
9269 // Add the clobbered value to the operand list, so that the register
9270 // allocator is aware that the physreg got clobbered.
9271 if (!OpInfo.AssignedRegs.Regs.empty())
9272 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9273 false, 0, getCurSDLoc(), DAG,
9274 AsmNodeOperands);
9275 break;
9276 }
9277 }
9278
9279 // Finish up input operands. Set the input chain and add the flag last.
9280 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9281 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
9282
9283 unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9284 Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9285 DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9286 Flag = Chain.getValue(1);
9287
9288 // Do additional work to generate outputs.
9289
9290 SmallVector<EVT, 1> ResultVTs;
9291 SmallVector<SDValue, 1> ResultValues;
9292 SmallVector<SDValue, 8> OutChains;
9293
9294 llvm::Type *CallResultType = Call.getType();
9295 ArrayRef<Type *> ResultTypes;
9296 if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9297 ResultTypes = StructResult->elements();
9298 else if (!CallResultType->isVoidTy())
9299 ResultTypes = ArrayRef(CallResultType);
9300
9301 auto CurResultType = ResultTypes.begin();
9302 auto handleRegAssign = [&](SDValue V) {
9303 assert(CurResultType != ResultTypes.end() && "Unexpected value");
9304 assert((*CurResultType)->isSized() && "Unexpected unsized type");
9305 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9306 ++CurResultType;
9307 // If the type of the inline asm call site return value is different but has
9308 // same size as the type of the asm output bitcast it. One example of this
9309 // is for vectors with different width / number of elements. This can
9310 // happen for register classes that can contain multiple different value
9311 // types. The preg or vreg allocated may not have the same VT as was
9312 // expected.
9313 //
9314 // This can also happen for a return value that disagrees with the register
9315 // class it is put in, eg. a double in a general-purpose register on a
9316 // 32-bit machine.
9317 if (ResultVT != V.getValueType() &&
9318 ResultVT.getSizeInBits() == V.getValueSizeInBits())
9319 V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9320 else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9321 V.getValueType().isInteger()) {
9322 // If a result value was tied to an input value, the computed result
9323 // may have a wider width than the expected result. Extract the
9324 // relevant portion.
9325 V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9326 }
9327 assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9328 ResultVTs.push_back(ResultVT);
9329 ResultValues.push_back(V);
9330 };
9331
9332 // Deal with output operands.
9333 for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9334 if (OpInfo.Type == InlineAsm::isOutput) {
9335 SDValue Val;
9336 // Skip trivial output operands.
9337 if (OpInfo.AssignedRegs.Regs.empty())
9338 continue;
9339
9340 switch (OpInfo.ConstraintType) {
9341 case TargetLowering::C_Register:
9342 case TargetLowering::C_RegisterClass:
9343 Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9344 Chain, &Flag, &Call);
9345 break;
9346 case TargetLowering::C_Immediate:
9347 case TargetLowering::C_Other:
9348 Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9349 OpInfo, DAG);
9350 break;
9351 case TargetLowering::C_Memory:
9352 break; // Already handled.
9353 case TargetLowering::C_Address:
9354 break; // Silence warning.
9355 case TargetLowering::C_Unknown:
9356 assert(false && "Unexpected unknown constraint");
9357 }
9358
9359 // Indirect output manifest as stores. Record output chains.
9360 if (OpInfo.isIndirect) {
9361 const Value *Ptr = OpInfo.CallOperandVal;
9362 assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9363 SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9364 MachinePointerInfo(Ptr));
9365 OutChains.push_back(Store);
9366 } else {
9367 // generate CopyFromRegs to associated registers.
9368 assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9369 if (Val.getOpcode() == ISD::MERGE_VALUES) {
9370 for (const SDValue &V : Val->op_values())
9371 handleRegAssign(V);
9372 } else
9373 handleRegAssign(Val);
9374 }
9375 }
9376 }
9377
9378 // Set results.
9379 if (!ResultValues.empty()) {
9380 assert(CurResultType == ResultTypes.end() &&
9381 "Mismatch in number of ResultTypes");
9382 assert(ResultValues.size() == ResultTypes.size() &&
9383 "Mismatch in number of output operands in asm result");
9384
9385 SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9386 DAG.getVTList(ResultVTs), ResultValues);
9387 setValue(&Call, V);
9388 }
9389
9390 // Collect store chains.
9391 if (!OutChains.empty())
9392 Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9393
9394 if (EmitEHLabels) {
9395 Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9396 }
9397
9398 // Only Update Root if inline assembly has a memory effect.
9399 if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9400 EmitEHLabels)
9401 DAG.setRoot(Chain);
9402 }
9403
emitInlineAsmError(const CallBase & Call,const Twine & Message)9404 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9405 const Twine &Message) {
9406 LLVMContext &Ctx = *DAG.getContext();
9407 Ctx.emitError(&Call, Message);
9408
9409 // Make sure we leave the DAG in a valid state
9410 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9411 SmallVector<EVT, 1> ValueVTs;
9412 ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9413
9414 if (ValueVTs.empty())
9415 return;
9416
9417 SmallVector<SDValue, 1> Ops;
9418 for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9419 Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9420
9421 setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9422 }
9423
visitVAStart(const CallInst & I)9424 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9425 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9426 MVT::Other, getRoot(),
9427 getValue(I.getArgOperand(0)),
9428 DAG.getSrcValue(I.getArgOperand(0))));
9429 }
9430
visitVAArg(const VAArgInst & I)9431 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9433 const DataLayout &DL = DAG.getDataLayout();
9434 SDValue V = DAG.getVAArg(
9435 TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9436 getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9437 DL.getABITypeAlign(I.getType()).value());
9438 DAG.setRoot(V.getValue(1));
9439
9440 if (I.getType()->isPointerTy())
9441 V = DAG.getPtrExtOrTrunc(
9442 V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9443 setValue(&I, V);
9444 }
9445
visitVAEnd(const CallInst & I)9446 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9447 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9448 MVT::Other, getRoot(),
9449 getValue(I.getArgOperand(0)),
9450 DAG.getSrcValue(I.getArgOperand(0))));
9451 }
9452
visitVACopy(const CallInst & I)9453 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9454 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9455 MVT::Other, getRoot(),
9456 getValue(I.getArgOperand(0)),
9457 getValue(I.getArgOperand(1)),
9458 DAG.getSrcValue(I.getArgOperand(0)),
9459 DAG.getSrcValue(I.getArgOperand(1))));
9460 }
9461
lowerRangeToAssertZExt(SelectionDAG & DAG,const Instruction & I,SDValue Op)9462 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9463 const Instruction &I,
9464 SDValue Op) {
9465 const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9466 if (!Range)
9467 return Op;
9468
9469 ConstantRange CR = getConstantRangeFromMetadata(*Range);
9470 if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9471 return Op;
9472
9473 APInt Lo = CR.getUnsignedMin();
9474 if (!Lo.isMinValue())
9475 return Op;
9476
9477 APInt Hi = CR.getUnsignedMax();
9478 unsigned Bits = std::max(Hi.getActiveBits(),
9479 static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9480
9481 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9482
9483 SDLoc SL = getCurSDLoc();
9484
9485 SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9486 DAG.getValueType(SmallVT));
9487 unsigned NumVals = Op.getNode()->getNumValues();
9488 if (NumVals == 1)
9489 return ZExt;
9490
9491 SmallVector<SDValue, 4> Ops;
9492
9493 Ops.push_back(ZExt);
9494 for (unsigned I = 1; I != NumVals; ++I)
9495 Ops.push_back(Op.getValue(I));
9496
9497 return DAG.getMergeValues(Ops, SL);
9498 }
9499
9500 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9501 /// the call being lowered.
9502 ///
9503 /// This is a helper for lowering intrinsics that follow a target calling
9504 /// convention or require stack pointer adjustment. Only a subset of the
9505 /// intrinsic's operands need to participate in the calling convention.
populateCallLoweringInfo(TargetLowering::CallLoweringInfo & CLI,const CallBase * Call,unsigned ArgIdx,unsigned NumArgs,SDValue Callee,Type * ReturnTy,bool IsPatchPoint)9506 void SelectionDAGBuilder::populateCallLoweringInfo(
9507 TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9508 unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9509 bool IsPatchPoint) {
9510 TargetLowering::ArgListTy Args;
9511 Args.reserve(NumArgs);
9512
9513 // Populate the argument list.
9514 // Attributes for args start at offset 1, after the return attribute.
9515 for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9516 ArgI != ArgE; ++ArgI) {
9517 const Value *V = Call->getOperand(ArgI);
9518
9519 assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9520
9521 TargetLowering::ArgListEntry Entry;
9522 Entry.Node = getValue(V);
9523 Entry.Ty = V->getType();
9524 Entry.setAttributes(Call, ArgI);
9525 Args.push_back(Entry);
9526 }
9527
9528 CLI.setDebugLoc(getCurSDLoc())
9529 .setChain(getRoot())
9530 .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9531 .setDiscardResult(Call->use_empty())
9532 .setIsPatchPoint(IsPatchPoint)
9533 .setIsPreallocated(
9534 Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9535 }
9536
9537 /// Add a stack map intrinsic call's live variable operands to a stackmap
9538 /// or patchpoint target node's operand list.
9539 ///
9540 /// Constants are converted to TargetConstants purely as an optimization to
9541 /// avoid constant materialization and register allocation.
9542 ///
9543 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9544 /// generate addess computation nodes, and so FinalizeISel can convert the
9545 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9546 /// address materialization and register allocation, but may also be required
9547 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9548 /// alloca in the entry block, then the runtime may assume that the alloca's
9549 /// StackMap location can be read immediately after compilation and that the
9550 /// location is valid at any point during execution (this is similar to the
9551 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9552 /// only available in a register, then the runtime would need to trap when
9553 /// execution reaches the StackMap in order to read the alloca's location.
addStackMapLiveVars(const CallBase & Call,unsigned StartIdx,const SDLoc & DL,SmallVectorImpl<SDValue> & Ops,SelectionDAGBuilder & Builder)9554 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9555 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9556 SelectionDAGBuilder &Builder) {
9557 SelectionDAG &DAG = Builder.DAG;
9558 for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9559 SDValue Op = Builder.getValue(Call.getArgOperand(I));
9560
9561 // Things on the stack are pointer-typed, meaning that they are already
9562 // legal and can be emitted directly to target nodes.
9563 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9564 Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9565 } else {
9566 // Otherwise emit a target independent node to be legalised.
9567 Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9568 }
9569 }
9570 }
9571
9572 /// Lower llvm.experimental.stackmap.
visitStackmap(const CallInst & CI)9573 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9574 // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9575 // [live variables...])
9576
9577 assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9578
9579 SDValue Chain, InFlag, Callee;
9580 SmallVector<SDValue, 32> Ops;
9581
9582 SDLoc DL = getCurSDLoc();
9583 Callee = getValue(CI.getCalledOperand());
9584
9585 // The stackmap intrinsic only records the live variables (the arguments
9586 // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9587 // intrinsic, this won't be lowered to a function call. This means we don't
9588 // have to worry about calling conventions and target specific lowering code.
9589 // Instead we perform the call lowering right here.
9590 //
9591 // chain, flag = CALLSEQ_START(chain, 0, 0)
9592 // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9593 // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9594 //
9595 Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9596 InFlag = Chain.getValue(1);
9597
9598 // Add the STACKMAP operands, starting with DAG house-keeping.
9599 Ops.push_back(Chain);
9600 Ops.push_back(InFlag);
9601
9602 // Add the <id>, <numShadowBytes> operands.
9603 //
9604 // These do not require legalisation, and can be emitted directly to target
9605 // constant nodes.
9606 SDValue ID = getValue(CI.getArgOperand(0));
9607 assert(ID.getValueType() == MVT::i64);
9608 SDValue IDConst = DAG.getTargetConstant(
9609 cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9610 Ops.push_back(IDConst);
9611
9612 SDValue Shad = getValue(CI.getArgOperand(1));
9613 assert(Shad.getValueType() == MVT::i32);
9614 SDValue ShadConst = DAG.getTargetConstant(
9615 cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9616 Ops.push_back(ShadConst);
9617
9618 // Add the live variables.
9619 addStackMapLiveVars(CI, 2, DL, Ops, *this);
9620
9621 // Create the STACKMAP node.
9622 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9623 Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9624 InFlag = Chain.getValue(1);
9625
9626 Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL);
9627
9628 // Stackmaps don't generate values, so nothing goes into the NodeMap.
9629
9630 // Set the root to the target-lowered call chain.
9631 DAG.setRoot(Chain);
9632
9633 // Inform the Frame Information that we have a stackmap in this function.
9634 FuncInfo.MF->getFrameInfo().setHasStackMap();
9635 }
9636
9637 /// Lower llvm.experimental.patchpoint directly to its target opcode.
visitPatchpoint(const CallBase & CB,const BasicBlock * EHPadBB)9638 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9639 const BasicBlock *EHPadBB) {
9640 // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9641 // i32 <numBytes>,
9642 // i8* <target>,
9643 // i32 <numArgs>,
9644 // [Args...],
9645 // [live variables...])
9646
9647 CallingConv::ID CC = CB.getCallingConv();
9648 bool IsAnyRegCC = CC == CallingConv::AnyReg;
9649 bool HasDef = !CB.getType()->isVoidTy();
9650 SDLoc dl = getCurSDLoc();
9651 SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9652
9653 // Handle immediate and symbolic callees.
9654 if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9655 Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9656 /*isTarget=*/true);
9657 else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9658 Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9659 SDLoc(SymbolicCallee),
9660 SymbolicCallee->getValueType(0));
9661
9662 // Get the real number of arguments participating in the call <numArgs>
9663 SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9664 unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9665
9666 // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9667 // Intrinsics include all meta-operands up to but not including CC.
9668 unsigned NumMetaOpers = PatchPointOpers::CCPos;
9669 assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9670 "Not enough arguments provided to the patchpoint intrinsic");
9671
9672 // For AnyRegCC the arguments are lowered later on manually.
9673 unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9674 Type *ReturnTy =
9675 IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9676
9677 TargetLowering::CallLoweringInfo CLI(DAG);
9678 populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9679 ReturnTy, true);
9680 std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9681
9682 SDNode *CallEnd = Result.second.getNode();
9683 if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9684 CallEnd = CallEnd->getOperand(0).getNode();
9685
9686 /// Get a call instruction from the call sequence chain.
9687 /// Tail calls are not allowed.
9688 assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9689 "Expected a callseq node.");
9690 SDNode *Call = CallEnd->getOperand(0).getNode();
9691 bool HasGlue = Call->getGluedNode();
9692
9693 // Replace the target specific call node with the patchable intrinsic.
9694 SmallVector<SDValue, 8> Ops;
9695
9696 // Push the chain.
9697 Ops.push_back(*(Call->op_begin()));
9698
9699 // Optionally, push the glue (if any).
9700 if (HasGlue)
9701 Ops.push_back(*(Call->op_end() - 1));
9702
9703 // Push the register mask info.
9704 if (HasGlue)
9705 Ops.push_back(*(Call->op_end() - 2));
9706 else
9707 Ops.push_back(*(Call->op_end() - 1));
9708
9709 // Add the <id> and <numBytes> constants.
9710 SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9711 Ops.push_back(DAG.getTargetConstant(
9712 cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9713 SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9714 Ops.push_back(DAG.getTargetConstant(
9715 cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9716 MVT::i32));
9717
9718 // Add the callee.
9719 Ops.push_back(Callee);
9720
9721 // Adjust <numArgs> to account for any arguments that have been passed on the
9722 // stack instead.
9723 // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9724 unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9725 NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9726 Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9727
9728 // Add the calling convention
9729 Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9730
9731 // Add the arguments we omitted previously. The register allocator should
9732 // place these in any free register.
9733 if (IsAnyRegCC)
9734 for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9735 Ops.push_back(getValue(CB.getArgOperand(i)));
9736
9737 // Push the arguments from the call instruction.
9738 SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9739 Ops.append(Call->op_begin() + 2, e);
9740
9741 // Push live variables for the stack map.
9742 addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9743
9744 SDVTList NodeTys;
9745 if (IsAnyRegCC && HasDef) {
9746 // Create the return types based on the intrinsic definition
9747 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9748 SmallVector<EVT, 3> ValueVTs;
9749 ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9750 assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9751
9752 // There is always a chain and a glue type at the end
9753 ValueVTs.push_back(MVT::Other);
9754 ValueVTs.push_back(MVT::Glue);
9755 NodeTys = DAG.getVTList(ValueVTs);
9756 } else
9757 NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9758
9759 // Replace the target specific call node with a PATCHPOINT node.
9760 SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9761
9762 // Update the NodeMap.
9763 if (HasDef) {
9764 if (IsAnyRegCC)
9765 setValue(&CB, SDValue(PPV.getNode(), 0));
9766 else
9767 setValue(&CB, Result.first);
9768 }
9769
9770 // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9771 // call sequence. Furthermore the location of the chain and glue can change
9772 // when the AnyReg calling convention is used and the intrinsic returns a
9773 // value.
9774 if (IsAnyRegCC && HasDef) {
9775 SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9776 SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9777 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9778 } else
9779 DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9780 DAG.DeleteNode(Call);
9781
9782 // Inform the Frame Information that we have a patchpoint in this function.
9783 FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9784 }
9785
visitVectorReduce(const CallInst & I,unsigned Intrinsic)9786 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9787 unsigned Intrinsic) {
9788 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9789 SDValue Op1 = getValue(I.getArgOperand(0));
9790 SDValue Op2;
9791 if (I.arg_size() > 1)
9792 Op2 = getValue(I.getArgOperand(1));
9793 SDLoc dl = getCurSDLoc();
9794 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9795 SDValue Res;
9796 SDNodeFlags SDFlags;
9797 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9798 SDFlags.copyFMF(*FPMO);
9799
9800 switch (Intrinsic) {
9801 case Intrinsic::vector_reduce_fadd:
9802 if (SDFlags.hasAllowReassociation())
9803 Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9804 DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9805 SDFlags);
9806 else
9807 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9808 break;
9809 case Intrinsic::vector_reduce_fmul:
9810 if (SDFlags.hasAllowReassociation())
9811 Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9812 DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9813 SDFlags);
9814 else
9815 Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9816 break;
9817 case Intrinsic::vector_reduce_add:
9818 Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9819 break;
9820 case Intrinsic::vector_reduce_mul:
9821 Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9822 break;
9823 case Intrinsic::vector_reduce_and:
9824 Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9825 break;
9826 case Intrinsic::vector_reduce_or:
9827 Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9828 break;
9829 case Intrinsic::vector_reduce_xor:
9830 Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9831 break;
9832 case Intrinsic::vector_reduce_smax:
9833 Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9834 break;
9835 case Intrinsic::vector_reduce_smin:
9836 Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9837 break;
9838 case Intrinsic::vector_reduce_umax:
9839 Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9840 break;
9841 case Intrinsic::vector_reduce_umin:
9842 Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9843 break;
9844 case Intrinsic::vector_reduce_fmax:
9845 Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9846 break;
9847 case Intrinsic::vector_reduce_fmin:
9848 Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9849 break;
9850 default:
9851 llvm_unreachable("Unhandled vector reduce intrinsic");
9852 }
9853 setValue(&I, Res);
9854 }
9855
9856 /// Returns an AttributeList representing the attributes applied to the return
9857 /// value of the given call.
getReturnAttrs(TargetLowering::CallLoweringInfo & CLI)9858 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9859 SmallVector<Attribute::AttrKind, 2> Attrs;
9860 if (CLI.RetSExt)
9861 Attrs.push_back(Attribute::SExt);
9862 if (CLI.RetZExt)
9863 Attrs.push_back(Attribute::ZExt);
9864 if (CLI.IsInReg)
9865 Attrs.push_back(Attribute::InReg);
9866
9867 return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9868 Attrs);
9869 }
9870
9871 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9872 /// implementation, which just calls LowerCall.
9873 /// FIXME: When all targets are
9874 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9875 std::pair<SDValue, SDValue>
LowerCallTo(TargetLowering::CallLoweringInfo & CLI) const9876 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9877 // Handle the incoming return values from the call.
9878 CLI.Ins.clear();
9879 Type *OrigRetTy = CLI.RetTy;
9880 SmallVector<EVT, 4> RetTys;
9881 SmallVector<uint64_t, 4> Offsets;
9882 auto &DL = CLI.DAG.getDataLayout();
9883 ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9884
9885 if (CLI.IsPostTypeLegalization) {
9886 // If we are lowering a libcall after legalization, split the return type.
9887 SmallVector<EVT, 4> OldRetTys;
9888 SmallVector<uint64_t, 4> OldOffsets;
9889 RetTys.swap(OldRetTys);
9890 Offsets.swap(OldOffsets);
9891
9892 for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9893 EVT RetVT = OldRetTys[i];
9894 uint64_t Offset = OldOffsets[i];
9895 MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9896 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9897 unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9898 RetTys.append(NumRegs, RegisterVT);
9899 for (unsigned j = 0; j != NumRegs; ++j)
9900 Offsets.push_back(Offset + j * RegisterVTByteSZ);
9901 }
9902 }
9903
9904 SmallVector<ISD::OutputArg, 4> Outs;
9905 GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9906
9907 bool CanLowerReturn =
9908 this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9909 CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9910
9911 SDValue DemoteStackSlot;
9912 int DemoteStackIdx = -100;
9913 if (!CanLowerReturn) {
9914 // FIXME: equivalent assert?
9915 // assert(!CS.hasInAllocaArgument() &&
9916 // "sret demotion is incompatible with inalloca");
9917 uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9918 Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9919 MachineFunction &MF = CLI.DAG.getMachineFunction();
9920 DemoteStackIdx =
9921 MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9922 Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9923 DL.getAllocaAddrSpace());
9924
9925 DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9926 ArgListEntry Entry;
9927 Entry.Node = DemoteStackSlot;
9928 Entry.Ty = StackSlotPtrType;
9929 Entry.IsSExt = false;
9930 Entry.IsZExt = false;
9931 Entry.IsInReg = false;
9932 Entry.IsSRet = true;
9933 Entry.IsNest = false;
9934 Entry.IsByVal = false;
9935 Entry.IsByRef = false;
9936 Entry.IsReturned = false;
9937 Entry.IsSwiftSelf = false;
9938 Entry.IsSwiftAsync = false;
9939 Entry.IsSwiftError = false;
9940 Entry.IsCFGuardTarget = false;
9941 Entry.Alignment = Alignment;
9942 CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9943 CLI.NumFixedArgs += 1;
9944 CLI.getArgs()[0].IndirectType = CLI.RetTy;
9945 CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9946
9947 // sret demotion isn't compatible with tail-calls, since the sret argument
9948 // points into the callers stack frame.
9949 CLI.IsTailCall = false;
9950 } else {
9951 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9952 CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9953 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9954 ISD::ArgFlagsTy Flags;
9955 if (NeedsRegBlock) {
9956 Flags.setInConsecutiveRegs();
9957 if (I == RetTys.size() - 1)
9958 Flags.setInConsecutiveRegsLast();
9959 }
9960 EVT VT = RetTys[I];
9961 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9962 CLI.CallConv, VT);
9963 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9964 CLI.CallConv, VT);
9965 for (unsigned i = 0; i != NumRegs; ++i) {
9966 ISD::InputArg MyFlags;
9967 MyFlags.Flags = Flags;
9968 MyFlags.VT = RegisterVT;
9969 MyFlags.ArgVT = VT;
9970 MyFlags.Used = CLI.IsReturnValueUsed;
9971 if (CLI.RetTy->isPointerTy()) {
9972 MyFlags.Flags.setPointer();
9973 MyFlags.Flags.setPointerAddrSpace(
9974 cast<PointerType>(CLI.RetTy)->getAddressSpace());
9975 }
9976 if (CLI.RetSExt)
9977 MyFlags.Flags.setSExt();
9978 if (CLI.RetZExt)
9979 MyFlags.Flags.setZExt();
9980 if (CLI.IsInReg)
9981 MyFlags.Flags.setInReg();
9982 CLI.Ins.push_back(MyFlags);
9983 }
9984 }
9985 }
9986
9987 // We push in swifterror return as the last element of CLI.Ins.
9988 ArgListTy &Args = CLI.getArgs();
9989 if (supportSwiftError()) {
9990 for (const ArgListEntry &Arg : Args) {
9991 if (Arg.IsSwiftError) {
9992 ISD::InputArg MyFlags;
9993 MyFlags.VT = getPointerTy(DL);
9994 MyFlags.ArgVT = EVT(getPointerTy(DL));
9995 MyFlags.Flags.setSwiftError();
9996 CLI.Ins.push_back(MyFlags);
9997 }
9998 }
9999 }
10000
10001 // Handle all of the outgoing arguments.
10002 CLI.Outs.clear();
10003 CLI.OutVals.clear();
10004 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10005 SmallVector<EVT, 4> ValueVTs;
10006 ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10007 // FIXME: Split arguments if CLI.IsPostTypeLegalization
10008 Type *FinalType = Args[i].Ty;
10009 if (Args[i].IsByVal)
10010 FinalType = Args[i].IndirectType;
10011 bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10012 FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10013 for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10014 ++Value) {
10015 EVT VT = ValueVTs[Value];
10016 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10017 SDValue Op = SDValue(Args[i].Node.getNode(),
10018 Args[i].Node.getResNo() + Value);
10019 ISD::ArgFlagsTy Flags;
10020
10021 // Certain targets (such as MIPS), may have a different ABI alignment
10022 // for a type depending on the context. Give the target a chance to
10023 // specify the alignment it wants.
10024 const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10025 Flags.setOrigAlign(OriginalAlignment);
10026
10027 if (Args[i].Ty->isPointerTy()) {
10028 Flags.setPointer();
10029 Flags.setPointerAddrSpace(
10030 cast<PointerType>(Args[i].Ty)->getAddressSpace());
10031 }
10032 if (Args[i].IsZExt)
10033 Flags.setZExt();
10034 if (Args[i].IsSExt)
10035 Flags.setSExt();
10036 if (Args[i].IsInReg) {
10037 // If we are using vectorcall calling convention, a structure that is
10038 // passed InReg - is surely an HVA
10039 if (CLI.CallConv == CallingConv::X86_VectorCall &&
10040 isa<StructType>(FinalType)) {
10041 // The first value of a structure is marked
10042 if (0 == Value)
10043 Flags.setHvaStart();
10044 Flags.setHva();
10045 }
10046 // Set InReg Flag
10047 Flags.setInReg();
10048 }
10049 if (Args[i].IsSRet)
10050 Flags.setSRet();
10051 if (Args[i].IsSwiftSelf)
10052 Flags.setSwiftSelf();
10053 if (Args[i].IsSwiftAsync)
10054 Flags.setSwiftAsync();
10055 if (Args[i].IsSwiftError)
10056 Flags.setSwiftError();
10057 if (Args[i].IsCFGuardTarget)
10058 Flags.setCFGuardTarget();
10059 if (Args[i].IsByVal)
10060 Flags.setByVal();
10061 if (Args[i].IsByRef)
10062 Flags.setByRef();
10063 if (Args[i].IsPreallocated) {
10064 Flags.setPreallocated();
10065 // Set the byval flag for CCAssignFn callbacks that don't know about
10066 // preallocated. This way we can know how many bytes we should've
10067 // allocated and how many bytes a callee cleanup function will pop. If
10068 // we port preallocated to more targets, we'll have to add custom
10069 // preallocated handling in the various CC lowering callbacks.
10070 Flags.setByVal();
10071 }
10072 if (Args[i].IsInAlloca) {
10073 Flags.setInAlloca();
10074 // Set the byval flag for CCAssignFn callbacks that don't know about
10075 // inalloca. This way we can know how many bytes we should've allocated
10076 // and how many bytes a callee cleanup function will pop. If we port
10077 // inalloca to more targets, we'll have to add custom inalloca handling
10078 // in the various CC lowering callbacks.
10079 Flags.setByVal();
10080 }
10081 Align MemAlign;
10082 if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10083 unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10084 Flags.setByValSize(FrameSize);
10085
10086 // info is not there but there are cases it cannot get right.
10087 if (auto MA = Args[i].Alignment)
10088 MemAlign = *MA;
10089 else
10090 MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10091 } else if (auto MA = Args[i].Alignment) {
10092 MemAlign = *MA;
10093 } else {
10094 MemAlign = OriginalAlignment;
10095 }
10096 Flags.setMemAlign(MemAlign);
10097 if (Args[i].IsNest)
10098 Flags.setNest();
10099 if (NeedsRegBlock)
10100 Flags.setInConsecutiveRegs();
10101
10102 MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10103 CLI.CallConv, VT);
10104 unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10105 CLI.CallConv, VT);
10106 SmallVector<SDValue, 4> Parts(NumParts);
10107 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10108
10109 if (Args[i].IsSExt)
10110 ExtendKind = ISD::SIGN_EXTEND;
10111 else if (Args[i].IsZExt)
10112 ExtendKind = ISD::ZERO_EXTEND;
10113
10114 // Conservatively only handle 'returned' on non-vectors that can be lowered,
10115 // for now.
10116 if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10117 CanLowerReturn) {
10118 assert((CLI.RetTy == Args[i].Ty ||
10119 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10120 CLI.RetTy->getPointerAddressSpace() ==
10121 Args[i].Ty->getPointerAddressSpace())) &&
10122 RetTys.size() == NumValues && "unexpected use of 'returned'");
10123 // Before passing 'returned' to the target lowering code, ensure that
10124 // either the register MVT and the actual EVT are the same size or that
10125 // the return value and argument are extended in the same way; in these
10126 // cases it's safe to pass the argument register value unchanged as the
10127 // return register value (although it's at the target's option whether
10128 // to do so)
10129 // TODO: allow code generation to take advantage of partially preserved
10130 // registers rather than clobbering the entire register when the
10131 // parameter extension method is not compatible with the return
10132 // extension method
10133 if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10134 (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10135 CLI.RetZExt == Args[i].IsZExt))
10136 Flags.setReturned();
10137 }
10138
10139 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10140 CLI.CallConv, ExtendKind);
10141
10142 for (unsigned j = 0; j != NumParts; ++j) {
10143 // if it isn't first piece, alignment must be 1
10144 // For scalable vectors the scalable part is currently handled
10145 // by individual targets, so we just use the known minimum size here.
10146 ISD::OutputArg MyFlags(
10147 Flags, Parts[j].getValueType().getSimpleVT(), VT,
10148 i < CLI.NumFixedArgs, i,
10149 j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10150 if (NumParts > 1 && j == 0)
10151 MyFlags.Flags.setSplit();
10152 else if (j != 0) {
10153 MyFlags.Flags.setOrigAlign(Align(1));
10154 if (j == NumParts - 1)
10155 MyFlags.Flags.setSplitEnd();
10156 }
10157
10158 CLI.Outs.push_back(MyFlags);
10159 CLI.OutVals.push_back(Parts[j]);
10160 }
10161
10162 if (NeedsRegBlock && Value == NumValues - 1)
10163 CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10164 }
10165 }
10166
10167 SmallVector<SDValue, 4> InVals;
10168 CLI.Chain = LowerCall(CLI, InVals);
10169
10170 // Update CLI.InVals to use outside of this function.
10171 CLI.InVals = InVals;
10172
10173 // Verify that the target's LowerCall behaved as expected.
10174 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10175 "LowerCall didn't return a valid chain!");
10176 assert((!CLI.IsTailCall || InVals.empty()) &&
10177 "LowerCall emitted a return value for a tail call!");
10178 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10179 "LowerCall didn't emit the correct number of values!");
10180
10181 // For a tail call, the return value is merely live-out and there aren't
10182 // any nodes in the DAG representing it. Return a special value to
10183 // indicate that a tail call has been emitted and no more Instructions
10184 // should be processed in the current block.
10185 if (CLI.IsTailCall) {
10186 CLI.DAG.setRoot(CLI.Chain);
10187 return std::make_pair(SDValue(), SDValue());
10188 }
10189
10190 #ifndef NDEBUG
10191 for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10192 assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10193 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10194 "LowerCall emitted a value with the wrong type!");
10195 }
10196 #endif
10197
10198 SmallVector<SDValue, 4> ReturnValues;
10199 if (!CanLowerReturn) {
10200 // The instruction result is the result of loading from the
10201 // hidden sret parameter.
10202 SmallVector<EVT, 1> PVTs;
10203 Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10204
10205 ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10206 assert(PVTs.size() == 1 && "Pointers should fit in one register");
10207 EVT PtrVT = PVTs[0];
10208
10209 unsigned NumValues = RetTys.size();
10210 ReturnValues.resize(NumValues);
10211 SmallVector<SDValue, 4> Chains(NumValues);
10212
10213 // An aggregate return value cannot wrap around the address space, so
10214 // offsets to its parts don't wrap either.
10215 SDNodeFlags Flags;
10216 Flags.setNoUnsignedWrap(true);
10217
10218 MachineFunction &MF = CLI.DAG.getMachineFunction();
10219 Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10220 for (unsigned i = 0; i < NumValues; ++i) {
10221 SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10222 CLI.DAG.getConstant(Offsets[i], CLI.DL,
10223 PtrVT), Flags);
10224 SDValue L = CLI.DAG.getLoad(
10225 RetTys[i], CLI.DL, CLI.Chain, Add,
10226 MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10227 DemoteStackIdx, Offsets[i]),
10228 HiddenSRetAlign);
10229 ReturnValues[i] = L;
10230 Chains[i] = L.getValue(1);
10231 }
10232
10233 CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10234 } else {
10235 // Collect the legal value parts into potentially illegal values
10236 // that correspond to the original function's return values.
10237 std::optional<ISD::NodeType> AssertOp;
10238 if (CLI.RetSExt)
10239 AssertOp = ISD::AssertSext;
10240 else if (CLI.RetZExt)
10241 AssertOp = ISD::AssertZext;
10242 unsigned CurReg = 0;
10243 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10244 EVT VT = RetTys[I];
10245 MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10246 CLI.CallConv, VT);
10247 unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10248 CLI.CallConv, VT);
10249
10250 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10251 NumRegs, RegisterVT, VT, nullptr,
10252 CLI.CallConv, AssertOp));
10253 CurReg += NumRegs;
10254 }
10255
10256 // For a function returning void, there is no return value. We can't create
10257 // such a node, so we just return a null return value in that case. In
10258 // that case, nothing will actually look at the value.
10259 if (ReturnValues.empty())
10260 return std::make_pair(SDValue(), CLI.Chain);
10261 }
10262
10263 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10264 CLI.DAG.getVTList(RetTys), ReturnValues);
10265 return std::make_pair(Res, CLI.Chain);
10266 }
10267
10268 /// Places new result values for the node in Results (their number
10269 /// and types must exactly match those of the original return values of
10270 /// the node), or leaves Results empty, which indicates that the node is not
10271 /// to be custom lowered after all.
LowerOperationWrapper(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const10272 void TargetLowering::LowerOperationWrapper(SDNode *N,
10273 SmallVectorImpl<SDValue> &Results,
10274 SelectionDAG &DAG) const {
10275 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10276
10277 if (!Res.getNode())
10278 return;
10279
10280 // If the original node has one result, take the return value from
10281 // LowerOperation as is. It might not be result number 0.
10282 if (N->getNumValues() == 1) {
10283 Results.push_back(Res);
10284 return;
10285 }
10286
10287 // If the original node has multiple results, then the return node should
10288 // have the same number of results.
10289 assert((N->getNumValues() == Res->getNumValues()) &&
10290 "Lowering returned the wrong number of results!");
10291
10292 // Places new result values base on N result number.
10293 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10294 Results.push_back(Res.getValue(I));
10295 }
10296
LowerOperation(SDValue Op,SelectionDAG & DAG) const10297 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10298 llvm_unreachable("LowerOperation not implemented for this target!");
10299 }
10300
CopyValueToVirtualRegister(const Value * V,unsigned Reg,ISD::NodeType ExtendType)10301 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10302 unsigned Reg,
10303 ISD::NodeType ExtendType) {
10304 SDValue Op = getNonRegisterValue(V);
10305 assert((Op.getOpcode() != ISD::CopyFromReg ||
10306 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10307 "Copy from a reg to the same reg!");
10308 assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10309
10310 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10311 // If this is an InlineAsm we have to match the registers required, not the
10312 // notional registers required by the type.
10313
10314 RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10315 std::nullopt); // This is not an ABI copy.
10316 SDValue Chain = DAG.getEntryNode();
10317
10318 if (ExtendType == ISD::ANY_EXTEND) {
10319 auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10320 if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10321 ExtendType = PreferredExtendIt->second;
10322 }
10323 RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10324 PendingExports.push_back(Chain);
10325 }
10326
10327 #include "llvm/CodeGen/SelectionDAGISel.h"
10328
10329 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10330 /// entry block, return true. This includes arguments used by switches, since
10331 /// the switch may expand into multiple basic blocks.
isOnlyUsedInEntryBlock(const Argument * A,bool FastISel)10332 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10333 // With FastISel active, we may be splitting blocks, so force creation
10334 // of virtual registers for all non-dead arguments.
10335 if (FastISel)
10336 return A->use_empty();
10337
10338 const BasicBlock &Entry = A->getParent()->front();
10339 for (const User *U : A->users())
10340 if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10341 return false; // Use not in entry block.
10342
10343 return true;
10344 }
10345
10346 using ArgCopyElisionMapTy =
10347 DenseMap<const Argument *,
10348 std::pair<const AllocaInst *, const StoreInst *>>;
10349
10350 /// Scan the entry block of the function in FuncInfo for arguments that look
10351 /// like copies into a local alloca. Record any copied arguments in
10352 /// ArgCopyElisionCandidates.
10353 static void
findArgumentCopyElisionCandidates(const DataLayout & DL,FunctionLoweringInfo * FuncInfo,ArgCopyElisionMapTy & ArgCopyElisionCandidates)10354 findArgumentCopyElisionCandidates(const DataLayout &DL,
10355 FunctionLoweringInfo *FuncInfo,
10356 ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10357 // Record the state of every static alloca used in the entry block. Argument
10358 // allocas are all used in the entry block, so we need approximately as many
10359 // entries as we have arguments.
10360 enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10361 SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10362 unsigned NumArgs = FuncInfo->Fn->arg_size();
10363 StaticAllocas.reserve(NumArgs * 2);
10364
10365 auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10366 if (!V)
10367 return nullptr;
10368 V = V->stripPointerCasts();
10369 const auto *AI = dyn_cast<AllocaInst>(V);
10370 if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10371 return nullptr;
10372 auto Iter = StaticAllocas.insert({AI, Unknown});
10373 return &Iter.first->second;
10374 };
10375
10376 // Look for stores of arguments to static allocas. Look through bitcasts and
10377 // GEPs to handle type coercions, as long as the alloca is fully initialized
10378 // by the store. Any non-store use of an alloca escapes it and any subsequent
10379 // unanalyzed store might write it.
10380 // FIXME: Handle structs initialized with multiple stores.
10381 for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10382 // Look for stores, and handle non-store uses conservatively.
10383 const auto *SI = dyn_cast<StoreInst>(&I);
10384 if (!SI) {
10385 // We will look through cast uses, so ignore them completely.
10386 if (I.isCast())
10387 continue;
10388 // Ignore debug info and pseudo op intrinsics, they don't escape or store
10389 // to allocas.
10390 if (I.isDebugOrPseudoInst())
10391 continue;
10392 // This is an unknown instruction. Assume it escapes or writes to all
10393 // static alloca operands.
10394 for (const Use &U : I.operands()) {
10395 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10396 *Info = StaticAllocaInfo::Clobbered;
10397 }
10398 continue;
10399 }
10400
10401 // If the stored value is a static alloca, mark it as escaped.
10402 if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10403 *Info = StaticAllocaInfo::Clobbered;
10404
10405 // Check if the destination is a static alloca.
10406 const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10407 StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10408 if (!Info)
10409 continue;
10410 const AllocaInst *AI = cast<AllocaInst>(Dst);
10411
10412 // Skip allocas that have been initialized or clobbered.
10413 if (*Info != StaticAllocaInfo::Unknown)
10414 continue;
10415
10416 // Check if the stored value is an argument, and that this store fully
10417 // initializes the alloca.
10418 // If the argument type has padding bits we can't directly forward a pointer
10419 // as the upper bits may contain garbage.
10420 // Don't elide copies from the same argument twice.
10421 const Value *Val = SI->getValueOperand()->stripPointerCasts();
10422 const auto *Arg = dyn_cast<Argument>(Val);
10423 if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10424 Arg->getType()->isEmptyTy() ||
10425 DL.getTypeStoreSize(Arg->getType()) !=
10426 DL.getTypeAllocSize(AI->getAllocatedType()) ||
10427 !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10428 ArgCopyElisionCandidates.count(Arg)) {
10429 *Info = StaticAllocaInfo::Clobbered;
10430 continue;
10431 }
10432
10433 LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10434 << '\n');
10435
10436 // Mark this alloca and store for argument copy elision.
10437 *Info = StaticAllocaInfo::Elidable;
10438 ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10439
10440 // Stop scanning if we've seen all arguments. This will happen early in -O0
10441 // builds, which is useful, because -O0 builds have large entry blocks and
10442 // many allocas.
10443 if (ArgCopyElisionCandidates.size() == NumArgs)
10444 break;
10445 }
10446 }
10447
10448 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10449 /// ArgVal is a load from a suitable fixed stack object.
tryToElideArgumentCopy(FunctionLoweringInfo & FuncInfo,SmallVectorImpl<SDValue> & Chains,DenseMap<int,int> & ArgCopyElisionFrameIndexMap,SmallPtrSetImpl<const Instruction * > & ElidedArgCopyInstrs,ArgCopyElisionMapTy & ArgCopyElisionCandidates,const Argument & Arg,SDValue ArgVal,bool & ArgHasUses)10450 static void tryToElideArgumentCopy(
10451 FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10452 DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10453 SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10454 ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10455 SDValue ArgVal, bool &ArgHasUses) {
10456 // Check if this is a load from a fixed stack object.
10457 auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10458 if (!LNode)
10459 return;
10460 auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10461 if (!FINode)
10462 return;
10463
10464 // Check that the fixed stack object is the right size and alignment.
10465 // Look at the alignment that the user wrote on the alloca instead of looking
10466 // at the stack object.
10467 auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10468 assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10469 const AllocaInst *AI = ArgCopyIter->second.first;
10470 int FixedIndex = FINode->getIndex();
10471 int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10472 int OldIndex = AllocaIndex;
10473 MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10474 if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10475 LLVM_DEBUG(
10476 dbgs() << " argument copy elision failed due to bad fixed stack "
10477 "object size\n");
10478 return;
10479 }
10480 Align RequiredAlignment = AI->getAlign();
10481 if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10482 LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
10483 "greater than stack argument alignment ("
10484 << DebugStr(RequiredAlignment) << " vs "
10485 << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10486 return;
10487 }
10488
10489 // Perform the elision. Delete the old stack object and replace its only use
10490 // in the variable info map. Mark the stack object as mutable.
10491 LLVM_DEBUG({
10492 dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10493 << " Replacing frame index " << OldIndex << " with " << FixedIndex
10494 << '\n';
10495 });
10496 MFI.RemoveStackObject(OldIndex);
10497 MFI.setIsImmutableObjectIndex(FixedIndex, false);
10498 AllocaIndex = FixedIndex;
10499 ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10500 Chains.push_back(ArgVal.getValue(1));
10501
10502 // Avoid emitting code for the store implementing the copy.
10503 const StoreInst *SI = ArgCopyIter->second.second;
10504 ElidedArgCopyInstrs.insert(SI);
10505
10506 // Check for uses of the argument again so that we can avoid exporting ArgVal
10507 // if it is't used by anything other than the store.
10508 for (const Value *U : Arg.users()) {
10509 if (U != SI) {
10510 ArgHasUses = true;
10511 break;
10512 }
10513 }
10514 }
10515
LowerArguments(const Function & F)10516 void SelectionDAGISel::LowerArguments(const Function &F) {
10517 SelectionDAG &DAG = SDB->DAG;
10518 SDLoc dl = SDB->getCurSDLoc();
10519 const DataLayout &DL = DAG.getDataLayout();
10520 SmallVector<ISD::InputArg, 16> Ins;
10521
10522 // In Naked functions we aren't going to save any registers.
10523 if (F.hasFnAttribute(Attribute::Naked))
10524 return;
10525
10526 if (!FuncInfo->CanLowerReturn) {
10527 // Put in an sret pointer parameter before all the other parameters.
10528 SmallVector<EVT, 1> ValueVTs;
10529 ComputeValueVTs(*TLI, DAG.getDataLayout(),
10530 F.getReturnType()->getPointerTo(
10531 DAG.getDataLayout().getAllocaAddrSpace()),
10532 ValueVTs);
10533
10534 // NOTE: Assuming that a pointer will never break down to more than one VT
10535 // or one register.
10536 ISD::ArgFlagsTy Flags;
10537 Flags.setSRet();
10538 MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10539 ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10540 ISD::InputArg::NoArgIndex, 0);
10541 Ins.push_back(RetArg);
10542 }
10543
10544 // Look for stores of arguments to static allocas. Mark such arguments with a
10545 // flag to ask the target to give us the memory location of that argument if
10546 // available.
10547 ArgCopyElisionMapTy ArgCopyElisionCandidates;
10548 findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10549 ArgCopyElisionCandidates);
10550
10551 // Set up the incoming argument description vector.
10552 for (const Argument &Arg : F.args()) {
10553 unsigned ArgNo = Arg.getArgNo();
10554 SmallVector<EVT, 4> ValueVTs;
10555 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10556 bool isArgValueUsed = !Arg.use_empty();
10557 unsigned PartBase = 0;
10558 Type *FinalType = Arg.getType();
10559 if (Arg.hasAttribute(Attribute::ByVal))
10560 FinalType = Arg.getParamByValType();
10561 bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10562 FinalType, F.getCallingConv(), F.isVarArg(), DL);
10563 for (unsigned Value = 0, NumValues = ValueVTs.size();
10564 Value != NumValues; ++Value) {
10565 EVT VT = ValueVTs[Value];
10566 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10567 ISD::ArgFlagsTy Flags;
10568
10569
10570 if (Arg.getType()->isPointerTy()) {
10571 Flags.setPointer();
10572 Flags.setPointerAddrSpace(
10573 cast<PointerType>(Arg.getType())->getAddressSpace());
10574 }
10575 if (Arg.hasAttribute(Attribute::ZExt))
10576 Flags.setZExt();
10577 if (Arg.hasAttribute(Attribute::SExt))
10578 Flags.setSExt();
10579 if (Arg.hasAttribute(Attribute::InReg)) {
10580 // If we are using vectorcall calling convention, a structure that is
10581 // passed InReg - is surely an HVA
10582 if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10583 isa<StructType>(Arg.getType())) {
10584 // The first value of a structure is marked
10585 if (0 == Value)
10586 Flags.setHvaStart();
10587 Flags.setHva();
10588 }
10589 // Set InReg Flag
10590 Flags.setInReg();
10591 }
10592 if (Arg.hasAttribute(Attribute::StructRet))
10593 Flags.setSRet();
10594 if (Arg.hasAttribute(Attribute::SwiftSelf))
10595 Flags.setSwiftSelf();
10596 if (Arg.hasAttribute(Attribute::SwiftAsync))
10597 Flags.setSwiftAsync();
10598 if (Arg.hasAttribute(Attribute::SwiftError))
10599 Flags.setSwiftError();
10600 if (Arg.hasAttribute(Attribute::ByVal))
10601 Flags.setByVal();
10602 if (Arg.hasAttribute(Attribute::ByRef))
10603 Flags.setByRef();
10604 if (Arg.hasAttribute(Attribute::InAlloca)) {
10605 Flags.setInAlloca();
10606 // Set the byval flag for CCAssignFn callbacks that don't know about
10607 // inalloca. This way we can know how many bytes we should've allocated
10608 // and how many bytes a callee cleanup function will pop. If we port
10609 // inalloca to more targets, we'll have to add custom inalloca handling
10610 // in the various CC lowering callbacks.
10611 Flags.setByVal();
10612 }
10613 if (Arg.hasAttribute(Attribute::Preallocated)) {
10614 Flags.setPreallocated();
10615 // Set the byval flag for CCAssignFn callbacks that don't know about
10616 // preallocated. This way we can know how many bytes we should've
10617 // allocated and how many bytes a callee cleanup function will pop. If
10618 // we port preallocated to more targets, we'll have to add custom
10619 // preallocated handling in the various CC lowering callbacks.
10620 Flags.setByVal();
10621 }
10622
10623 // Certain targets (such as MIPS), may have a different ABI alignment
10624 // for a type depending on the context. Give the target a chance to
10625 // specify the alignment it wants.
10626 const Align OriginalAlignment(
10627 TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10628 Flags.setOrigAlign(OriginalAlignment);
10629
10630 Align MemAlign;
10631 Type *ArgMemTy = nullptr;
10632 if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10633 Flags.isByRef()) {
10634 if (!ArgMemTy)
10635 ArgMemTy = Arg.getPointeeInMemoryValueType();
10636
10637 uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10638
10639 // For in-memory arguments, size and alignment should be passed from FE.
10640 // BE will guess if this info is not there but there are cases it cannot
10641 // get right.
10642 if (auto ParamAlign = Arg.getParamStackAlign())
10643 MemAlign = *ParamAlign;
10644 else if ((ParamAlign = Arg.getParamAlign()))
10645 MemAlign = *ParamAlign;
10646 else
10647 MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10648 if (Flags.isByRef())
10649 Flags.setByRefSize(MemSize);
10650 else
10651 Flags.setByValSize(MemSize);
10652 } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10653 MemAlign = *ParamAlign;
10654 } else {
10655 MemAlign = OriginalAlignment;
10656 }
10657 Flags.setMemAlign(MemAlign);
10658
10659 if (Arg.hasAttribute(Attribute::Nest))
10660 Flags.setNest();
10661 if (NeedsRegBlock)
10662 Flags.setInConsecutiveRegs();
10663 if (ArgCopyElisionCandidates.count(&Arg))
10664 Flags.setCopyElisionCandidate();
10665 if (Arg.hasAttribute(Attribute::Returned))
10666 Flags.setReturned();
10667
10668 MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10669 *CurDAG->getContext(), F.getCallingConv(), VT);
10670 unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10671 *CurDAG->getContext(), F.getCallingConv(), VT);
10672 for (unsigned i = 0; i != NumRegs; ++i) {
10673 // For scalable vectors, use the minimum size; individual targets
10674 // are responsible for handling scalable vector arguments and
10675 // return values.
10676 ISD::InputArg MyFlags(
10677 Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
10678 PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
10679 if (NumRegs > 1 && i == 0)
10680 MyFlags.Flags.setSplit();
10681 // if it isn't first piece, alignment must be 1
10682 else if (i > 0) {
10683 MyFlags.Flags.setOrigAlign(Align(1));
10684 if (i == NumRegs - 1)
10685 MyFlags.Flags.setSplitEnd();
10686 }
10687 Ins.push_back(MyFlags);
10688 }
10689 if (NeedsRegBlock && Value == NumValues - 1)
10690 Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10691 PartBase += VT.getStoreSize().getKnownMinValue();
10692 }
10693 }
10694
10695 // Call the target to set up the argument values.
10696 SmallVector<SDValue, 8> InVals;
10697 SDValue NewRoot = TLI->LowerFormalArguments(
10698 DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10699
10700 // Verify that the target's LowerFormalArguments behaved as expected.
10701 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10702 "LowerFormalArguments didn't return a valid chain!");
10703 assert(InVals.size() == Ins.size() &&
10704 "LowerFormalArguments didn't emit the correct number of values!");
10705 LLVM_DEBUG({
10706 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10707 assert(InVals[i].getNode() &&
10708 "LowerFormalArguments emitted a null value!");
10709 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10710 "LowerFormalArguments emitted a value with the wrong type!");
10711 }
10712 });
10713
10714 // Update the DAG with the new chain value resulting from argument lowering.
10715 DAG.setRoot(NewRoot);
10716
10717 // Set up the argument values.
10718 unsigned i = 0;
10719 if (!FuncInfo->CanLowerReturn) {
10720 // Create a virtual register for the sret pointer, and put in a copy
10721 // from the sret argument into it.
10722 SmallVector<EVT, 1> ValueVTs;
10723 ComputeValueVTs(*TLI, DAG.getDataLayout(),
10724 F.getReturnType()->getPointerTo(
10725 DAG.getDataLayout().getAllocaAddrSpace()),
10726 ValueVTs);
10727 MVT VT = ValueVTs[0].getSimpleVT();
10728 MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10729 std::optional<ISD::NodeType> AssertOp;
10730 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10731 nullptr, F.getCallingConv(), AssertOp);
10732
10733 MachineFunction& MF = SDB->DAG.getMachineFunction();
10734 MachineRegisterInfo& RegInfo = MF.getRegInfo();
10735 Register SRetReg =
10736 RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10737 FuncInfo->DemoteRegister = SRetReg;
10738 NewRoot =
10739 SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10740 DAG.setRoot(NewRoot);
10741
10742 // i indexes lowered arguments. Bump it past the hidden sret argument.
10743 ++i;
10744 }
10745
10746 SmallVector<SDValue, 4> Chains;
10747 DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10748 for (const Argument &Arg : F.args()) {
10749 SmallVector<SDValue, 4> ArgValues;
10750 SmallVector<EVT, 4> ValueVTs;
10751 ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10752 unsigned NumValues = ValueVTs.size();
10753 if (NumValues == 0)
10754 continue;
10755
10756 bool ArgHasUses = !Arg.use_empty();
10757
10758 // Elide the copying store if the target loaded this argument from a
10759 // suitable fixed stack object.
10760 if (Ins[i].Flags.isCopyElisionCandidate()) {
10761 tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10762 ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10763 InVals[i], ArgHasUses);
10764 }
10765
10766 // If this argument is unused then remember its value. It is used to generate
10767 // debugging information.
10768 bool isSwiftErrorArg =
10769 TLI->supportSwiftError() &&
10770 Arg.hasAttribute(Attribute::SwiftError);
10771 if (!ArgHasUses && !isSwiftErrorArg) {
10772 SDB->setUnusedArgValue(&Arg, InVals[i]);
10773
10774 // Also remember any frame index for use in FastISel.
10775 if (FrameIndexSDNode *FI =
10776 dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10777 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10778 }
10779
10780 for (unsigned Val = 0; Val != NumValues; ++Val) {
10781 EVT VT = ValueVTs[Val];
10782 MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10783 F.getCallingConv(), VT);
10784 unsigned NumParts = TLI->getNumRegistersForCallingConv(
10785 *CurDAG->getContext(), F.getCallingConv(), VT);
10786
10787 // Even an apparent 'unused' swifterror argument needs to be returned. So
10788 // we do generate a copy for it that can be used on return from the
10789 // function.
10790 if (ArgHasUses || isSwiftErrorArg) {
10791 std::optional<ISD::NodeType> AssertOp;
10792 if (Arg.hasAttribute(Attribute::SExt))
10793 AssertOp = ISD::AssertSext;
10794 else if (Arg.hasAttribute(Attribute::ZExt))
10795 AssertOp = ISD::AssertZext;
10796
10797 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10798 PartVT, VT, nullptr,
10799 F.getCallingConv(), AssertOp));
10800 }
10801
10802 i += NumParts;
10803 }
10804
10805 // We don't need to do anything else for unused arguments.
10806 if (ArgValues.empty())
10807 continue;
10808
10809 // Note down frame index.
10810 if (FrameIndexSDNode *FI =
10811 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10812 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10813
10814 SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
10815 SDB->getCurSDLoc());
10816
10817 SDB->setValue(&Arg, Res);
10818 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10819 // We want to associate the argument with the frame index, among
10820 // involved operands, that correspond to the lowest address. The
10821 // getCopyFromParts function, called earlier, is swapping the order of
10822 // the operands to BUILD_PAIR depending on endianness. The result of
10823 // that swapping is that the least significant bits of the argument will
10824 // be in the first operand of the BUILD_PAIR node, and the most
10825 // significant bits will be in the second operand.
10826 unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10827 if (LoadSDNode *LNode =
10828 dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10829 if (FrameIndexSDNode *FI =
10830 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10831 FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10832 }
10833
10834 // Analyses past this point are naive and don't expect an assertion.
10835 if (Res.getOpcode() == ISD::AssertZext)
10836 Res = Res.getOperand(0);
10837
10838 // Update the SwiftErrorVRegDefMap.
10839 if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10840 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10841 if (Register::isVirtualRegister(Reg))
10842 SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10843 Reg);
10844 }
10845
10846 // If this argument is live outside of the entry block, insert a copy from
10847 // wherever we got it to the vreg that other BB's will reference it as.
10848 if (Res.getOpcode() == ISD::CopyFromReg) {
10849 // If we can, though, try to skip creating an unnecessary vreg.
10850 // FIXME: This isn't very clean... it would be nice to make this more
10851 // general.
10852 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10853 if (Register::isVirtualRegister(Reg)) {
10854 FuncInfo->ValueMap[&Arg] = Reg;
10855 continue;
10856 }
10857 }
10858 if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10859 FuncInfo->InitializeRegForValue(&Arg);
10860 SDB->CopyToExportRegsIfNeeded(&Arg);
10861 }
10862 }
10863
10864 if (!Chains.empty()) {
10865 Chains.push_back(NewRoot);
10866 NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10867 }
10868
10869 DAG.setRoot(NewRoot);
10870
10871 assert(i == InVals.size() && "Argument register count mismatch!");
10872
10873 // If any argument copy elisions occurred and we have debug info, update the
10874 // stale frame indices used in the dbg.declare variable info table.
10875 MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10876 if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10877 for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10878 auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10879 if (I != ArgCopyElisionFrameIndexMap.end())
10880 VI.Slot = I->second;
10881 }
10882 }
10883
10884 // Finally, if the target has anything special to do, allow it to do so.
10885 emitFunctionEntryCode();
10886 }
10887
10888 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
10889 /// ensure constants are generated when needed. Remember the virtual registers
10890 /// that need to be added to the Machine PHI nodes as input. We cannot just
10891 /// directly add them, because expansion might result in multiple MBB's for one
10892 /// BB. As such, the start of the BB might correspond to a different MBB than
10893 /// the end.
10894 void
HandlePHINodesInSuccessorBlocks(const BasicBlock * LLVMBB)10895 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10897
10898 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10899
10900 // Check PHI nodes in successors that expect a value to be available from this
10901 // block.
10902 for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
10903 if (!isa<PHINode>(SuccBB->begin())) continue;
10904 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10905
10906 // If this terminator has multiple identical successors (common for
10907 // switches), only handle each succ once.
10908 if (!SuccsHandled.insert(SuccMBB).second)
10909 continue;
10910
10911 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10912
10913 // At this point we know that there is a 1-1 correspondence between LLVM PHI
10914 // nodes and Machine PHI nodes, but the incoming operands have not been
10915 // emitted yet.
10916 for (const PHINode &PN : SuccBB->phis()) {
10917 // Ignore dead phi's.
10918 if (PN.use_empty())
10919 continue;
10920
10921 // Skip empty types
10922 if (PN.getType()->isEmptyTy())
10923 continue;
10924
10925 unsigned Reg;
10926 const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10927
10928 if (const auto *C = dyn_cast<Constant>(PHIOp)) {
10929 unsigned &RegOut = ConstantsOut[C];
10930 if (RegOut == 0) {
10931 RegOut = FuncInfo.CreateRegs(C);
10932 // We need to zero/sign extend ConstantInt phi operands to match
10933 // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10934 ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10935 if (auto *CI = dyn_cast<ConstantInt>(C))
10936 ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10937 : ISD::ZERO_EXTEND;
10938 CopyValueToVirtualRegister(C, RegOut, ExtendType);
10939 }
10940 Reg = RegOut;
10941 } else {
10942 DenseMap<const Value *, Register>::iterator I =
10943 FuncInfo.ValueMap.find(PHIOp);
10944 if (I != FuncInfo.ValueMap.end())
10945 Reg = I->second;
10946 else {
10947 assert(isa<AllocaInst>(PHIOp) &&
10948 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10949 "Didn't codegen value into a register!??");
10950 Reg = FuncInfo.CreateRegs(PHIOp);
10951 CopyValueToVirtualRegister(PHIOp, Reg);
10952 }
10953 }
10954
10955 // Remember that this register needs to added to the machine PHI node as
10956 // the input for this MBB.
10957 SmallVector<EVT, 4> ValueVTs;
10958 ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10959 for (EVT VT : ValueVTs) {
10960 const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10961 for (unsigned i = 0; i != NumRegisters; ++i)
10962 FuncInfo.PHINodesToUpdate.push_back(
10963 std::make_pair(&*MBBI++, Reg + i));
10964 Reg += NumRegisters;
10965 }
10966 }
10967 }
10968
10969 ConstantsOut.clear();
10970 }
10971
NextBlock(MachineBasicBlock * MBB)10972 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10973 MachineFunction::iterator I(MBB);
10974 if (++I == FuncInfo.MF->end())
10975 return nullptr;
10976 return &*I;
10977 }
10978
10979 /// During lowering new call nodes can be created (such as memset, etc.).
10980 /// Those will become new roots of the current DAG, but complications arise
10981 /// when they are tail calls. In such cases, the call lowering will update
10982 /// the root, but the builder still needs to know that a tail call has been
10983 /// lowered in order to avoid generating an additional return.
updateDAGForMaybeTailCall(SDValue MaybeTC)10984 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10985 // If the node is null, we do have a tail call.
10986 if (MaybeTC.getNode() != nullptr)
10987 DAG.setRoot(MaybeTC);
10988 else
10989 HasTailCall = true;
10990 }
10991
lowerWorkItem(SwitchWorkListItem W,Value * Cond,MachineBasicBlock * SwitchMBB,MachineBasicBlock * DefaultMBB)10992 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10993 MachineBasicBlock *SwitchMBB,
10994 MachineBasicBlock *DefaultMBB) {
10995 MachineFunction *CurMF = FuncInfo.MF;
10996 MachineBasicBlock *NextMBB = nullptr;
10997 MachineFunction::iterator BBI(W.MBB);
10998 if (++BBI != FuncInfo.MF->end())
10999 NextMBB = &*BBI;
11000
11001 unsigned Size = W.LastCluster - W.FirstCluster + 1;
11002
11003 BranchProbabilityInfo *BPI = FuncInfo.BPI;
11004
11005 if (Size == 2 && W.MBB == SwitchMBB) {
11006 // If any two of the cases has the same destination, and if one value
11007 // is the same as the other, but has one bit unset that the other has set,
11008 // use bit manipulation to do two compares at once. For example:
11009 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11010 // TODO: This could be extended to merge any 2 cases in switches with 3
11011 // cases.
11012 // TODO: Handle cases where W.CaseBB != SwitchBB.
11013 CaseCluster &Small = *W.FirstCluster;
11014 CaseCluster &Big = *W.LastCluster;
11015
11016 if (Small.Low == Small.High && Big.Low == Big.High &&
11017 Small.MBB == Big.MBB) {
11018 const APInt &SmallValue = Small.Low->getValue();
11019 const APInt &BigValue = Big.Low->getValue();
11020
11021 // Check that there is only one bit different.
11022 APInt CommonBit = BigValue ^ SmallValue;
11023 if (CommonBit.isPowerOf2()) {
11024 SDValue CondLHS = getValue(Cond);
11025 EVT VT = CondLHS.getValueType();
11026 SDLoc DL = getCurSDLoc();
11027
11028 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11029 DAG.getConstant(CommonBit, DL, VT));
11030 SDValue Cond = DAG.getSetCC(
11031 DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11032 ISD::SETEQ);
11033
11034 // Update successor info.
11035 // Both Small and Big will jump to Small.BB, so we sum up the
11036 // probabilities.
11037 addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11038 if (BPI)
11039 addSuccessorWithProb(
11040 SwitchMBB, DefaultMBB,
11041 // The default destination is the first successor in IR.
11042 BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11043 else
11044 addSuccessorWithProb(SwitchMBB, DefaultMBB);
11045
11046 // Insert the true branch.
11047 SDValue BrCond =
11048 DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11049 DAG.getBasicBlock(Small.MBB));
11050 // Insert the false branch.
11051 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11052 DAG.getBasicBlock(DefaultMBB));
11053
11054 DAG.setRoot(BrCond);
11055 return;
11056 }
11057 }
11058 }
11059
11060 if (TM.getOptLevel() != CodeGenOpt::None) {
11061 // Here, we order cases by probability so the most likely case will be
11062 // checked first. However, two clusters can have the same probability in
11063 // which case their relative ordering is non-deterministic. So we use Low
11064 // as a tie-breaker as clusters are guaranteed to never overlap.
11065 llvm::sort(W.FirstCluster, W.LastCluster + 1,
11066 [](const CaseCluster &a, const CaseCluster &b) {
11067 return a.Prob != b.Prob ?
11068 a.Prob > b.Prob :
11069 a.Low->getValue().slt(b.Low->getValue());
11070 });
11071
11072 // Rearrange the case blocks so that the last one falls through if possible
11073 // without changing the order of probabilities.
11074 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11075 --I;
11076 if (I->Prob > W.LastCluster->Prob)
11077 break;
11078 if (I->Kind == CC_Range && I->MBB == NextMBB) {
11079 std::swap(*I, *W.LastCluster);
11080 break;
11081 }
11082 }
11083 }
11084
11085 // Compute total probability.
11086 BranchProbability DefaultProb = W.DefaultProb;
11087 BranchProbability UnhandledProbs = DefaultProb;
11088 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11089 UnhandledProbs += I->Prob;
11090
11091 MachineBasicBlock *CurMBB = W.MBB;
11092 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11093 bool FallthroughUnreachable = false;
11094 MachineBasicBlock *Fallthrough;
11095 if (I == W.LastCluster) {
11096 // For the last cluster, fall through to the default destination.
11097 Fallthrough = DefaultMBB;
11098 FallthroughUnreachable = isa<UnreachableInst>(
11099 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11100 } else {
11101 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11102 CurMF->insert(BBI, Fallthrough);
11103 // Put Cond in a virtual register to make it available from the new blocks.
11104 ExportFromCurrentBlock(Cond);
11105 }
11106 UnhandledProbs -= I->Prob;
11107
11108 switch (I->Kind) {
11109 case CC_JumpTable: {
11110 // FIXME: Optimize away range check based on pivot comparisons.
11111 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11112 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11113
11114 // The jump block hasn't been inserted yet; insert it here.
11115 MachineBasicBlock *JumpMBB = JT->MBB;
11116 CurMF->insert(BBI, JumpMBB);
11117
11118 auto JumpProb = I->Prob;
11119 auto FallthroughProb = UnhandledProbs;
11120
11121 // If the default statement is a target of the jump table, we evenly
11122 // distribute the default probability to successors of CurMBB. Also
11123 // update the probability on the edge from JumpMBB to Fallthrough.
11124 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11125 SE = JumpMBB->succ_end();
11126 SI != SE; ++SI) {
11127 if (*SI == DefaultMBB) {
11128 JumpProb += DefaultProb / 2;
11129 FallthroughProb -= DefaultProb / 2;
11130 JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11131 JumpMBB->normalizeSuccProbs();
11132 break;
11133 }
11134 }
11135
11136 if (FallthroughUnreachable)
11137 JTH->FallthroughUnreachable = true;
11138
11139 if (!JTH->FallthroughUnreachable)
11140 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11141 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11142 CurMBB->normalizeSuccProbs();
11143
11144 // The jump table header will be inserted in our current block, do the
11145 // range check, and fall through to our fallthrough block.
11146 JTH->HeaderBB = CurMBB;
11147 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11148
11149 // If we're in the right place, emit the jump table header right now.
11150 if (CurMBB == SwitchMBB) {
11151 visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11152 JTH->Emitted = true;
11153 }
11154 break;
11155 }
11156 case CC_BitTests: {
11157 // FIXME: Optimize away range check based on pivot comparisons.
11158 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11159
11160 // The bit test blocks haven't been inserted yet; insert them here.
11161 for (BitTestCase &BTC : BTB->Cases)
11162 CurMF->insert(BBI, BTC.ThisBB);
11163
11164 // Fill in fields of the BitTestBlock.
11165 BTB->Parent = CurMBB;
11166 BTB->Default = Fallthrough;
11167
11168 BTB->DefaultProb = UnhandledProbs;
11169 // If the cases in bit test don't form a contiguous range, we evenly
11170 // distribute the probability on the edge to Fallthrough to two
11171 // successors of CurMBB.
11172 if (!BTB->ContiguousRange) {
11173 BTB->Prob += DefaultProb / 2;
11174 BTB->DefaultProb -= DefaultProb / 2;
11175 }
11176
11177 if (FallthroughUnreachable)
11178 BTB->FallthroughUnreachable = true;
11179
11180 // If we're in the right place, emit the bit test header right now.
11181 if (CurMBB == SwitchMBB) {
11182 visitBitTestHeader(*BTB, SwitchMBB);
11183 BTB->Emitted = true;
11184 }
11185 break;
11186 }
11187 case CC_Range: {
11188 const Value *RHS, *LHS, *MHS;
11189 ISD::CondCode CC;
11190 if (I->Low == I->High) {
11191 // Check Cond == I->Low.
11192 CC = ISD::SETEQ;
11193 LHS = Cond;
11194 RHS=I->Low;
11195 MHS = nullptr;
11196 } else {
11197 // Check I->Low <= Cond <= I->High.
11198 CC = ISD::SETLE;
11199 LHS = I->Low;
11200 MHS = Cond;
11201 RHS = I->High;
11202 }
11203
11204 // If Fallthrough is unreachable, fold away the comparison.
11205 if (FallthroughUnreachable)
11206 CC = ISD::SETTRUE;
11207
11208 // The false probability is the sum of all unhandled cases.
11209 CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11210 getCurSDLoc(), I->Prob, UnhandledProbs);
11211
11212 if (CurMBB == SwitchMBB)
11213 visitSwitchCase(CB, SwitchMBB);
11214 else
11215 SL->SwitchCases.push_back(CB);
11216
11217 break;
11218 }
11219 }
11220 CurMBB = Fallthrough;
11221 }
11222 }
11223
caseClusterRank(const CaseCluster & CC,CaseClusterIt First,CaseClusterIt Last)11224 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11225 CaseClusterIt First,
11226 CaseClusterIt Last) {
11227 return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11228 if (X.Prob != CC.Prob)
11229 return X.Prob > CC.Prob;
11230
11231 // Ties are broken by comparing the case value.
11232 return X.Low->getValue().slt(CC.Low->getValue());
11233 });
11234 }
11235
splitWorkItem(SwitchWorkList & WorkList,const SwitchWorkListItem & W,Value * Cond,MachineBasicBlock * SwitchMBB)11236 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11237 const SwitchWorkListItem &W,
11238 Value *Cond,
11239 MachineBasicBlock *SwitchMBB) {
11240 assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11241 "Clusters not sorted?");
11242
11243 assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11244
11245 // Balance the tree based on branch probabilities to create a near-optimal (in
11246 // terms of search time given key frequency) binary search tree. See e.g. Kurt
11247 // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11248 CaseClusterIt LastLeft = W.FirstCluster;
11249 CaseClusterIt FirstRight = W.LastCluster;
11250 auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11251 auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11252
11253 // Move LastLeft and FirstRight towards each other from opposite directions to
11254 // find a partitioning of the clusters which balances the probability on both
11255 // sides. If LeftProb and RightProb are equal, alternate which side is
11256 // taken to ensure 0-probability nodes are distributed evenly.
11257 unsigned I = 0;
11258 while (LastLeft + 1 < FirstRight) {
11259 if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11260 LeftProb += (++LastLeft)->Prob;
11261 else
11262 RightProb += (--FirstRight)->Prob;
11263 I++;
11264 }
11265
11266 while (true) {
11267 // Our binary search tree differs from a typical BST in that ours can have up
11268 // to three values in each leaf. The pivot selection above doesn't take that
11269 // into account, which means the tree might require more nodes and be less
11270 // efficient. We compensate for this here.
11271
11272 unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11273 unsigned NumRight = W.LastCluster - FirstRight + 1;
11274
11275 if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11276 // If one side has less than 3 clusters, and the other has more than 3,
11277 // consider taking a cluster from the other side.
11278
11279 if (NumLeft < NumRight) {
11280 // Consider moving the first cluster on the right to the left side.
11281 CaseCluster &CC = *FirstRight;
11282 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11283 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11284 if (LeftSideRank <= RightSideRank) {
11285 // Moving the cluster to the left does not demote it.
11286 ++LastLeft;
11287 ++FirstRight;
11288 continue;
11289 }
11290 } else {
11291 assert(NumRight < NumLeft);
11292 // Consider moving the last element on the left to the right side.
11293 CaseCluster &CC = *LastLeft;
11294 unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11295 unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11296 if (RightSideRank <= LeftSideRank) {
11297 // Moving the cluster to the right does not demot it.
11298 --LastLeft;
11299 --FirstRight;
11300 continue;
11301 }
11302 }
11303 }
11304 break;
11305 }
11306
11307 assert(LastLeft + 1 == FirstRight);
11308 assert(LastLeft >= W.FirstCluster);
11309 assert(FirstRight <= W.LastCluster);
11310
11311 // Use the first element on the right as pivot since we will make less-than
11312 // comparisons against it.
11313 CaseClusterIt PivotCluster = FirstRight;
11314 assert(PivotCluster > W.FirstCluster);
11315 assert(PivotCluster <= W.LastCluster);
11316
11317 CaseClusterIt FirstLeft = W.FirstCluster;
11318 CaseClusterIt LastRight = W.LastCluster;
11319
11320 const ConstantInt *Pivot = PivotCluster->Low;
11321
11322 // New blocks will be inserted immediately after the current one.
11323 MachineFunction::iterator BBI(W.MBB);
11324 ++BBI;
11325
11326 // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11327 // we can branch to its destination directly if it's squeezed exactly in
11328 // between the known lower bound and Pivot - 1.
11329 MachineBasicBlock *LeftMBB;
11330 if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11331 FirstLeft->Low == W.GE &&
11332 (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11333 LeftMBB = FirstLeft->MBB;
11334 } else {
11335 LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11336 FuncInfo.MF->insert(BBI, LeftMBB);
11337 WorkList.push_back(
11338 {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11339 // Put Cond in a virtual register to make it available from the new blocks.
11340 ExportFromCurrentBlock(Cond);
11341 }
11342
11343 // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11344 // single cluster, RHS.Low == Pivot, and we can branch to its destination
11345 // directly if RHS.High equals the current upper bound.
11346 MachineBasicBlock *RightMBB;
11347 if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11348 W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11349 RightMBB = FirstRight->MBB;
11350 } else {
11351 RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11352 FuncInfo.MF->insert(BBI, RightMBB);
11353 WorkList.push_back(
11354 {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11355 // Put Cond in a virtual register to make it available from the new blocks.
11356 ExportFromCurrentBlock(Cond);
11357 }
11358
11359 // Create the CaseBlock record that will be used to lower the branch.
11360 CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11361 getCurSDLoc(), LeftProb, RightProb);
11362
11363 if (W.MBB == SwitchMBB)
11364 visitSwitchCase(CB, SwitchMBB);
11365 else
11366 SL->SwitchCases.push_back(CB);
11367 }
11368
11369 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11370 // from the swith statement.
scaleCaseProbality(BranchProbability CaseProb,BranchProbability PeeledCaseProb)11371 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11372 BranchProbability PeeledCaseProb) {
11373 if (PeeledCaseProb == BranchProbability::getOne())
11374 return BranchProbability::getZero();
11375 BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11376
11377 uint32_t Numerator = CaseProb.getNumerator();
11378 uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11379 return BranchProbability(Numerator, std::max(Numerator, Denominator));
11380 }
11381
11382 // Try to peel the top probability case if it exceeds the threshold.
11383 // Return current MachineBasicBlock for the switch statement if the peeling
11384 // does not occur.
11385 // If the peeling is performed, return the newly created MachineBasicBlock
11386 // for the peeled switch statement. Also update Clusters to remove the peeled
11387 // case. PeeledCaseProb is the BranchProbability for the peeled case.
peelDominantCaseCluster(const SwitchInst & SI,CaseClusterVector & Clusters,BranchProbability & PeeledCaseProb)11388 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11389 const SwitchInst &SI, CaseClusterVector &Clusters,
11390 BranchProbability &PeeledCaseProb) {
11391 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11392 // Don't perform if there is only one cluster or optimizing for size.
11393 if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11394 TM.getOptLevel() == CodeGenOpt::None ||
11395 SwitchMBB->getParent()->getFunction().hasMinSize())
11396 return SwitchMBB;
11397
11398 BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11399 unsigned PeeledCaseIndex = 0;
11400 bool SwitchPeeled = false;
11401 for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11402 CaseCluster &CC = Clusters[Index];
11403 if (CC.Prob < TopCaseProb)
11404 continue;
11405 TopCaseProb = CC.Prob;
11406 PeeledCaseIndex = Index;
11407 SwitchPeeled = true;
11408 }
11409 if (!SwitchPeeled)
11410 return SwitchMBB;
11411
11412 LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11413 << TopCaseProb << "\n");
11414
11415 // Record the MBB for the peeled switch statement.
11416 MachineFunction::iterator BBI(SwitchMBB);
11417 ++BBI;
11418 MachineBasicBlock *PeeledSwitchMBB =
11419 FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11420 FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11421
11422 ExportFromCurrentBlock(SI.getCondition());
11423 auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11424 SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11425 nullptr, nullptr, TopCaseProb.getCompl()};
11426 lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11427
11428 Clusters.erase(PeeledCaseIt);
11429 for (CaseCluster &CC : Clusters) {
11430 LLVM_DEBUG(
11431 dbgs() << "Scale the probablity for one cluster, before scaling: "
11432 << CC.Prob << "\n");
11433 CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11434 LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11435 }
11436 PeeledCaseProb = TopCaseProb;
11437 return PeeledSwitchMBB;
11438 }
11439
visitSwitch(const SwitchInst & SI)11440 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11441 // Extract cases from the switch.
11442 BranchProbabilityInfo *BPI = FuncInfo.BPI;
11443 CaseClusterVector Clusters;
11444 Clusters.reserve(SI.getNumCases());
11445 for (auto I : SI.cases()) {
11446 MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11447 const ConstantInt *CaseVal = I.getCaseValue();
11448 BranchProbability Prob =
11449 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11450 : BranchProbability(1, SI.getNumCases() + 1);
11451 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11452 }
11453
11454 MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11455
11456 // Cluster adjacent cases with the same destination. We do this at all
11457 // optimization levels because it's cheap to do and will make codegen faster
11458 // if there are many clusters.
11459 sortAndRangeify(Clusters);
11460
11461 // The branch probablity of the peeled case.
11462 BranchProbability PeeledCaseProb = BranchProbability::getZero();
11463 MachineBasicBlock *PeeledSwitchMBB =
11464 peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11465
11466 // If there is only the default destination, jump there directly.
11467 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11468 if (Clusters.empty()) {
11469 assert(PeeledSwitchMBB == SwitchMBB);
11470 SwitchMBB->addSuccessor(DefaultMBB);
11471 if (DefaultMBB != NextBlock(SwitchMBB)) {
11472 DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11473 getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11474 }
11475 return;
11476 }
11477
11478 SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11479 SL->findBitTestClusters(Clusters, &SI);
11480
11481 LLVM_DEBUG({
11482 dbgs() << "Case clusters: ";
11483 for (const CaseCluster &C : Clusters) {
11484 if (C.Kind == CC_JumpTable)
11485 dbgs() << "JT:";
11486 if (C.Kind == CC_BitTests)
11487 dbgs() << "BT:";
11488
11489 C.Low->getValue().print(dbgs(), true);
11490 if (C.Low != C.High) {
11491 dbgs() << '-';
11492 C.High->getValue().print(dbgs(), true);
11493 }
11494 dbgs() << ' ';
11495 }
11496 dbgs() << '\n';
11497 });
11498
11499 assert(!Clusters.empty());
11500 SwitchWorkList WorkList;
11501 CaseClusterIt First = Clusters.begin();
11502 CaseClusterIt Last = Clusters.end() - 1;
11503 auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11504 // Scale the branchprobability for DefaultMBB if the peel occurs and
11505 // DefaultMBB is not replaced.
11506 if (PeeledCaseProb != BranchProbability::getZero() &&
11507 DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11508 DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11509 WorkList.push_back(
11510 {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11511
11512 while (!WorkList.empty()) {
11513 SwitchWorkListItem W = WorkList.pop_back_val();
11514 unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11515
11516 if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11517 !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11518 // For optimized builds, lower large range as a balanced binary tree.
11519 splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11520 continue;
11521 }
11522
11523 lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11524 }
11525 }
11526
visitStepVector(const CallInst & I)11527 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11528 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11529 auto DL = getCurSDLoc();
11530 EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11531 setValue(&I, DAG.getStepVector(DL, ResultVT));
11532 }
11533
visitVectorReverse(const CallInst & I)11534 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11535 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11536 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11537
11538 SDLoc DL = getCurSDLoc();
11539 SDValue V = getValue(I.getOperand(0));
11540 assert(VT == V.getValueType() && "Malformed vector.reverse!");
11541
11542 if (VT.isScalableVector()) {
11543 setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11544 return;
11545 }
11546
11547 // Use VECTOR_SHUFFLE for the fixed-length vector
11548 // to maintain existing behavior.
11549 SmallVector<int, 8> Mask;
11550 unsigned NumElts = VT.getVectorMinNumElements();
11551 for (unsigned i = 0; i != NumElts; ++i)
11552 Mask.push_back(NumElts - 1 - i);
11553
11554 setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11555 }
11556
visitFreeze(const FreezeInst & I)11557 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11558 SmallVector<EVT, 4> ValueVTs;
11559 ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11560 ValueVTs);
11561 unsigned NumValues = ValueVTs.size();
11562 if (NumValues == 0) return;
11563
11564 SmallVector<SDValue, 4> Values(NumValues);
11565 SDValue Op = getValue(I.getOperand(0));
11566
11567 for (unsigned i = 0; i != NumValues; ++i)
11568 Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11569 SDValue(Op.getNode(), Op.getResNo() + i));
11570
11571 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11572 DAG.getVTList(ValueVTs), Values));
11573 }
11574
visitVectorSplice(const CallInst & I)11575 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11576 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11577 EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11578
11579 SDLoc DL = getCurSDLoc();
11580 SDValue V1 = getValue(I.getOperand(0));
11581 SDValue V2 = getValue(I.getOperand(1));
11582 int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11583
11584 // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11585 if (VT.isScalableVector()) {
11586 MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11587 setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11588 DAG.getConstant(Imm, DL, IdxVT)));
11589 return;
11590 }
11591
11592 unsigned NumElts = VT.getVectorNumElements();
11593
11594 uint64_t Idx = (NumElts + Imm) % NumElts;
11595
11596 // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11597 SmallVector<int, 8> Mask;
11598 for (unsigned i = 0; i < NumElts; ++i)
11599 Mask.push_back(Idx + i);
11600 setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11601 }
11602