xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision bc110de78a4bf47f63267eae07ef02f14bcc78e3)
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/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallingConv.h"
73 #include "llvm/IR/Constant.h"
74 #include "llvm/IR/ConstantRange.h"
75 #include "llvm/IR/Constants.h"
76 #include "llvm/IR/DataLayout.h"
77 #include "llvm/IR/DebugInfoMetadata.h"
78 #include "llvm/IR/DebugLoc.h"
79 #include "llvm/IR/DerivedTypes.h"
80 #include "llvm/IR/Function.h"
81 #include "llvm/IR/GetElementPtrTypeIterator.h"
82 #include "llvm/IR/InlineAsm.h"
83 #include "llvm/IR/InstrTypes.h"
84 #include "llvm/IR/Instruction.h"
85 #include "llvm/IR/Instructions.h"
86 #include "llvm/IR/IntrinsicInst.h"
87 #include "llvm/IR/Intrinsics.h"
88 #include "llvm/IR/IntrinsicsAArch64.h"
89 #include "llvm/IR/IntrinsicsWebAssembly.h"
90 #include "llvm/IR/LLVMContext.h"
91 #include "llvm/IR/Metadata.h"
92 #include "llvm/IR/Module.h"
93 #include "llvm/IR/Operator.h"
94 #include "llvm/IR/PatternMatch.h"
95 #include "llvm/IR/Statepoint.h"
96 #include "llvm/IR/Type.h"
97 #include "llvm/IR/User.h"
98 #include "llvm/IR/Value.h"
99 #include "llvm/MC/MCContext.h"
100 #include "llvm/MC/MCSymbol.h"
101 #include "llvm/Support/AtomicOrdering.h"
102 #include "llvm/Support/BranchProbability.h"
103 #include "llvm/Support/Casting.h"
104 #include "llvm/Support/CodeGen.h"
105 #include "llvm/Support/CommandLine.h"
106 #include "llvm/Support/Compiler.h"
107 #include "llvm/Support/Debug.h"
108 #include "llvm/Support/ErrorHandling.h"
109 #include "llvm/Support/MachineValueType.h"
110 #include "llvm/Support/MathExtras.h"
111 #include "llvm/Support/raw_ostream.h"
112 #include "llvm/Target/TargetIntrinsicInfo.h"
113 #include "llvm/Target/TargetMachine.h"
114 #include "llvm/Target/TargetOptions.h"
115 #include "llvm/Transforms/Utils/Local.h"
116 #include <algorithm>
117 #include <cassert>
118 #include <cstddef>
119 #include <cstdint>
120 #include <cstring>
121 #include <iterator>
122 #include <limits>
123 #include <numeric>
124 #include <tuple>
125 #include <utility>
126 #include <vector>
127 
128 using namespace llvm;
129 using namespace PatternMatch;
130 using namespace SwitchCG;
131 
132 #define DEBUG_TYPE "isel"
133 
134 /// LimitFloatPrecision - Generate low-precision inline sequences for
135 /// some float libcalls (6, 8 or 12 bits).
136 static unsigned LimitFloatPrecision;
137 
138 static cl::opt<bool>
139     InsertAssertAlign("insert-assert-align", cl::init(true),
140                       cl::desc("Insert the experimental `assertalign` node."),
141                       cl::ReallyHidden);
142 
143 static cl::opt<unsigned, true>
144     LimitFPPrecision("limit-float-precision",
145                      cl::desc("Generate low-precision inline sequences "
146                               "for some float libcalls"),
147                      cl::location(LimitFloatPrecision), cl::Hidden,
148                      cl::init(0));
149 
150 static cl::opt<unsigned> SwitchPeelThreshold(
151     "switch-peel-threshold", cl::Hidden, cl::init(66),
152     cl::desc("Set the case probability threshold for peeling the case from a "
153              "switch statement. A value greater than 100 will void this "
154              "optimization"));
155 
156 // Limit the width of DAG chains. This is important in general to prevent
157 // DAG-based analysis from blowing up. For example, alias analysis and
158 // load clustering may not complete in reasonable time. It is difficult to
159 // recognize and avoid this situation within each individual analysis, and
160 // future analyses are likely to have the same behavior. Limiting DAG width is
161 // the safe approach and will be especially important with global DAGs.
162 //
163 // MaxParallelChains default is arbitrarily high to avoid affecting
164 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
165 // sequence over this should have been converted to llvm.memcpy by the
166 // frontend. It is easy to induce this behavior with .ll code such as:
167 // %buffer = alloca [4096 x i8]
168 // %data = load [4096 x i8]* %argPtr
169 // store [4096 x i8] %data, [4096 x i8]* %buffer
170 static const unsigned MaxParallelChains = 64;
171 
172 // Return the calling convention if the Value passed requires ABI mangling as it
173 // is a parameter to a function or a return value from a function which is not
174 // an intrinsic.
175 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
176   if (auto *R = dyn_cast<ReturnInst>(V))
177     return R->getParent()->getParent()->getCallingConv();
178 
179   if (auto *CI = dyn_cast<CallInst>(V)) {
180     const bool IsInlineAsm = CI->isInlineAsm();
181     const bool IsIndirectFunctionCall =
182         !IsInlineAsm && !CI->getCalledFunction();
183 
184     // It is possible that the call instruction is an inline asm statement or an
185     // indirect function call in which case the return value of
186     // getCalledFunction() would be nullptr.
187     const bool IsInstrinsicCall =
188         !IsInlineAsm && !IsIndirectFunctionCall &&
189         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
190 
191     if (!IsInlineAsm && !IsInstrinsicCall)
192       return CI->getCallingConv();
193   }
194 
195   return None;
196 }
197 
198 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
199                                       const SDValue *Parts, unsigned NumParts,
200                                       MVT PartVT, EVT ValueVT, const Value *V,
201                                       Optional<CallingConv::ID> CC);
202 
203 /// getCopyFromParts - Create a value that contains the specified legal parts
204 /// combined into the value they represent.  If the parts combine to a type
205 /// larger than ValueVT then AssertOp can be used to specify whether the extra
206 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
207 /// (ISD::AssertSext).
208 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
209                                 const SDValue *Parts, unsigned NumParts,
210                                 MVT PartVT, EVT ValueVT, const Value *V,
211                                 Optional<CallingConv::ID> CC = None,
212                                 Optional<ISD::NodeType> AssertOp = None) {
213   // Let the target assemble the parts if it wants to
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
216                                                    PartVT, ValueVT, CC))
217     return Val;
218 
219   if (ValueVT.isVector())
220     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
221                                   CC);
222 
223   assert(NumParts > 0 && "No parts to assemble!");
224   SDValue Val = Parts[0];
225 
226   if (NumParts > 1) {
227     // Assemble the value from multiple parts.
228     if (ValueVT.isInteger()) {
229       unsigned PartBits = PartVT.getSizeInBits();
230       unsigned ValueBits = ValueVT.getSizeInBits();
231 
232       // Assemble the power of 2 part.
233       unsigned RoundParts =
234           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
235       unsigned RoundBits = PartBits * RoundParts;
236       EVT RoundVT = RoundBits == ValueBits ?
237         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
238       SDValue Lo, Hi;
239 
240       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
241 
242       if (RoundParts > 2) {
243         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
244                               PartVT, HalfVT, V);
245         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
246                               RoundParts / 2, PartVT, HalfVT, V);
247       } else {
248         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
249         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
250       }
251 
252       if (DAG.getDataLayout().isBigEndian())
253         std::swap(Lo, Hi);
254 
255       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
256 
257       if (RoundParts < NumParts) {
258         // Assemble the trailing non-power-of-2 part.
259         unsigned OddParts = NumParts - RoundParts;
260         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
261         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
262                               OddVT, V, CC);
263 
264         // Combine the round and odd parts.
265         Lo = Val;
266         if (DAG.getDataLayout().isBigEndian())
267           std::swap(Lo, Hi);
268         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
269         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
270         Hi =
271             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
272                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
273                                         TLI.getPointerTy(DAG.getDataLayout())));
274         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
275         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
276       }
277     } else if (PartVT.isFloatingPoint()) {
278       // FP split into multiple FP parts (for ppcf128)
279       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
280              "Unexpected split");
281       SDValue Lo, Hi;
282       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
283       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
284       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
285         std::swap(Lo, Hi);
286       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
287     } else {
288       // FP split into integer parts (soft fp)
289       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
290              !PartVT.isVector() && "Unexpected split");
291       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
292       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
293     }
294   }
295 
296   // There is now one part, held in Val.  Correct it to match ValueVT.
297   // PartEVT is the type of the register class that holds the value.
298   // ValueVT is the type of the inline asm operation.
299   EVT PartEVT = Val.getValueType();
300 
301   if (PartEVT == ValueVT)
302     return Val;
303 
304   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
305       ValueVT.bitsLT(PartEVT)) {
306     // For an FP value in an integer part, we need to truncate to the right
307     // width first.
308     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
309     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
310   }
311 
312   // Handle types that have the same size.
313   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
314     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
315 
316   // Handle types with different sizes.
317   if (PartEVT.isInteger() && ValueVT.isInteger()) {
318     if (ValueVT.bitsLT(PartEVT)) {
319       // For a truncate, see if we have any information to
320       // indicate whether the truncated bits will always be
321       // zero or sign-extension.
322       if (AssertOp.hasValue())
323         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
324                           DAG.getValueType(ValueVT));
325       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
326     }
327     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
328   }
329 
330   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
331     // FP_ROUND's are always exact here.
332     if (ValueVT.bitsLT(Val.getValueType()))
333       return DAG.getNode(
334           ISD::FP_ROUND, DL, ValueVT, Val,
335           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
336 
337     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
338   }
339 
340   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
341   // then truncating.
342   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
343       ValueVT.bitsLT(PartEVT)) {
344     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
345     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
346   }
347 
348   report_fatal_error("Unknown mismatch in getCopyFromParts!");
349 }
350 
351 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
352                                               const Twine &ErrMsg) {
353   const Instruction *I = dyn_cast_or_null<Instruction>(V);
354   if (!V)
355     return Ctx.emitError(ErrMsg);
356 
357   const char *AsmError = ", possible invalid constraint for vector type";
358   if (const CallInst *CI = dyn_cast<CallInst>(I))
359     if (CI->isInlineAsm())
360       return Ctx.emitError(I, ErrMsg + AsmError);
361 
362   return Ctx.emitError(I, ErrMsg);
363 }
364 
365 /// getCopyFromPartsVector - Create a value that contains the specified legal
366 /// parts combined into the value they represent.  If the parts combine to a
367 /// type larger than ValueVT then AssertOp can be used to specify whether the
368 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
369 /// ValueVT (ISD::AssertSext).
370 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
371                                       const SDValue *Parts, unsigned NumParts,
372                                       MVT PartVT, EVT ValueVT, const Value *V,
373                                       Optional<CallingConv::ID> CallConv) {
374   assert(ValueVT.isVector() && "Not a vector value");
375   assert(NumParts > 0 && "No parts to assemble!");
376   const bool IsABIRegCopy = CallConv.hasValue();
377 
378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
379   SDValue Val = Parts[0];
380 
381   // Handle a multi-element vector.
382   if (NumParts > 1) {
383     EVT IntermediateVT;
384     MVT RegisterVT;
385     unsigned NumIntermediates;
386     unsigned NumRegs;
387 
388     if (IsABIRegCopy) {
389       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
390           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
391           NumIntermediates, RegisterVT);
392     } else {
393       NumRegs =
394           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
395                                      NumIntermediates, RegisterVT);
396     }
397 
398     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
399     NumParts = NumRegs; // Silence a compiler warning.
400     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
401     assert(RegisterVT.getSizeInBits() ==
402            Parts[0].getSimpleValueType().getSizeInBits() &&
403            "Part type sizes don't match!");
404 
405     // Assemble the parts into intermediate operands.
406     SmallVector<SDValue, 8> Ops(NumIntermediates);
407     if (NumIntermediates == NumParts) {
408       // If the register was not expanded, truncate or copy the value,
409       // as appropriate.
410       for (unsigned i = 0; i != NumParts; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
412                                   PartVT, IntermediateVT, V);
413     } else if (NumParts > 0) {
414       // If the intermediate type was expanded, build the intermediate
415       // operands from the parts.
416       assert(NumParts % NumIntermediates == 0 &&
417              "Must expand into a divisible number of parts!");
418       unsigned Factor = NumParts / NumIntermediates;
419       for (unsigned i = 0; i != NumIntermediates; ++i)
420         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
421                                   PartVT, IntermediateVT, V);
422     }
423 
424     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
425     // intermediate operands.
426     EVT BuiltVectorTy =
427         IntermediateVT.isVector()
428             ? EVT::getVectorVT(
429                   *DAG.getContext(), IntermediateVT.getScalarType(),
430                   IntermediateVT.getVectorElementCount() * NumParts)
431             : EVT::getVectorVT(*DAG.getContext(),
432                                IntermediateVT.getScalarType(),
433                                NumIntermediates);
434     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
435                                                 : ISD::BUILD_VECTOR,
436                       DL, BuiltVectorTy, Ops);
437   }
438 
439   // There is now one part, held in Val.  Correct it to match ValueVT.
440   EVT PartEVT = Val.getValueType();
441 
442   if (PartEVT == ValueVT)
443     return Val;
444 
445   if (PartEVT.isVector()) {
446     // If the element type of the source/dest vectors are the same, but the
447     // parts vector has more elements than the value vector, then we have a
448     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
449     // elements we want.
450     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
451       assert((PartEVT.getVectorElementCount().Min >
452               ValueVT.getVectorElementCount().Min) &&
453              (PartEVT.getVectorElementCount().Scalable ==
454               ValueVT.getVectorElementCount().Scalable) &&
455              "Cannot narrow, it would be a lossy transformation");
456       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
457                          DAG.getVectorIdxConstant(0, DL));
458     }
459 
460     // Vector/Vector bitcast.
461     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
462       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
463 
464     assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
465       "Cannot handle this kind of promotion");
466     // Promoted vector extract
467     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
468 
469   }
470 
471   // Trivial bitcast if the types are the same size and the destination
472   // vector type is legal.
473   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
474       TLI.isTypeLegal(ValueVT))
475     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
476 
477   if (ValueVT.getVectorNumElements() != 1) {
478      // Certain ABIs require that vectors are passed as integers. For vectors
479      // are the same size, this is an obvious bitcast.
480      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
481        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
482      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
483        // Bitcast Val back the original type and extract the corresponding
484        // vector we want.
485        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
486        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
487                                            ValueVT.getVectorElementType(), Elts);
488        Val = DAG.getBitcast(WiderVecType, Val);
489        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
490                           DAG.getVectorIdxConstant(0, DL));
491      }
492 
493      diagnosePossiblyInvalidConstraint(
494          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
495      return DAG.getUNDEF(ValueVT);
496   }
497 
498   // Handle cases such as i8 -> <1 x i1>
499   EVT ValueSVT = ValueVT.getVectorElementType();
500   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
501     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
502       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
503     else
504       Val = ValueVT.isFloatingPoint()
505                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
506                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
507   }
508 
509   return DAG.getBuildVector(ValueVT, DL, Val);
510 }
511 
512 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
513                                  SDValue Val, SDValue *Parts, unsigned NumParts,
514                                  MVT PartVT, const Value *V,
515                                  Optional<CallingConv::ID> CallConv);
516 
517 /// getCopyToParts - Create a series of nodes that contain the specified value
518 /// split into legal parts.  If the parts contain more bits than Val, then, for
519 /// integers, ExtendKind can be used to specify how to generate the extra bits.
520 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
521                            SDValue *Parts, unsigned NumParts, MVT PartVT,
522                            const Value *V,
523                            Optional<CallingConv::ID> CallConv = None,
524                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
525   // Let the target split the parts if it wants to
526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
527   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
528                                       CallConv))
529     return;
530   EVT ValueVT = Val.getValueType();
531 
532   // Handle the vector case separately.
533   if (ValueVT.isVector())
534     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
535                                 CallConv);
536 
537   unsigned PartBits = PartVT.getSizeInBits();
538   unsigned OrigNumParts = NumParts;
539   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
540          "Copying to an illegal type!");
541 
542   if (NumParts == 0)
543     return;
544 
545   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
546   EVT PartEVT = PartVT;
547   if (PartEVT == ValueVT) {
548     assert(NumParts == 1 && "No-op copy with multiple parts!");
549     Parts[0] = Val;
550     return;
551   }
552 
553   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
554     // If the parts cover more bits than the value has, promote the value.
555     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
556       assert(NumParts == 1 && "Do not know what to promote to!");
557       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
558     } else {
559       if (ValueVT.isFloatingPoint()) {
560         // FP values need to be bitcast, then extended if they are being put
561         // into a larger container.
562         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
563         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
564       }
565       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
566              ValueVT.isInteger() &&
567              "Unknown mismatch!");
568       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
569       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
570       if (PartVT == MVT::x86mmx)
571         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
572     }
573   } else if (PartBits == ValueVT.getSizeInBits()) {
574     // Different types of the same size.
575     assert(NumParts == 1 && PartEVT != ValueVT);
576     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
577   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
578     // If the parts cover less bits than value has, truncate the value.
579     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
580            ValueVT.isInteger() &&
581            "Unknown mismatch!");
582     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
583     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
584     if (PartVT == MVT::x86mmx)
585       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
586   }
587 
588   // The value may have changed - recompute ValueVT.
589   ValueVT = Val.getValueType();
590   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
591          "Failed to tile the value with PartVT!");
592 
593   if (NumParts == 1) {
594     if (PartEVT != ValueVT) {
595       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
596                                         "scalar-to-vector conversion failed");
597       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
598     }
599 
600     Parts[0] = Val;
601     return;
602   }
603 
604   // Expand the value into multiple parts.
605   if (NumParts & (NumParts - 1)) {
606     // The number of parts is not a power of 2.  Split off and copy the tail.
607     assert(PartVT.isInteger() && ValueVT.isInteger() &&
608            "Do not know what to expand to!");
609     unsigned RoundParts = 1 << Log2_32(NumParts);
610     unsigned RoundBits = RoundParts * PartBits;
611     unsigned OddParts = NumParts - RoundParts;
612     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
613       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
614 
615     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
616                    CallConv);
617 
618     if (DAG.getDataLayout().isBigEndian())
619       // The odd parts were reversed by getCopyToParts - unreverse them.
620       std::reverse(Parts + RoundParts, Parts + NumParts);
621 
622     NumParts = RoundParts;
623     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
624     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
625   }
626 
627   // The number of parts is a power of 2.  Repeatedly bisect the value using
628   // EXTRACT_ELEMENT.
629   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
630                          EVT::getIntegerVT(*DAG.getContext(),
631                                            ValueVT.getSizeInBits()),
632                          Val);
633 
634   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
635     for (unsigned i = 0; i < NumParts; i += StepSize) {
636       unsigned ThisBits = StepSize * PartBits / 2;
637       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
638       SDValue &Part0 = Parts[i];
639       SDValue &Part1 = Parts[i+StepSize/2];
640 
641       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
642                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
643       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
644                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
645 
646       if (ThisBits == PartBits && ThisVT != PartVT) {
647         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
648         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
649       }
650     }
651   }
652 
653   if (DAG.getDataLayout().isBigEndian())
654     std::reverse(Parts, Parts + OrigNumParts);
655 }
656 
657 static SDValue widenVectorToPartType(SelectionDAG &DAG,
658                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
659   if (!PartVT.isVector())
660     return SDValue();
661 
662   EVT ValueVT = Val.getValueType();
663   unsigned PartNumElts = PartVT.getVectorNumElements();
664   unsigned ValueNumElts = ValueVT.getVectorNumElements();
665   if (PartNumElts > ValueNumElts &&
666       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
667     EVT ElementVT = PartVT.getVectorElementType();
668     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
669     // undef elements.
670     SmallVector<SDValue, 16> Ops;
671     DAG.ExtractVectorElements(Val, Ops);
672     SDValue EltUndef = DAG.getUNDEF(ElementVT);
673     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
674       Ops.push_back(EltUndef);
675 
676     // FIXME: Use CONCAT for 2x -> 4x.
677     return DAG.getBuildVector(PartVT, DL, Ops);
678   }
679 
680   return SDValue();
681 }
682 
683 /// getCopyToPartsVector - Create a series of nodes that contain the specified
684 /// value split into legal parts.
685 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
686                                  SDValue Val, SDValue *Parts, unsigned NumParts,
687                                  MVT PartVT, const Value *V,
688                                  Optional<CallingConv::ID> CallConv) {
689   EVT ValueVT = Val.getValueType();
690   assert(ValueVT.isVector() && "Not a vector");
691   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
692   const bool IsABIRegCopy = CallConv.hasValue();
693 
694   if (NumParts == 1) {
695     EVT PartEVT = PartVT;
696     if (PartEVT == ValueVT) {
697       // Nothing to do.
698     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
699       // Bitconvert vector->vector case.
700       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
701     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
702       Val = Widened;
703     } else if (PartVT.isVector() &&
704                PartEVT.getVectorElementType().bitsGE(
705                  ValueVT.getVectorElementType()) &&
706                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
707 
708       // Promoted vector extract
709       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
710     } else {
711       if (ValueVT.getVectorNumElements() == 1) {
712         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
713                           DAG.getVectorIdxConstant(0, DL));
714       } else {
715         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
716                "lossy conversion of vector to scalar type");
717         EVT IntermediateType =
718             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
719         Val = DAG.getBitcast(IntermediateType, Val);
720         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
721       }
722     }
723 
724     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
725     Parts[0] = Val;
726     return;
727   }
728 
729   // Handle a multi-element vector.
730   EVT IntermediateVT;
731   MVT RegisterVT;
732   unsigned NumIntermediates;
733   unsigned NumRegs;
734   if (IsABIRegCopy) {
735     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
736         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
737         NumIntermediates, RegisterVT);
738   } else {
739     NumRegs =
740         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
741                                    NumIntermediates, RegisterVT);
742   }
743 
744   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
745   NumParts = NumRegs; // Silence a compiler warning.
746   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
747 
748   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
749          "Mixing scalable and fixed vectors when copying in parts");
750 
751   ElementCount DestEltCnt;
752 
753   if (IntermediateVT.isVector())
754     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
755   else
756     DestEltCnt = ElementCount(NumIntermediates, false);
757 
758   EVT BuiltVectorTy = EVT::getVectorVT(
759       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt);
760   if (ValueVT != BuiltVectorTy) {
761     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
762       Val = Widened;
763 
764     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
765   }
766 
767   // Split the vector into intermediate operands.
768   SmallVector<SDValue, 8> Ops(NumIntermediates);
769   for (unsigned i = 0; i != NumIntermediates; ++i) {
770     if (IntermediateVT.isVector()) {
771       // This does something sensible for scalable vectors - see the
772       // definition of EXTRACT_SUBVECTOR for further details.
773       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
774       Ops[i] =
775           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
776                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
777     } else {
778       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
779                            DAG.getVectorIdxConstant(i, DL));
780     }
781   }
782 
783   // Split the intermediate operands into legal parts.
784   if (NumParts == NumIntermediates) {
785     // If the register was not expanded, promote or copy the value,
786     // as appropriate.
787     for (unsigned i = 0; i != NumParts; ++i)
788       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
789   } else if (NumParts > 0) {
790     // If the intermediate type was expanded, split each the value into
791     // legal parts.
792     assert(NumIntermediates != 0 && "division by zero");
793     assert(NumParts % NumIntermediates == 0 &&
794            "Must expand into a divisible number of parts!");
795     unsigned Factor = NumParts / NumIntermediates;
796     for (unsigned i = 0; i != NumIntermediates; ++i)
797       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
798                      CallConv);
799   }
800 }
801 
802 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
803                            EVT valuevt, Optional<CallingConv::ID> CC)
804     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
805       RegCount(1, regs.size()), CallConv(CC) {}
806 
807 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
808                            const DataLayout &DL, unsigned Reg, Type *Ty,
809                            Optional<CallingConv::ID> CC) {
810   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
811 
812   CallConv = CC;
813 
814   for (EVT ValueVT : ValueVTs) {
815     unsigned NumRegs =
816         isABIMangled()
817             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
818             : TLI.getNumRegisters(Context, ValueVT);
819     MVT RegisterVT =
820         isABIMangled()
821             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
822             : TLI.getRegisterType(Context, ValueVT);
823     for (unsigned i = 0; i != NumRegs; ++i)
824       Regs.push_back(Reg + i);
825     RegVTs.push_back(RegisterVT);
826     RegCount.push_back(NumRegs);
827     Reg += NumRegs;
828   }
829 }
830 
831 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
832                                       FunctionLoweringInfo &FuncInfo,
833                                       const SDLoc &dl, SDValue &Chain,
834                                       SDValue *Flag, const Value *V) const {
835   // A Value with type {} or [0 x %t] needs no registers.
836   if (ValueVTs.empty())
837     return SDValue();
838 
839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
840 
841   // Assemble the legal parts into the final values.
842   SmallVector<SDValue, 4> Values(ValueVTs.size());
843   SmallVector<SDValue, 8> Parts;
844   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
845     // Copy the legal parts from the registers.
846     EVT ValueVT = ValueVTs[Value];
847     unsigned NumRegs = RegCount[Value];
848     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
849                                           *DAG.getContext(),
850                                           CallConv.getValue(), RegVTs[Value])
851                                     : RegVTs[Value];
852 
853     Parts.resize(NumRegs);
854     for (unsigned i = 0; i != NumRegs; ++i) {
855       SDValue P;
856       if (!Flag) {
857         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
858       } else {
859         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
860         *Flag = P.getValue(2);
861       }
862 
863       Chain = P.getValue(1);
864       Parts[i] = P;
865 
866       // If the source register was virtual and if we know something about it,
867       // add an assert node.
868       if (!Register::isVirtualRegister(Regs[Part + i]) ||
869           !RegisterVT.isInteger())
870         continue;
871 
872       const FunctionLoweringInfo::LiveOutInfo *LOI =
873         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
874       if (!LOI)
875         continue;
876 
877       unsigned RegSize = RegisterVT.getScalarSizeInBits();
878       unsigned NumSignBits = LOI->NumSignBits;
879       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
880 
881       if (NumZeroBits == RegSize) {
882         // The current value is a zero.
883         // Explicitly express that as it would be easier for
884         // optimizations to kick in.
885         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
886         continue;
887       }
888 
889       // FIXME: We capture more information than the dag can represent.  For
890       // now, just use the tightest assertzext/assertsext possible.
891       bool isSExt;
892       EVT FromVT(MVT::Other);
893       if (NumZeroBits) {
894         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
895         isSExt = false;
896       } else if (NumSignBits > 1) {
897         FromVT =
898             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
899         isSExt = true;
900       } else {
901         continue;
902       }
903       // Add an assertion node.
904       assert(FromVT != MVT::Other);
905       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
906                              RegisterVT, P, DAG.getValueType(FromVT));
907     }
908 
909     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
910                                      RegisterVT, ValueVT, V, CallConv);
911     Part += NumRegs;
912     Parts.clear();
913   }
914 
915   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
916 }
917 
918 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
919                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
920                                  const Value *V,
921                                  ISD::NodeType PreferredExtendType) const {
922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
923   ISD::NodeType ExtendKind = PreferredExtendType;
924 
925   // Get the list of the values's legal parts.
926   unsigned NumRegs = Regs.size();
927   SmallVector<SDValue, 8> Parts(NumRegs);
928   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
929     unsigned NumParts = RegCount[Value];
930 
931     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
932                                           *DAG.getContext(),
933                                           CallConv.getValue(), RegVTs[Value])
934                                     : RegVTs[Value];
935 
936     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
937       ExtendKind = ISD::ZERO_EXTEND;
938 
939     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
940                    NumParts, RegisterVT, V, CallConv, ExtendKind);
941     Part += NumParts;
942   }
943 
944   // Copy the parts into the registers.
945   SmallVector<SDValue, 8> Chains(NumRegs);
946   for (unsigned i = 0; i != NumRegs; ++i) {
947     SDValue Part;
948     if (!Flag) {
949       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
950     } else {
951       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
952       *Flag = Part.getValue(1);
953     }
954 
955     Chains[i] = Part.getValue(0);
956   }
957 
958   if (NumRegs == 1 || Flag)
959     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
960     // flagged to it. That is the CopyToReg nodes and the user are considered
961     // a single scheduling unit. If we create a TokenFactor and return it as
962     // chain, then the TokenFactor is both a predecessor (operand) of the
963     // user as well as a successor (the TF operands are flagged to the user).
964     // c1, f1 = CopyToReg
965     // c2, f2 = CopyToReg
966     // c3     = TokenFactor c1, c2
967     // ...
968     //        = op c3, ..., f2
969     Chain = Chains[NumRegs-1];
970   else
971     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
972 }
973 
974 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
975                                         unsigned MatchingIdx, const SDLoc &dl,
976                                         SelectionDAG &DAG,
977                                         std::vector<SDValue> &Ops) const {
978   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
979 
980   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
981   if (HasMatching)
982     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
983   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
984     // Put the register class of the virtual registers in the flag word.  That
985     // way, later passes can recompute register class constraints for inline
986     // assembly as well as normal instructions.
987     // Don't do this for tied operands that can use the regclass information
988     // from the def.
989     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
990     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
991     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
992   }
993 
994   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
995   Ops.push_back(Res);
996 
997   if (Code == InlineAsm::Kind_Clobber) {
998     // Clobbers should always have a 1:1 mapping with registers, and may
999     // reference registers that have illegal (e.g. vector) types. Hence, we
1000     // shouldn't try to apply any sort of splitting logic to them.
1001     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1002            "No 1:1 mapping from clobbers to regs?");
1003     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
1004     (void)SP;
1005     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1006       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1007       assert(
1008           (Regs[I] != SP ||
1009            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1010           "If we clobbered the stack pointer, MFI should know about it.");
1011     }
1012     return;
1013   }
1014 
1015   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1016     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
1017     MVT RegisterVT = RegVTs[Value];
1018     for (unsigned i = 0; i != NumRegs; ++i) {
1019       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1020       unsigned TheReg = Regs[Reg++];
1021       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1022     }
1023   }
1024 }
1025 
1026 SmallVector<std::pair<unsigned, unsigned>, 4>
1027 RegsForValue::getRegsAndSizes() const {
1028   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1029   unsigned I = 0;
1030   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1031     unsigned RegCount = std::get<0>(CountAndVT);
1032     MVT RegisterVT = std::get<1>(CountAndVT);
1033     unsigned RegisterSize = RegisterVT.getSizeInBits();
1034     for (unsigned E = I + RegCount; I != E; ++I)
1035       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1036   }
1037   return OutVec;
1038 }
1039 
1040 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1041                                const TargetLibraryInfo *li) {
1042   AA = aa;
1043   GFI = gfi;
1044   LibInfo = li;
1045   DL = &DAG.getDataLayout();
1046   Context = DAG.getContext();
1047   LPadToCallSiteMap.clear();
1048   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1049 }
1050 
1051 void SelectionDAGBuilder::clear() {
1052   NodeMap.clear();
1053   UnusedArgNodeMap.clear();
1054   PendingLoads.clear();
1055   PendingExports.clear();
1056   PendingConstrainedFP.clear();
1057   PendingConstrainedFPStrict.clear();
1058   CurInst = nullptr;
1059   HasTailCall = false;
1060   SDNodeOrder = LowestSDNodeOrder;
1061   StatepointLowering.clear();
1062 }
1063 
1064 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1065   DanglingDebugInfoMap.clear();
1066 }
1067 
1068 // Update DAG root to include dependencies on Pending chains.
1069 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1070   SDValue Root = DAG.getRoot();
1071 
1072   if (Pending.empty())
1073     return Root;
1074 
1075   // Add current root to PendingChains, unless we already indirectly
1076   // depend on it.
1077   if (Root.getOpcode() != ISD::EntryToken) {
1078     unsigned i = 0, e = Pending.size();
1079     for (; i != e; ++i) {
1080       assert(Pending[i].getNode()->getNumOperands() > 1);
1081       if (Pending[i].getNode()->getOperand(0) == Root)
1082         break;  // Don't add the root if we already indirectly depend on it.
1083     }
1084 
1085     if (i == e)
1086       Pending.push_back(Root);
1087   }
1088 
1089   if (Pending.size() == 1)
1090     Root = Pending[0];
1091   else
1092     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1093 
1094   DAG.setRoot(Root);
1095   Pending.clear();
1096   return Root;
1097 }
1098 
1099 SDValue SelectionDAGBuilder::getMemoryRoot() {
1100   return updateRoot(PendingLoads);
1101 }
1102 
1103 SDValue SelectionDAGBuilder::getRoot() {
1104   // Chain up all pending constrained intrinsics together with all
1105   // pending loads, by simply appending them to PendingLoads and
1106   // then calling getMemoryRoot().
1107   PendingLoads.reserve(PendingLoads.size() +
1108                        PendingConstrainedFP.size() +
1109                        PendingConstrainedFPStrict.size());
1110   PendingLoads.append(PendingConstrainedFP.begin(),
1111                       PendingConstrainedFP.end());
1112   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1113                       PendingConstrainedFPStrict.end());
1114   PendingConstrainedFP.clear();
1115   PendingConstrainedFPStrict.clear();
1116   return getMemoryRoot();
1117 }
1118 
1119 SDValue SelectionDAGBuilder::getControlRoot() {
1120   // We need to emit pending fpexcept.strict constrained intrinsics,
1121   // so append them to the PendingExports list.
1122   PendingExports.append(PendingConstrainedFPStrict.begin(),
1123                         PendingConstrainedFPStrict.end());
1124   PendingConstrainedFPStrict.clear();
1125   return updateRoot(PendingExports);
1126 }
1127 
1128 void SelectionDAGBuilder::visit(const Instruction &I) {
1129   // Set up outgoing PHI node register values before emitting the terminator.
1130   if (I.isTerminator()) {
1131     HandlePHINodesInSuccessorBlocks(I.getParent());
1132   }
1133 
1134   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1135   if (!isa<DbgInfoIntrinsic>(I))
1136     ++SDNodeOrder;
1137 
1138   CurInst = &I;
1139 
1140   visit(I.getOpcode(), I);
1141 
1142   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1143     // ConstrainedFPIntrinsics handle their own FMF.
1144     if (!isa<ConstrainedFPIntrinsic>(&I)) {
1145       // Propagate the fast-math-flags of this IR instruction to the DAG node that
1146       // maps to this instruction.
1147       // TODO: We could handle all flags (nsw, etc) here.
1148       // TODO: If an IR instruction maps to >1 node, only the final node will have
1149       //       flags set.
1150       if (SDNode *Node = getNodeForIRValue(&I)) {
1151         SDNodeFlags IncomingFlags;
1152         IncomingFlags.copyFMF(*FPMO);
1153         if (!Node->getFlags().isDefined())
1154           Node->setFlags(IncomingFlags);
1155         else
1156           Node->intersectFlagsWith(IncomingFlags);
1157       }
1158     }
1159   }
1160 
1161   if (!I.isTerminator() && !HasTailCall &&
1162       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1163     CopyToExportRegsIfNeeded(&I);
1164 
1165   CurInst = nullptr;
1166 }
1167 
1168 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1169   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1170 }
1171 
1172 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1173   // Note: this doesn't use InstVisitor, because it has to work with
1174   // ConstantExpr's in addition to instructions.
1175   switch (Opcode) {
1176   default: llvm_unreachable("Unknown instruction type encountered!");
1177     // Build the switch statement using the Instruction.def file.
1178 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1179     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1180 #include "llvm/IR/Instruction.def"
1181   }
1182 }
1183 
1184 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1185                                                 const DIExpression *Expr) {
1186   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1187     const DbgValueInst *DI = DDI.getDI();
1188     DIVariable *DanglingVariable = DI->getVariable();
1189     DIExpression *DanglingExpr = DI->getExpression();
1190     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1191       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1192       return true;
1193     }
1194     return false;
1195   };
1196 
1197   for (auto &DDIMI : DanglingDebugInfoMap) {
1198     DanglingDebugInfoVector &DDIV = DDIMI.second;
1199 
1200     // If debug info is to be dropped, run it through final checks to see
1201     // whether it can be salvaged.
1202     for (auto &DDI : DDIV)
1203       if (isMatchingDbgValue(DDI))
1204         salvageUnresolvedDbgValue(DDI);
1205 
1206     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1207   }
1208 }
1209 
1210 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1211 // generate the debug data structures now that we've seen its definition.
1212 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1213                                                    SDValue Val) {
1214   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1215   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1216     return;
1217 
1218   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1219   for (auto &DDI : DDIV) {
1220     const DbgValueInst *DI = DDI.getDI();
1221     assert(DI && "Ill-formed DanglingDebugInfo");
1222     DebugLoc dl = DDI.getdl();
1223     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1224     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1225     DILocalVariable *Variable = DI->getVariable();
1226     DIExpression *Expr = DI->getExpression();
1227     assert(Variable->isValidLocationForIntrinsic(dl) &&
1228            "Expected inlined-at fields to agree");
1229     SDDbgValue *SDV;
1230     if (Val.getNode()) {
1231       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1232       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1233       // we couldn't resolve it directly when examining the DbgValue intrinsic
1234       // in the first place we should not be more successful here). Unless we
1235       // have some test case that prove this to be correct we should avoid
1236       // calling EmitFuncArgumentDbgValue here.
1237       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1238         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1239                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1240         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1241         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1242         // inserted after the definition of Val when emitting the instructions
1243         // after ISel. An alternative could be to teach
1244         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1245         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1246                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1247                    << ValSDNodeOrder << "\n");
1248         SDV = getDbgValue(Val, Variable, Expr, dl,
1249                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1250         DAG.AddDbgValue(SDV, Val.getNode(), false);
1251       } else
1252         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1253                           << "in EmitFuncArgumentDbgValue\n");
1254     } else {
1255       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1256       auto Undef =
1257           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1258       auto SDV =
1259           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1260       DAG.AddDbgValue(SDV, nullptr, false);
1261     }
1262   }
1263   DDIV.clear();
1264 }
1265 
1266 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1267   Value *V = DDI.getDI()->getValue();
1268   DILocalVariable *Var = DDI.getDI()->getVariable();
1269   DIExpression *Expr = DDI.getDI()->getExpression();
1270   DebugLoc DL = DDI.getdl();
1271   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1272   unsigned SDOrder = DDI.getSDNodeOrder();
1273 
1274   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1275   // that DW_OP_stack_value is desired.
1276   assert(isa<DbgValueInst>(DDI.getDI()));
1277   bool StackValue = true;
1278 
1279   // Can this Value can be encoded without any further work?
1280   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1281     return;
1282 
1283   // Attempt to salvage back through as many instructions as possible. Bail if
1284   // a non-instruction is seen, such as a constant expression or global
1285   // variable. FIXME: Further work could recover those too.
1286   while (isa<Instruction>(V)) {
1287     Instruction &VAsInst = *cast<Instruction>(V);
1288     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1289 
1290     // If we cannot salvage any further, and haven't yet found a suitable debug
1291     // expression, bail out.
1292     if (!NewExpr)
1293       break;
1294 
1295     // New value and expr now represent this debuginfo.
1296     V = VAsInst.getOperand(0);
1297     Expr = NewExpr;
1298 
1299     // Some kind of simplification occurred: check whether the operand of the
1300     // salvaged debug expression can be encoded in this DAG.
1301     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1302       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1303                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1304       return;
1305     }
1306   }
1307 
1308   // This was the final opportunity to salvage this debug information, and it
1309   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1310   // any earlier variable location.
1311   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1312   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1313   DAG.AddDbgValue(SDV, nullptr, false);
1314 
1315   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1316                     << "\n");
1317   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1318                     << "\n");
1319 }
1320 
1321 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1322                                            DIExpression *Expr, DebugLoc dl,
1323                                            DebugLoc InstDL, unsigned Order) {
1324   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1325   SDDbgValue *SDV;
1326   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1327       isa<ConstantPointerNull>(V)) {
1328     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1329     DAG.AddDbgValue(SDV, nullptr, false);
1330     return true;
1331   }
1332 
1333   // If the Value is a frame index, we can create a FrameIndex debug value
1334   // without relying on the DAG at all.
1335   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1336     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1337     if (SI != FuncInfo.StaticAllocaMap.end()) {
1338       auto SDV =
1339           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1340                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1341       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1342       // is still available even if the SDNode gets optimized out.
1343       DAG.AddDbgValue(SDV, nullptr, false);
1344       return true;
1345     }
1346   }
1347 
1348   // Do not use getValue() in here; we don't want to generate code at
1349   // this point if it hasn't been done yet.
1350   SDValue N = NodeMap[V];
1351   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1352     N = UnusedArgNodeMap[V];
1353   if (N.getNode()) {
1354     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1355       return true;
1356     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1357     DAG.AddDbgValue(SDV, N.getNode(), false);
1358     return true;
1359   }
1360 
1361   // Special rules apply for the first dbg.values of parameter variables in a
1362   // function. Identify them by the fact they reference Argument Values, that
1363   // they're parameters, and they are parameters of the current function. We
1364   // need to let them dangle until they get an SDNode.
1365   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1366                        !InstDL.getInlinedAt();
1367   if (!IsParamOfFunc) {
1368     // The value is not used in this block yet (or it would have an SDNode).
1369     // We still want the value to appear for the user if possible -- if it has
1370     // an associated VReg, we can refer to that instead.
1371     auto VMI = FuncInfo.ValueMap.find(V);
1372     if (VMI != FuncInfo.ValueMap.end()) {
1373       unsigned Reg = VMI->second;
1374       // If this is a PHI node, it may be split up into several MI PHI nodes
1375       // (in FunctionLoweringInfo::set).
1376       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1377                        V->getType(), None);
1378       if (RFV.occupiesMultipleRegs()) {
1379         unsigned Offset = 0;
1380         unsigned BitsToDescribe = 0;
1381         if (auto VarSize = Var->getSizeInBits())
1382           BitsToDescribe = *VarSize;
1383         if (auto Fragment = Expr->getFragmentInfo())
1384           BitsToDescribe = Fragment->SizeInBits;
1385         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1386           unsigned RegisterSize = RegAndSize.second;
1387           // Bail out if all bits are described already.
1388           if (Offset >= BitsToDescribe)
1389             break;
1390           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1391               ? BitsToDescribe - Offset
1392               : RegisterSize;
1393           auto FragmentExpr = DIExpression::createFragmentExpression(
1394               Expr, Offset, FragmentSize);
1395           if (!FragmentExpr)
1396               continue;
1397           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1398                                     false, dl, SDNodeOrder);
1399           DAG.AddDbgValue(SDV, nullptr, false);
1400           Offset += RegisterSize;
1401         }
1402       } else {
1403         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1404         DAG.AddDbgValue(SDV, nullptr, false);
1405       }
1406       return true;
1407     }
1408   }
1409 
1410   return false;
1411 }
1412 
1413 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1414   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1415   for (auto &Pair : DanglingDebugInfoMap)
1416     for (auto &DDI : Pair.second)
1417       salvageUnresolvedDbgValue(DDI);
1418   clearDanglingDebugInfo();
1419 }
1420 
1421 /// getCopyFromRegs - If there was virtual register allocated for the value V
1422 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1423 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1424   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1425   SDValue Result;
1426 
1427   if (It != FuncInfo.ValueMap.end()) {
1428     Register InReg = It->second;
1429 
1430     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1431                      DAG.getDataLayout(), InReg, Ty,
1432                      None); // This is not an ABI copy.
1433     SDValue Chain = DAG.getEntryNode();
1434     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1435                                  V);
1436     resolveDanglingDebugInfo(V, Result);
1437   }
1438 
1439   return Result;
1440 }
1441 
1442 /// getValue - Return an SDValue for the given Value.
1443 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1444   // If we already have an SDValue for this value, use it. It's important
1445   // to do this first, so that we don't create a CopyFromReg if we already
1446   // have a regular SDValue.
1447   SDValue &N = NodeMap[V];
1448   if (N.getNode()) return N;
1449 
1450   // If there's a virtual register allocated and initialized for this
1451   // value, use it.
1452   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1453     return copyFromReg;
1454 
1455   // Otherwise create a new SDValue and remember it.
1456   SDValue Val = getValueImpl(V);
1457   NodeMap[V] = Val;
1458   resolveDanglingDebugInfo(V, Val);
1459   return Val;
1460 }
1461 
1462 /// getNonRegisterValue - Return an SDValue for the given Value, but
1463 /// don't look in FuncInfo.ValueMap for a virtual register.
1464 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1465   // If we already have an SDValue for this value, use it.
1466   SDValue &N = NodeMap[V];
1467   if (N.getNode()) {
1468     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1469       // Remove the debug location from the node as the node is about to be used
1470       // in a location which may differ from the original debug location.  This
1471       // is relevant to Constant and ConstantFP nodes because they can appear
1472       // as constant expressions inside PHI nodes.
1473       N->setDebugLoc(DebugLoc());
1474     }
1475     return N;
1476   }
1477 
1478   // Otherwise create a new SDValue and remember it.
1479   SDValue Val = getValueImpl(V);
1480   NodeMap[V] = Val;
1481   resolveDanglingDebugInfo(V, Val);
1482   return Val;
1483 }
1484 
1485 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1486 /// Create an SDValue for the given value.
1487 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1489 
1490   if (const Constant *C = dyn_cast<Constant>(V)) {
1491     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1492 
1493     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1494       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1495 
1496     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1497       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1498 
1499     if (isa<ConstantPointerNull>(C)) {
1500       unsigned AS = V->getType()->getPointerAddressSpace();
1501       return DAG.getConstant(0, getCurSDLoc(),
1502                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1503     }
1504 
1505     if (match(C, m_VScale(DAG.getDataLayout())))
1506       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1507 
1508     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1509       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1510 
1511     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1512       return DAG.getUNDEF(VT);
1513 
1514     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1515       visit(CE->getOpcode(), *CE);
1516       SDValue N1 = NodeMap[V];
1517       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1518       return N1;
1519     }
1520 
1521     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1522       SmallVector<SDValue, 4> Constants;
1523       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1524            OI != OE; ++OI) {
1525         SDNode *Val = getValue(*OI).getNode();
1526         // If the operand is an empty aggregate, there are no values.
1527         if (!Val) continue;
1528         // Add each leaf value from the operand to the Constants list
1529         // to form a flattened list of all the values.
1530         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1531           Constants.push_back(SDValue(Val, i));
1532       }
1533 
1534       return DAG.getMergeValues(Constants, getCurSDLoc());
1535     }
1536 
1537     if (const ConstantDataSequential *CDS =
1538           dyn_cast<ConstantDataSequential>(C)) {
1539       SmallVector<SDValue, 4> Ops;
1540       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1541         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1542         // Add each leaf value from the operand to the Constants list
1543         // to form a flattened list of all the values.
1544         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1545           Ops.push_back(SDValue(Val, i));
1546       }
1547 
1548       if (isa<ArrayType>(CDS->getType()))
1549         return DAG.getMergeValues(Ops, getCurSDLoc());
1550       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1551     }
1552 
1553     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1554       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1555              "Unknown struct or array constant!");
1556 
1557       SmallVector<EVT, 4> ValueVTs;
1558       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1559       unsigned NumElts = ValueVTs.size();
1560       if (NumElts == 0)
1561         return SDValue(); // empty struct
1562       SmallVector<SDValue, 4> Constants(NumElts);
1563       for (unsigned i = 0; i != NumElts; ++i) {
1564         EVT EltVT = ValueVTs[i];
1565         if (isa<UndefValue>(C))
1566           Constants[i] = DAG.getUNDEF(EltVT);
1567         else if (EltVT.isFloatingPoint())
1568           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1569         else
1570           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1571       }
1572 
1573       return DAG.getMergeValues(Constants, getCurSDLoc());
1574     }
1575 
1576     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1577       return DAG.getBlockAddress(BA, VT);
1578 
1579     VectorType *VecTy = cast<VectorType>(V->getType());
1580 
1581     // Now that we know the number and type of the elements, get that number of
1582     // elements into the Ops array based on what kind of constant it is.
1583     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1584       SmallVector<SDValue, 16> Ops;
1585       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1586       for (unsigned i = 0; i != NumElements; ++i)
1587         Ops.push_back(getValue(CV->getOperand(i)));
1588 
1589       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1590     } else if (isa<ConstantAggregateZero>(C)) {
1591       EVT EltVT =
1592           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1593 
1594       SDValue Op;
1595       if (EltVT.isFloatingPoint())
1596         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1597       else
1598         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1599 
1600       if (isa<ScalableVectorType>(VecTy))
1601         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1602       else {
1603         SmallVector<SDValue, 16> Ops;
1604         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1605         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1606       }
1607     }
1608     llvm_unreachable("Unknown vector constant");
1609   }
1610 
1611   // If this is a static alloca, generate it as the frameindex instead of
1612   // computation.
1613   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1614     DenseMap<const AllocaInst*, int>::iterator SI =
1615       FuncInfo.StaticAllocaMap.find(AI);
1616     if (SI != FuncInfo.StaticAllocaMap.end())
1617       return DAG.getFrameIndex(SI->second,
1618                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1619   }
1620 
1621   // If this is an instruction which fast-isel has deferred, select it now.
1622   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1623     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1624 
1625     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1626                      Inst->getType(), getABIRegCopyCC(V));
1627     SDValue Chain = DAG.getEntryNode();
1628     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1629   }
1630 
1631   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1632     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1633   }
1634   llvm_unreachable("Can't get register for value!");
1635 }
1636 
1637 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1638   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1639   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1640   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1641   bool IsSEH = isAsynchronousEHPersonality(Pers);
1642   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1643   if (!IsSEH)
1644     CatchPadMBB->setIsEHScopeEntry();
1645   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1646   if (IsMSVCCXX || IsCoreCLR)
1647     CatchPadMBB->setIsEHFuncletEntry();
1648 }
1649 
1650 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1651   // Update machine-CFG edge.
1652   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1653   FuncInfo.MBB->addSuccessor(TargetMBB);
1654 
1655   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1656   bool IsSEH = isAsynchronousEHPersonality(Pers);
1657   if (IsSEH) {
1658     // If this is not a fall-through branch or optimizations are switched off,
1659     // emit the branch.
1660     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1661         TM.getOptLevel() == CodeGenOpt::None)
1662       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1663                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1664     return;
1665   }
1666 
1667   // Figure out the funclet membership for the catchret's successor.
1668   // This will be used by the FuncletLayout pass to determine how to order the
1669   // BB's.
1670   // A 'catchret' returns to the outer scope's color.
1671   Value *ParentPad = I.getCatchSwitchParentPad();
1672   const BasicBlock *SuccessorColor;
1673   if (isa<ConstantTokenNone>(ParentPad))
1674     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1675   else
1676     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1677   assert(SuccessorColor && "No parent funclet for catchret!");
1678   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1679   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1680 
1681   // Create the terminator node.
1682   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1683                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1684                             DAG.getBasicBlock(SuccessorColorMBB));
1685   DAG.setRoot(Ret);
1686 }
1687 
1688 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1689   // Don't emit any special code for the cleanuppad instruction. It just marks
1690   // the start of an EH scope/funclet.
1691   FuncInfo.MBB->setIsEHScopeEntry();
1692   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1693   if (Pers != EHPersonality::Wasm_CXX) {
1694     FuncInfo.MBB->setIsEHFuncletEntry();
1695     FuncInfo.MBB->setIsCleanupFuncletEntry();
1696   }
1697 }
1698 
1699 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1700 // the control flow always stops at the single catch pad, as it does for a
1701 // cleanup pad. In case the exception caught is not of the types the catch pad
1702 // catches, it will be rethrown by a rethrow.
1703 static void findWasmUnwindDestinations(
1704     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1705     BranchProbability Prob,
1706     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1707         &UnwindDests) {
1708   while (EHPadBB) {
1709     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1710     if (isa<CleanupPadInst>(Pad)) {
1711       // Stop on cleanup pads.
1712       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1713       UnwindDests.back().first->setIsEHScopeEntry();
1714       break;
1715     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1716       // Add the catchpad handlers to the possible destinations. We don't
1717       // continue to the unwind destination of the catchswitch for wasm.
1718       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1719         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1720         UnwindDests.back().first->setIsEHScopeEntry();
1721       }
1722       break;
1723     } else {
1724       continue;
1725     }
1726   }
1727 }
1728 
1729 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1730 /// many places it could ultimately go. In the IR, we have a single unwind
1731 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1732 /// This function skips over imaginary basic blocks that hold catchswitch
1733 /// instructions, and finds all the "real" machine
1734 /// basic block destinations. As those destinations may not be successors of
1735 /// EHPadBB, here we also calculate the edge probability to those destinations.
1736 /// The passed-in Prob is the edge probability to EHPadBB.
1737 static void findUnwindDestinations(
1738     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1739     BranchProbability Prob,
1740     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1741         &UnwindDests) {
1742   EHPersonality Personality =
1743     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1744   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1745   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1746   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1747   bool IsSEH = isAsynchronousEHPersonality(Personality);
1748 
1749   if (IsWasmCXX) {
1750     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1751     assert(UnwindDests.size() <= 1 &&
1752            "There should be at most one unwind destination for wasm");
1753     return;
1754   }
1755 
1756   while (EHPadBB) {
1757     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1758     BasicBlock *NewEHPadBB = nullptr;
1759     if (isa<LandingPadInst>(Pad)) {
1760       // Stop on landingpads. They are not funclets.
1761       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1762       break;
1763     } else if (isa<CleanupPadInst>(Pad)) {
1764       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1765       // personalities.
1766       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1767       UnwindDests.back().first->setIsEHScopeEntry();
1768       UnwindDests.back().first->setIsEHFuncletEntry();
1769       break;
1770     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1771       // Add the catchpad handlers to the possible destinations.
1772       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1773         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1774         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1775         if (IsMSVCCXX || IsCoreCLR)
1776           UnwindDests.back().first->setIsEHFuncletEntry();
1777         if (!IsSEH)
1778           UnwindDests.back().first->setIsEHScopeEntry();
1779       }
1780       NewEHPadBB = CatchSwitch->getUnwindDest();
1781     } else {
1782       continue;
1783     }
1784 
1785     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1786     if (BPI && NewEHPadBB)
1787       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1788     EHPadBB = NewEHPadBB;
1789   }
1790 }
1791 
1792 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1793   // Update successor info.
1794   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1795   auto UnwindDest = I.getUnwindDest();
1796   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1797   BranchProbability UnwindDestProb =
1798       (BPI && UnwindDest)
1799           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1800           : BranchProbability::getZero();
1801   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1802   for (auto &UnwindDest : UnwindDests) {
1803     UnwindDest.first->setIsEHPad();
1804     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1805   }
1806   FuncInfo.MBB->normalizeSuccProbs();
1807 
1808   // Create the terminator node.
1809   SDValue Ret =
1810       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1811   DAG.setRoot(Ret);
1812 }
1813 
1814 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1815   report_fatal_error("visitCatchSwitch not yet implemented!");
1816 }
1817 
1818 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1820   auto &DL = DAG.getDataLayout();
1821   SDValue Chain = getControlRoot();
1822   SmallVector<ISD::OutputArg, 8> Outs;
1823   SmallVector<SDValue, 8> OutVals;
1824 
1825   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1826   // lower
1827   //
1828   //   %val = call <ty> @llvm.experimental.deoptimize()
1829   //   ret <ty> %val
1830   //
1831   // differently.
1832   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1833     LowerDeoptimizingReturn();
1834     return;
1835   }
1836 
1837   if (!FuncInfo.CanLowerReturn) {
1838     unsigned DemoteReg = FuncInfo.DemoteRegister;
1839     const Function *F = I.getParent()->getParent();
1840 
1841     // Emit a store of the return value through the virtual register.
1842     // Leave Outs empty so that LowerReturn won't try to load return
1843     // registers the usual way.
1844     SmallVector<EVT, 1> PtrValueVTs;
1845     ComputeValueVTs(TLI, DL,
1846                     F->getReturnType()->getPointerTo(
1847                         DAG.getDataLayout().getAllocaAddrSpace()),
1848                     PtrValueVTs);
1849 
1850     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1851                                         DemoteReg, PtrValueVTs[0]);
1852     SDValue RetOp = getValue(I.getOperand(0));
1853 
1854     SmallVector<EVT, 4> ValueVTs, MemVTs;
1855     SmallVector<uint64_t, 4> Offsets;
1856     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1857                     &Offsets);
1858     unsigned NumValues = ValueVTs.size();
1859 
1860     SmallVector<SDValue, 4> Chains(NumValues);
1861     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1862     for (unsigned i = 0; i != NumValues; ++i) {
1863       // An aggregate return value cannot wrap around the address space, so
1864       // offsets to its parts don't wrap either.
1865       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1866 
1867       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1868       if (MemVTs[i] != ValueVTs[i])
1869         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1870       Chains[i] = DAG.getStore(
1871           Chain, getCurSDLoc(), Val,
1872           // FIXME: better loc info would be nice.
1873           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1874           commonAlignment(BaseAlign, Offsets[i]));
1875     }
1876 
1877     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1878                         MVT::Other, Chains);
1879   } else if (I.getNumOperands() != 0) {
1880     SmallVector<EVT, 4> ValueVTs;
1881     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1882     unsigned NumValues = ValueVTs.size();
1883     if (NumValues) {
1884       SDValue RetOp = getValue(I.getOperand(0));
1885 
1886       const Function *F = I.getParent()->getParent();
1887 
1888       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1889           I.getOperand(0)->getType(), F->getCallingConv(),
1890           /*IsVarArg*/ false);
1891 
1892       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1893       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1894                                           Attribute::SExt))
1895         ExtendKind = ISD::SIGN_EXTEND;
1896       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1897                                                Attribute::ZExt))
1898         ExtendKind = ISD::ZERO_EXTEND;
1899 
1900       LLVMContext &Context = F->getContext();
1901       bool RetInReg = F->getAttributes().hasAttribute(
1902           AttributeList::ReturnIndex, Attribute::InReg);
1903 
1904       for (unsigned j = 0; j != NumValues; ++j) {
1905         EVT VT = ValueVTs[j];
1906 
1907         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1908           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1909 
1910         CallingConv::ID CC = F->getCallingConv();
1911 
1912         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1913         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1914         SmallVector<SDValue, 4> Parts(NumParts);
1915         getCopyToParts(DAG, getCurSDLoc(),
1916                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1917                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1918 
1919         // 'inreg' on function refers to return value
1920         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1921         if (RetInReg)
1922           Flags.setInReg();
1923 
1924         if (I.getOperand(0)->getType()->isPointerTy()) {
1925           Flags.setPointer();
1926           Flags.setPointerAddrSpace(
1927               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1928         }
1929 
1930         if (NeedsRegBlock) {
1931           Flags.setInConsecutiveRegs();
1932           if (j == NumValues - 1)
1933             Flags.setInConsecutiveRegsLast();
1934         }
1935 
1936         // Propagate extension type if any
1937         if (ExtendKind == ISD::SIGN_EXTEND)
1938           Flags.setSExt();
1939         else if (ExtendKind == ISD::ZERO_EXTEND)
1940           Flags.setZExt();
1941 
1942         for (unsigned i = 0; i < NumParts; ++i) {
1943           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1944                                         VT, /*isfixed=*/true, 0, 0));
1945           OutVals.push_back(Parts[i]);
1946         }
1947       }
1948     }
1949   }
1950 
1951   // Push in swifterror virtual register as the last element of Outs. This makes
1952   // sure swifterror virtual register will be returned in the swifterror
1953   // physical register.
1954   const Function *F = I.getParent()->getParent();
1955   if (TLI.supportSwiftError() &&
1956       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1957     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1958     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1959     Flags.setSwiftError();
1960     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1961                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1962                                   true /*isfixed*/, 1 /*origidx*/,
1963                                   0 /*partOffs*/));
1964     // Create SDNode for the swifterror virtual register.
1965     OutVals.push_back(
1966         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1967                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1968                         EVT(TLI.getPointerTy(DL))));
1969   }
1970 
1971   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1972   CallingConv::ID CallConv =
1973     DAG.getMachineFunction().getFunction().getCallingConv();
1974   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1975       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1976 
1977   // Verify that the target's LowerReturn behaved as expected.
1978   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1979          "LowerReturn didn't return a valid chain!");
1980 
1981   // Update the DAG with the new chain value resulting from return lowering.
1982   DAG.setRoot(Chain);
1983 }
1984 
1985 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1986 /// created for it, emit nodes to copy the value into the virtual
1987 /// registers.
1988 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1989   // Skip empty types
1990   if (V->getType()->isEmptyTy())
1991     return;
1992 
1993   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1994   if (VMI != FuncInfo.ValueMap.end()) {
1995     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1996     CopyValueToVirtualRegister(V, VMI->second);
1997   }
1998 }
1999 
2000 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2001 /// the current basic block, add it to ValueMap now so that we'll get a
2002 /// CopyTo/FromReg.
2003 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2004   // No need to export constants.
2005   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2006 
2007   // Already exported?
2008   if (FuncInfo.isExportedInst(V)) return;
2009 
2010   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2011   CopyValueToVirtualRegister(V, Reg);
2012 }
2013 
2014 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2015                                                      const BasicBlock *FromBB) {
2016   // The operands of the setcc have to be in this block.  We don't know
2017   // how to export them from some other block.
2018   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2019     // Can export from current BB.
2020     if (VI->getParent() == FromBB)
2021       return true;
2022 
2023     // Is already exported, noop.
2024     return FuncInfo.isExportedInst(V);
2025   }
2026 
2027   // If this is an argument, we can export it if the BB is the entry block or
2028   // if it is already exported.
2029   if (isa<Argument>(V)) {
2030     if (FromBB == &FromBB->getParent()->getEntryBlock())
2031       return true;
2032 
2033     // Otherwise, can only export this if it is already exported.
2034     return FuncInfo.isExportedInst(V);
2035   }
2036 
2037   // Otherwise, constants can always be exported.
2038   return true;
2039 }
2040 
2041 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2042 BranchProbability
2043 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2044                                         const MachineBasicBlock *Dst) const {
2045   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2046   const BasicBlock *SrcBB = Src->getBasicBlock();
2047   const BasicBlock *DstBB = Dst->getBasicBlock();
2048   if (!BPI) {
2049     // If BPI is not available, set the default probability as 1 / N, where N is
2050     // the number of successors.
2051     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2052     return BranchProbability(1, SuccSize);
2053   }
2054   return BPI->getEdgeProbability(SrcBB, DstBB);
2055 }
2056 
2057 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2058                                                MachineBasicBlock *Dst,
2059                                                BranchProbability Prob) {
2060   if (!FuncInfo.BPI)
2061     Src->addSuccessorWithoutProb(Dst);
2062   else {
2063     if (Prob.isUnknown())
2064       Prob = getEdgeProbability(Src, Dst);
2065     Src->addSuccessor(Dst, Prob);
2066   }
2067 }
2068 
2069 static bool InBlock(const Value *V, const BasicBlock *BB) {
2070   if (const Instruction *I = dyn_cast<Instruction>(V))
2071     return I->getParent() == BB;
2072   return true;
2073 }
2074 
2075 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2076 /// This function emits a branch and is used at the leaves of an OR or an
2077 /// AND operator tree.
2078 void
2079 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2080                                                   MachineBasicBlock *TBB,
2081                                                   MachineBasicBlock *FBB,
2082                                                   MachineBasicBlock *CurBB,
2083                                                   MachineBasicBlock *SwitchBB,
2084                                                   BranchProbability TProb,
2085                                                   BranchProbability FProb,
2086                                                   bool InvertCond) {
2087   const BasicBlock *BB = CurBB->getBasicBlock();
2088 
2089   // If the leaf of the tree is a comparison, merge the condition into
2090   // the caseblock.
2091   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2092     // The operands of the cmp have to be in this block.  We don't know
2093     // how to export them from some other block.  If this is the first block
2094     // of the sequence, no exporting is needed.
2095     if (CurBB == SwitchBB ||
2096         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2097          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2098       ISD::CondCode Condition;
2099       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2100         ICmpInst::Predicate Pred =
2101             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2102         Condition = getICmpCondCode(Pred);
2103       } else {
2104         const FCmpInst *FC = cast<FCmpInst>(Cond);
2105         FCmpInst::Predicate Pred =
2106             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2107         Condition = getFCmpCondCode(Pred);
2108         if (TM.Options.NoNaNsFPMath)
2109           Condition = getFCmpCodeWithoutNaN(Condition);
2110       }
2111 
2112       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2113                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2114       SL->SwitchCases.push_back(CB);
2115       return;
2116     }
2117   }
2118 
2119   // Create a CaseBlock record representing this branch.
2120   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2121   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2122                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2123   SL->SwitchCases.push_back(CB);
2124 }
2125 
2126 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2127                                                MachineBasicBlock *TBB,
2128                                                MachineBasicBlock *FBB,
2129                                                MachineBasicBlock *CurBB,
2130                                                MachineBasicBlock *SwitchBB,
2131                                                Instruction::BinaryOps Opc,
2132                                                BranchProbability TProb,
2133                                                BranchProbability FProb,
2134                                                bool InvertCond) {
2135   // Skip over not part of the tree and remember to invert op and operands at
2136   // next level.
2137   Value *NotCond;
2138   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2139       InBlock(NotCond, CurBB->getBasicBlock())) {
2140     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2141                          !InvertCond);
2142     return;
2143   }
2144 
2145   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2146   // Compute the effective opcode for Cond, taking into account whether it needs
2147   // to be inverted, e.g.
2148   //   and (not (or A, B)), C
2149   // gets lowered as
2150   //   and (and (not A, not B), C)
2151   unsigned BOpc = 0;
2152   if (BOp) {
2153     BOpc = BOp->getOpcode();
2154     if (InvertCond) {
2155       if (BOpc == Instruction::And)
2156         BOpc = Instruction::Or;
2157       else if (BOpc == Instruction::Or)
2158         BOpc = Instruction::And;
2159     }
2160   }
2161 
2162   // If this node is not part of the or/and tree, emit it as a branch.
2163   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2164       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2165       BOp->getParent() != CurBB->getBasicBlock() ||
2166       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2167       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2168     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2169                                  TProb, FProb, InvertCond);
2170     return;
2171   }
2172 
2173   //  Create TmpBB after CurBB.
2174   MachineFunction::iterator BBI(CurBB);
2175   MachineFunction &MF = DAG.getMachineFunction();
2176   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2177   CurBB->getParent()->insert(++BBI, TmpBB);
2178 
2179   if (Opc == Instruction::Or) {
2180     // Codegen X | Y as:
2181     // BB1:
2182     //   jmp_if_X TBB
2183     //   jmp TmpBB
2184     // TmpBB:
2185     //   jmp_if_Y TBB
2186     //   jmp FBB
2187     //
2188 
2189     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2190     // The requirement is that
2191     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2192     //     = TrueProb for original BB.
2193     // Assuming the original probabilities are A and B, one choice is to set
2194     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2195     // A/(1+B) and 2B/(1+B). This choice assumes that
2196     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2197     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2198     // TmpBB, but the math is more complicated.
2199 
2200     auto NewTrueProb = TProb / 2;
2201     auto NewFalseProb = TProb / 2 + FProb;
2202     // Emit the LHS condition.
2203     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2204                          NewTrueProb, NewFalseProb, InvertCond);
2205 
2206     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2207     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2208     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2209     // Emit the RHS condition into TmpBB.
2210     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2211                          Probs[0], Probs[1], InvertCond);
2212   } else {
2213     assert(Opc == Instruction::And && "Unknown merge op!");
2214     // Codegen X & Y as:
2215     // BB1:
2216     //   jmp_if_X TmpBB
2217     //   jmp FBB
2218     // TmpBB:
2219     //   jmp_if_Y TBB
2220     //   jmp FBB
2221     //
2222     //  This requires creation of TmpBB after CurBB.
2223 
2224     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2225     // The requirement is that
2226     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2227     //     = FalseProb for original BB.
2228     // Assuming the original probabilities are A and B, one choice is to set
2229     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2230     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2231     // TrueProb for BB1 * FalseProb for TmpBB.
2232 
2233     auto NewTrueProb = TProb + FProb / 2;
2234     auto NewFalseProb = FProb / 2;
2235     // Emit the LHS condition.
2236     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2237                          NewTrueProb, NewFalseProb, InvertCond);
2238 
2239     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2240     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2241     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2242     // Emit the RHS condition into TmpBB.
2243     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2244                          Probs[0], Probs[1], InvertCond);
2245   }
2246 }
2247 
2248 /// If the set of cases should be emitted as a series of branches, return true.
2249 /// If we should emit this as a bunch of and/or'd together conditions, return
2250 /// false.
2251 bool
2252 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2253   if (Cases.size() != 2) return true;
2254 
2255   // If this is two comparisons of the same values or'd or and'd together, they
2256   // will get folded into a single comparison, so don't emit two blocks.
2257   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2258        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2259       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2260        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2261     return false;
2262   }
2263 
2264   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2265   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2266   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2267       Cases[0].CC == Cases[1].CC &&
2268       isa<Constant>(Cases[0].CmpRHS) &&
2269       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2270     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2271       return false;
2272     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2273       return false;
2274   }
2275 
2276   return true;
2277 }
2278 
2279 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2280   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2281 
2282   // Update machine-CFG edges.
2283   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2284 
2285   if (I.isUnconditional()) {
2286     // Update machine-CFG edges.
2287     BrMBB->addSuccessor(Succ0MBB);
2288 
2289     // If this is not a fall-through branch or optimizations are switched off,
2290     // emit the branch.
2291     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2292       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2293                               MVT::Other, getControlRoot(),
2294                               DAG.getBasicBlock(Succ0MBB)));
2295 
2296     return;
2297   }
2298 
2299   // If this condition is one of the special cases we handle, do special stuff
2300   // now.
2301   const Value *CondVal = I.getCondition();
2302   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2303 
2304   // If this is a series of conditions that are or'd or and'd together, emit
2305   // this as a sequence of branches instead of setcc's with and/or operations.
2306   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2307   // unpredictable branches, and vector extracts because those jumps are likely
2308   // expensive for any target), this should improve performance.
2309   // For example, instead of something like:
2310   //     cmp A, B
2311   //     C = seteq
2312   //     cmp D, E
2313   //     F = setle
2314   //     or C, F
2315   //     jnz foo
2316   // Emit:
2317   //     cmp A, B
2318   //     je foo
2319   //     cmp D, E
2320   //     jle foo
2321   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2322     Instruction::BinaryOps Opcode = BOp->getOpcode();
2323     Value *Vec, *BOp0 = BOp->getOperand(0), *BOp1 = BOp->getOperand(1);
2324     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2325         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2326         (Opcode == Instruction::And || Opcode == Instruction::Or) &&
2327         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2328           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2329       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2330                            Opcode,
2331                            getEdgeProbability(BrMBB, Succ0MBB),
2332                            getEdgeProbability(BrMBB, Succ1MBB),
2333                            /*InvertCond=*/false);
2334       // If the compares in later blocks need to use values not currently
2335       // exported from this block, export them now.  This block should always
2336       // be the first entry.
2337       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2338 
2339       // Allow some cases to be rejected.
2340       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2341         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2342           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2343           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2344         }
2345 
2346         // Emit the branch for this block.
2347         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2348         SL->SwitchCases.erase(SL->SwitchCases.begin());
2349         return;
2350       }
2351 
2352       // Okay, we decided not to do this, remove any inserted MBB's and clear
2353       // SwitchCases.
2354       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2355         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2356 
2357       SL->SwitchCases.clear();
2358     }
2359   }
2360 
2361   // Create a CaseBlock record representing this branch.
2362   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2363                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2364 
2365   // Use visitSwitchCase to actually insert the fast branch sequence for this
2366   // cond branch.
2367   visitSwitchCase(CB, BrMBB);
2368 }
2369 
2370 /// visitSwitchCase - Emits the necessary code to represent a single node in
2371 /// the binary search tree resulting from lowering a switch instruction.
2372 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2373                                           MachineBasicBlock *SwitchBB) {
2374   SDValue Cond;
2375   SDValue CondLHS = getValue(CB.CmpLHS);
2376   SDLoc dl = CB.DL;
2377 
2378   if (CB.CC == ISD::SETTRUE) {
2379     // Branch or fall through to TrueBB.
2380     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2381     SwitchBB->normalizeSuccProbs();
2382     if (CB.TrueBB != NextBlock(SwitchBB)) {
2383       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2384                               DAG.getBasicBlock(CB.TrueBB)));
2385     }
2386     return;
2387   }
2388 
2389   auto &TLI = DAG.getTargetLoweringInfo();
2390   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2391 
2392   // Build the setcc now.
2393   if (!CB.CmpMHS) {
2394     // Fold "(X == true)" to X and "(X == false)" to !X to
2395     // handle common cases produced by branch lowering.
2396     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2397         CB.CC == ISD::SETEQ)
2398       Cond = CondLHS;
2399     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2400              CB.CC == ISD::SETEQ) {
2401       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2402       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2403     } else {
2404       SDValue CondRHS = getValue(CB.CmpRHS);
2405 
2406       // If a pointer's DAG type is larger than its memory type then the DAG
2407       // values are zero-extended. This breaks signed comparisons so truncate
2408       // back to the underlying type before doing the compare.
2409       if (CondLHS.getValueType() != MemVT) {
2410         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2411         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2412       }
2413       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2414     }
2415   } else {
2416     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2417 
2418     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2419     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2420 
2421     SDValue CmpOp = getValue(CB.CmpMHS);
2422     EVT VT = CmpOp.getValueType();
2423 
2424     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2425       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2426                           ISD::SETLE);
2427     } else {
2428       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2429                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2430       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2431                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2432     }
2433   }
2434 
2435   // Update successor info
2436   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2437   // TrueBB and FalseBB are always different unless the incoming IR is
2438   // degenerate. This only happens when running llc on weird IR.
2439   if (CB.TrueBB != CB.FalseBB)
2440     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2441   SwitchBB->normalizeSuccProbs();
2442 
2443   // If the lhs block is the next block, invert the condition so that we can
2444   // fall through to the lhs instead of the rhs block.
2445   if (CB.TrueBB == NextBlock(SwitchBB)) {
2446     std::swap(CB.TrueBB, CB.FalseBB);
2447     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2448     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2449   }
2450 
2451   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2452                                MVT::Other, getControlRoot(), Cond,
2453                                DAG.getBasicBlock(CB.TrueBB));
2454 
2455   // Insert the false branch. Do this even if it's a fall through branch,
2456   // this makes it easier to do DAG optimizations which require inverting
2457   // the branch condition.
2458   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2459                        DAG.getBasicBlock(CB.FalseBB));
2460 
2461   DAG.setRoot(BrCond);
2462 }
2463 
2464 /// visitJumpTable - Emit JumpTable node in the current MBB
2465 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2466   // Emit the code for the jump table
2467   assert(JT.Reg != -1U && "Should lower JT Header first!");
2468   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2469   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2470                                      JT.Reg, PTy);
2471   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2472   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2473                                     MVT::Other, Index.getValue(1),
2474                                     Table, Index);
2475   DAG.setRoot(BrJumpTable);
2476 }
2477 
2478 /// visitJumpTableHeader - This function emits necessary code to produce index
2479 /// in the JumpTable from switch case.
2480 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2481                                                JumpTableHeader &JTH,
2482                                                MachineBasicBlock *SwitchBB) {
2483   SDLoc dl = getCurSDLoc();
2484 
2485   // Subtract the lowest switch case value from the value being switched on.
2486   SDValue SwitchOp = getValue(JTH.SValue);
2487   EVT VT = SwitchOp.getValueType();
2488   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2489                             DAG.getConstant(JTH.First, dl, VT));
2490 
2491   // The SDNode we just created, which holds the value being switched on minus
2492   // the smallest case value, needs to be copied to a virtual register so it
2493   // can be used as an index into the jump table in a subsequent basic block.
2494   // This value may be smaller or larger than the target's pointer type, and
2495   // therefore require extension or truncating.
2496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2497   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2498 
2499   unsigned JumpTableReg =
2500       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2501   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2502                                     JumpTableReg, SwitchOp);
2503   JT.Reg = JumpTableReg;
2504 
2505   if (!JTH.OmitRangeCheck) {
2506     // Emit the range check for the jump table, and branch to the default block
2507     // for the switch statement if the value being switched on exceeds the
2508     // largest case in the switch.
2509     SDValue CMP = DAG.getSetCC(
2510         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2511                                    Sub.getValueType()),
2512         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2513 
2514     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2515                                  MVT::Other, CopyTo, CMP,
2516                                  DAG.getBasicBlock(JT.Default));
2517 
2518     // Avoid emitting unnecessary branches to the next block.
2519     if (JT.MBB != NextBlock(SwitchBB))
2520       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2521                            DAG.getBasicBlock(JT.MBB));
2522 
2523     DAG.setRoot(BrCond);
2524   } else {
2525     // Avoid emitting unnecessary branches to the next block.
2526     if (JT.MBB != NextBlock(SwitchBB))
2527       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2528                               DAG.getBasicBlock(JT.MBB)));
2529     else
2530       DAG.setRoot(CopyTo);
2531   }
2532 }
2533 
2534 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2535 /// variable if there exists one.
2536 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2537                                  SDValue &Chain) {
2538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2539   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2540   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2541   MachineFunction &MF = DAG.getMachineFunction();
2542   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2543   MachineSDNode *Node =
2544       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2545   if (Global) {
2546     MachinePointerInfo MPInfo(Global);
2547     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2548                  MachineMemOperand::MODereferenceable;
2549     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2550         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2551     DAG.setNodeMemRefs(Node, {MemRef});
2552   }
2553   if (PtrTy != PtrMemTy)
2554     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2555   return SDValue(Node, 0);
2556 }
2557 
2558 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2559 /// tail spliced into a stack protector check success bb.
2560 ///
2561 /// For a high level explanation of how this fits into the stack protector
2562 /// generation see the comment on the declaration of class
2563 /// StackProtectorDescriptor.
2564 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2565                                                   MachineBasicBlock *ParentBB) {
2566 
2567   // First create the loads to the guard/stack slot for the comparison.
2568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2569   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2570   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2571 
2572   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2573   int FI = MFI.getStackProtectorIndex();
2574 
2575   SDValue Guard;
2576   SDLoc dl = getCurSDLoc();
2577   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2578   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2579   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2580 
2581   // Generate code to load the content of the guard slot.
2582   SDValue GuardVal = DAG.getLoad(
2583       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2584       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2585       MachineMemOperand::MOVolatile);
2586 
2587   if (TLI.useStackGuardXorFP())
2588     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2589 
2590   // Retrieve guard check function, nullptr if instrumentation is inlined.
2591   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2592     // The target provides a guard check function to validate the guard value.
2593     // Generate a call to that function with the content of the guard slot as
2594     // argument.
2595     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2596     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2597 
2598     TargetLowering::ArgListTy Args;
2599     TargetLowering::ArgListEntry Entry;
2600     Entry.Node = GuardVal;
2601     Entry.Ty = FnTy->getParamType(0);
2602     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2603       Entry.IsInReg = true;
2604     Args.push_back(Entry);
2605 
2606     TargetLowering::CallLoweringInfo CLI(DAG);
2607     CLI.setDebugLoc(getCurSDLoc())
2608         .setChain(DAG.getEntryNode())
2609         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2610                    getValue(GuardCheckFn), std::move(Args));
2611 
2612     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2613     DAG.setRoot(Result.second);
2614     return;
2615   }
2616 
2617   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2618   // Otherwise, emit a volatile load to retrieve the stack guard value.
2619   SDValue Chain = DAG.getEntryNode();
2620   if (TLI.useLoadStackGuardNode()) {
2621     Guard = getLoadStackGuard(DAG, dl, Chain);
2622   } else {
2623     const Value *IRGuard = TLI.getSDagStackGuard(M);
2624     SDValue GuardPtr = getValue(IRGuard);
2625 
2626     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2627                         MachinePointerInfo(IRGuard, 0), Align,
2628                         MachineMemOperand::MOVolatile);
2629   }
2630 
2631   // Perform the comparison via a getsetcc.
2632   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2633                                                         *DAG.getContext(),
2634                                                         Guard.getValueType()),
2635                              Guard, GuardVal, ISD::SETNE);
2636 
2637   // If the guard/stackslot do not equal, branch to failure MBB.
2638   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2639                                MVT::Other, GuardVal.getOperand(0),
2640                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2641   // Otherwise branch to success MBB.
2642   SDValue Br = DAG.getNode(ISD::BR, dl,
2643                            MVT::Other, BrCond,
2644                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2645 
2646   DAG.setRoot(Br);
2647 }
2648 
2649 /// Codegen the failure basic block for a stack protector check.
2650 ///
2651 /// A failure stack protector machine basic block consists simply of a call to
2652 /// __stack_chk_fail().
2653 ///
2654 /// For a high level explanation of how this fits into the stack protector
2655 /// generation see the comment on the declaration of class
2656 /// StackProtectorDescriptor.
2657 void
2658 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2659   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2660   TargetLowering::MakeLibCallOptions CallOptions;
2661   CallOptions.setDiscardResult(true);
2662   SDValue Chain =
2663       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2664                       None, CallOptions, getCurSDLoc()).second;
2665   // On PS4, the "return address" must still be within the calling function,
2666   // even if it's at the very end, so emit an explicit TRAP here.
2667   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2668   if (TM.getTargetTriple().isPS4CPU())
2669     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2670 
2671   DAG.setRoot(Chain);
2672 }
2673 
2674 /// visitBitTestHeader - This function emits necessary code to produce value
2675 /// suitable for "bit tests"
2676 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2677                                              MachineBasicBlock *SwitchBB) {
2678   SDLoc dl = getCurSDLoc();
2679 
2680   // Subtract the minimum value.
2681   SDValue SwitchOp = getValue(B.SValue);
2682   EVT VT = SwitchOp.getValueType();
2683   SDValue RangeSub =
2684       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2685 
2686   // Determine the type of the test operands.
2687   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2688   bool UsePtrType = false;
2689   if (!TLI.isTypeLegal(VT)) {
2690     UsePtrType = true;
2691   } else {
2692     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2693       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2694         // Switch table case range are encoded into series of masks.
2695         // Just use pointer type, it's guaranteed to fit.
2696         UsePtrType = true;
2697         break;
2698       }
2699   }
2700   SDValue Sub = RangeSub;
2701   if (UsePtrType) {
2702     VT = TLI.getPointerTy(DAG.getDataLayout());
2703     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2704   }
2705 
2706   B.RegVT = VT.getSimpleVT();
2707   B.Reg = FuncInfo.CreateReg(B.RegVT);
2708   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2709 
2710   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2711 
2712   if (!B.OmitRangeCheck)
2713     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2714   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2715   SwitchBB->normalizeSuccProbs();
2716 
2717   SDValue Root = CopyTo;
2718   if (!B.OmitRangeCheck) {
2719     // Conditional branch to the default block.
2720     SDValue RangeCmp = DAG.getSetCC(dl,
2721         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2722                                RangeSub.getValueType()),
2723         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2724         ISD::SETUGT);
2725 
2726     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2727                        DAG.getBasicBlock(B.Default));
2728   }
2729 
2730   // Avoid emitting unnecessary branches to the next block.
2731   if (MBB != NextBlock(SwitchBB))
2732     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2733 
2734   DAG.setRoot(Root);
2735 }
2736 
2737 /// visitBitTestCase - this function produces one "bit test"
2738 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2739                                            MachineBasicBlock* NextMBB,
2740                                            BranchProbability BranchProbToNext,
2741                                            unsigned Reg,
2742                                            BitTestCase &B,
2743                                            MachineBasicBlock *SwitchBB) {
2744   SDLoc dl = getCurSDLoc();
2745   MVT VT = BB.RegVT;
2746   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2747   SDValue Cmp;
2748   unsigned PopCount = countPopulation(B.Mask);
2749   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2750   if (PopCount == 1) {
2751     // Testing for a single bit; just compare the shift count with what it
2752     // would need to be to shift a 1 bit in that position.
2753     Cmp = DAG.getSetCC(
2754         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2755         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2756         ISD::SETEQ);
2757   } else if (PopCount == BB.Range) {
2758     // There is only one zero bit in the range, test for it directly.
2759     Cmp = DAG.getSetCC(
2760         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2761         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2762         ISD::SETNE);
2763   } else {
2764     // Make desired shift
2765     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2766                                     DAG.getConstant(1, dl, VT), ShiftOp);
2767 
2768     // Emit bit tests and jumps
2769     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2770                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2771     Cmp = DAG.getSetCC(
2772         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2773         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2774   }
2775 
2776   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2777   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2778   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2779   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2780   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2781   // one as they are relative probabilities (and thus work more like weights),
2782   // and hence we need to normalize them to let the sum of them become one.
2783   SwitchBB->normalizeSuccProbs();
2784 
2785   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2786                               MVT::Other, getControlRoot(),
2787                               Cmp, DAG.getBasicBlock(B.TargetBB));
2788 
2789   // Avoid emitting unnecessary branches to the next block.
2790   if (NextMBB != NextBlock(SwitchBB))
2791     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2792                         DAG.getBasicBlock(NextMBB));
2793 
2794   DAG.setRoot(BrAnd);
2795 }
2796 
2797 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2798   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2799 
2800   // Retrieve successors. Look through artificial IR level blocks like
2801   // catchswitch for successors.
2802   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2803   const BasicBlock *EHPadBB = I.getSuccessor(1);
2804 
2805   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2806   // have to do anything here to lower funclet bundles.
2807   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2808                                         LLVMContext::OB_gc_transition,
2809                                         LLVMContext::OB_gc_live,
2810                                         LLVMContext::OB_funclet,
2811                                         LLVMContext::OB_cfguardtarget}) &&
2812          "Cannot lower invokes with arbitrary operand bundles yet!");
2813 
2814   const Value *Callee(I.getCalledOperand());
2815   const Function *Fn = dyn_cast<Function>(Callee);
2816   if (isa<InlineAsm>(Callee))
2817     visitInlineAsm(I);
2818   else if (Fn && Fn->isIntrinsic()) {
2819     switch (Fn->getIntrinsicID()) {
2820     default:
2821       llvm_unreachable("Cannot invoke this intrinsic");
2822     case Intrinsic::donothing:
2823       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2824       break;
2825     case Intrinsic::experimental_patchpoint_void:
2826     case Intrinsic::experimental_patchpoint_i64:
2827       visitPatchpoint(I, EHPadBB);
2828       break;
2829     case Intrinsic::experimental_gc_statepoint:
2830       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2831       break;
2832     case Intrinsic::wasm_rethrow_in_catch: {
2833       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2834       // special because it can be invoked, so we manually lower it to a DAG
2835       // node here.
2836       SmallVector<SDValue, 8> Ops;
2837       Ops.push_back(getRoot()); // inchain
2838       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2839       Ops.push_back(
2840           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2841                                 TLI.getPointerTy(DAG.getDataLayout())));
2842       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2843       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2844       break;
2845     }
2846     }
2847   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2848     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2849     // Eventually we will support lowering the @llvm.experimental.deoptimize
2850     // intrinsic, and right now there are no plans to support other intrinsics
2851     // with deopt state.
2852     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2853   } else {
2854     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2855   }
2856 
2857   // If the value of the invoke is used outside of its defining block, make it
2858   // available as a virtual register.
2859   // We already took care of the exported value for the statepoint instruction
2860   // during call to the LowerStatepoint.
2861   if (!isa<GCStatepointInst>(I)) {
2862     CopyToExportRegsIfNeeded(&I);
2863   }
2864 
2865   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2866   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2867   BranchProbability EHPadBBProb =
2868       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2869           : BranchProbability::getZero();
2870   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2871 
2872   // Update successor info.
2873   addSuccessorWithProb(InvokeMBB, Return);
2874   for (auto &UnwindDest : UnwindDests) {
2875     UnwindDest.first->setIsEHPad();
2876     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2877   }
2878   InvokeMBB->normalizeSuccProbs();
2879 
2880   // Drop into normal successor.
2881   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2882                           DAG.getBasicBlock(Return)));
2883 }
2884 
2885 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2886   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2887 
2888   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2889   // have to do anything here to lower funclet bundles.
2890   assert(!I.hasOperandBundlesOtherThan(
2891              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2892          "Cannot lower callbrs with arbitrary operand bundles yet!");
2893 
2894   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2895   visitInlineAsm(I);
2896   CopyToExportRegsIfNeeded(&I);
2897 
2898   // Retrieve successors.
2899   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2900 
2901   // Update successor info.
2902   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2903   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2904     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2905     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2906     Target->setIsInlineAsmBrIndirectTarget();
2907   }
2908   CallBrMBB->normalizeSuccProbs();
2909 
2910   // Drop into default successor.
2911   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2912                           MVT::Other, getControlRoot(),
2913                           DAG.getBasicBlock(Return)));
2914 }
2915 
2916 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2917   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2918 }
2919 
2920 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2921   assert(FuncInfo.MBB->isEHPad() &&
2922          "Call to landingpad not in landing pad!");
2923 
2924   // If there aren't registers to copy the values into (e.g., during SjLj
2925   // exceptions), then don't bother to create these DAG nodes.
2926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2927   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2928   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2929       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2930     return;
2931 
2932   // If landingpad's return type is token type, we don't create DAG nodes
2933   // for its exception pointer and selector value. The extraction of exception
2934   // pointer or selector value from token type landingpads is not currently
2935   // supported.
2936   if (LP.getType()->isTokenTy())
2937     return;
2938 
2939   SmallVector<EVT, 2> ValueVTs;
2940   SDLoc dl = getCurSDLoc();
2941   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2942   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2943 
2944   // Get the two live-in registers as SDValues. The physregs have already been
2945   // copied into virtual registers.
2946   SDValue Ops[2];
2947   if (FuncInfo.ExceptionPointerVirtReg) {
2948     Ops[0] = DAG.getZExtOrTrunc(
2949         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2950                            FuncInfo.ExceptionPointerVirtReg,
2951                            TLI.getPointerTy(DAG.getDataLayout())),
2952         dl, ValueVTs[0]);
2953   } else {
2954     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2955   }
2956   Ops[1] = DAG.getZExtOrTrunc(
2957       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2958                          FuncInfo.ExceptionSelectorVirtReg,
2959                          TLI.getPointerTy(DAG.getDataLayout())),
2960       dl, ValueVTs[1]);
2961 
2962   // Merge into one.
2963   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2964                             DAG.getVTList(ValueVTs), Ops);
2965   setValue(&LP, Res);
2966 }
2967 
2968 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2969                                            MachineBasicBlock *Last) {
2970   // Update JTCases.
2971   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2972     if (SL->JTCases[i].first.HeaderBB == First)
2973       SL->JTCases[i].first.HeaderBB = Last;
2974 
2975   // Update BitTestCases.
2976   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2977     if (SL->BitTestCases[i].Parent == First)
2978       SL->BitTestCases[i].Parent = Last;
2979 }
2980 
2981 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2982   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2983 
2984   // Update machine-CFG edges with unique successors.
2985   SmallSet<BasicBlock*, 32> Done;
2986   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2987     BasicBlock *BB = I.getSuccessor(i);
2988     bool Inserted = Done.insert(BB).second;
2989     if (!Inserted)
2990         continue;
2991 
2992     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2993     addSuccessorWithProb(IndirectBrMBB, Succ);
2994   }
2995   IndirectBrMBB->normalizeSuccProbs();
2996 
2997   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2998                           MVT::Other, getControlRoot(),
2999                           getValue(I.getAddress())));
3000 }
3001 
3002 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3003   if (!DAG.getTarget().Options.TrapUnreachable)
3004     return;
3005 
3006   // We may be able to ignore unreachable behind a noreturn call.
3007   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3008     const BasicBlock &BB = *I.getParent();
3009     if (&I != &BB.front()) {
3010       BasicBlock::const_iterator PredI =
3011         std::prev(BasicBlock::const_iterator(&I));
3012       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3013         if (Call->doesNotReturn())
3014           return;
3015       }
3016     }
3017   }
3018 
3019   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3020 }
3021 
3022 void SelectionDAGBuilder::visitFSub(const User &I) {
3023   // -0.0 - X --> fneg
3024   Type *Ty = I.getType();
3025   if (isa<Constant>(I.getOperand(0)) &&
3026       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
3027     SDValue Op2 = getValue(I.getOperand(1));
3028     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
3029                              Op2.getValueType(), Op2));
3030     return;
3031   }
3032 
3033   visitBinary(I, ISD::FSUB);
3034 }
3035 
3036 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3037   SDNodeFlags Flags;
3038 
3039   SDValue Op = getValue(I.getOperand(0));
3040   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3041                                     Op, Flags);
3042   setValue(&I, UnNodeValue);
3043 }
3044 
3045 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3046   SDNodeFlags Flags;
3047   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3048     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3049     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3050   }
3051   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3052     Flags.setExact(ExactOp->isExact());
3053   }
3054 
3055   SDValue Op1 = getValue(I.getOperand(0));
3056   SDValue Op2 = getValue(I.getOperand(1));
3057   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3058                                      Op1, Op2, Flags);
3059   setValue(&I, BinNodeValue);
3060 }
3061 
3062 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3063   SDValue Op1 = getValue(I.getOperand(0));
3064   SDValue Op2 = getValue(I.getOperand(1));
3065 
3066   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3067       Op1.getValueType(), DAG.getDataLayout());
3068 
3069   // Coerce the shift amount to the right type if we can.
3070   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3071     unsigned ShiftSize = ShiftTy.getSizeInBits();
3072     unsigned Op2Size = Op2.getValueSizeInBits();
3073     SDLoc DL = getCurSDLoc();
3074 
3075     // If the operand is smaller than the shift count type, promote it.
3076     if (ShiftSize > Op2Size)
3077       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3078 
3079     // If the operand is larger than the shift count type but the shift
3080     // count type has enough bits to represent any shift value, truncate
3081     // it now. This is a common case and it exposes the truncate to
3082     // optimization early.
3083     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3084       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3085     // Otherwise we'll need to temporarily settle for some other convenient
3086     // type.  Type legalization will make adjustments once the shiftee is split.
3087     else
3088       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3089   }
3090 
3091   bool nuw = false;
3092   bool nsw = false;
3093   bool exact = false;
3094 
3095   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3096 
3097     if (const OverflowingBinaryOperator *OFBinOp =
3098             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3099       nuw = OFBinOp->hasNoUnsignedWrap();
3100       nsw = OFBinOp->hasNoSignedWrap();
3101     }
3102     if (const PossiblyExactOperator *ExactOp =
3103             dyn_cast<const PossiblyExactOperator>(&I))
3104       exact = ExactOp->isExact();
3105   }
3106   SDNodeFlags Flags;
3107   Flags.setExact(exact);
3108   Flags.setNoSignedWrap(nsw);
3109   Flags.setNoUnsignedWrap(nuw);
3110   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3111                             Flags);
3112   setValue(&I, Res);
3113 }
3114 
3115 void SelectionDAGBuilder::visitSDiv(const User &I) {
3116   SDValue Op1 = getValue(I.getOperand(0));
3117   SDValue Op2 = getValue(I.getOperand(1));
3118 
3119   SDNodeFlags Flags;
3120   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3121                  cast<PossiblyExactOperator>(&I)->isExact());
3122   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3123                            Op2, Flags));
3124 }
3125 
3126 void SelectionDAGBuilder::visitICmp(const User &I) {
3127   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3128   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3129     predicate = IC->getPredicate();
3130   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3131     predicate = ICmpInst::Predicate(IC->getPredicate());
3132   SDValue Op1 = getValue(I.getOperand(0));
3133   SDValue Op2 = getValue(I.getOperand(1));
3134   ISD::CondCode Opcode = getICmpCondCode(predicate);
3135 
3136   auto &TLI = DAG.getTargetLoweringInfo();
3137   EVT MemVT =
3138       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3139 
3140   // If a pointer's DAG type is larger than its memory type then the DAG values
3141   // are zero-extended. This breaks signed comparisons so truncate back to the
3142   // underlying type before doing the compare.
3143   if (Op1.getValueType() != MemVT) {
3144     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3145     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3146   }
3147 
3148   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3149                                                         I.getType());
3150   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3151 }
3152 
3153 void SelectionDAGBuilder::visitFCmp(const User &I) {
3154   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3155   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3156     predicate = FC->getPredicate();
3157   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3158     predicate = FCmpInst::Predicate(FC->getPredicate());
3159   SDValue Op1 = getValue(I.getOperand(0));
3160   SDValue Op2 = getValue(I.getOperand(1));
3161 
3162   ISD::CondCode Condition = getFCmpCondCode(predicate);
3163   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3164   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3165     Condition = getFCmpCodeWithoutNaN(Condition);
3166 
3167   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3168                                                         I.getType());
3169   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3170 }
3171 
3172 // Check if the condition of the select has one use or two users that are both
3173 // selects with the same condition.
3174 static bool hasOnlySelectUsers(const Value *Cond) {
3175   return llvm::all_of(Cond->users(), [](const Value *V) {
3176     return isa<SelectInst>(V);
3177   });
3178 }
3179 
3180 void SelectionDAGBuilder::visitSelect(const User &I) {
3181   SmallVector<EVT, 4> ValueVTs;
3182   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3183                   ValueVTs);
3184   unsigned NumValues = ValueVTs.size();
3185   if (NumValues == 0) return;
3186 
3187   SmallVector<SDValue, 4> Values(NumValues);
3188   SDValue Cond     = getValue(I.getOperand(0));
3189   SDValue LHSVal   = getValue(I.getOperand(1));
3190   SDValue RHSVal   = getValue(I.getOperand(2));
3191   SmallVector<SDValue, 1> BaseOps(1, Cond);
3192   ISD::NodeType OpCode =
3193       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3194 
3195   bool IsUnaryAbs = false;
3196 
3197   // Min/max matching is only viable if all output VTs are the same.
3198   if (is_splat(ValueVTs)) {
3199     EVT VT = ValueVTs[0];
3200     LLVMContext &Ctx = *DAG.getContext();
3201     auto &TLI = DAG.getTargetLoweringInfo();
3202 
3203     // We care about the legality of the operation after it has been type
3204     // legalized.
3205     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3206       VT = TLI.getTypeToTransformTo(Ctx, VT);
3207 
3208     // If the vselect is legal, assume we want to leave this as a vector setcc +
3209     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3210     // min/max is legal on the scalar type.
3211     bool UseScalarMinMax = VT.isVector() &&
3212       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3213 
3214     Value *LHS, *RHS;
3215     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3216     ISD::NodeType Opc = ISD::DELETED_NODE;
3217     switch (SPR.Flavor) {
3218     case SPF_UMAX:    Opc = ISD::UMAX; break;
3219     case SPF_UMIN:    Opc = ISD::UMIN; break;
3220     case SPF_SMAX:    Opc = ISD::SMAX; break;
3221     case SPF_SMIN:    Opc = ISD::SMIN; break;
3222     case SPF_FMINNUM:
3223       switch (SPR.NaNBehavior) {
3224       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3225       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3226       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3227       case SPNB_RETURNS_ANY: {
3228         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3229           Opc = ISD::FMINNUM;
3230         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3231           Opc = ISD::FMINIMUM;
3232         else if (UseScalarMinMax)
3233           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3234             ISD::FMINNUM : ISD::FMINIMUM;
3235         break;
3236       }
3237       }
3238       break;
3239     case SPF_FMAXNUM:
3240       switch (SPR.NaNBehavior) {
3241       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3242       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3243       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3244       case SPNB_RETURNS_ANY:
3245 
3246         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3247           Opc = ISD::FMAXNUM;
3248         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3249           Opc = ISD::FMAXIMUM;
3250         else if (UseScalarMinMax)
3251           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3252             ISD::FMAXNUM : ISD::FMAXIMUM;
3253         break;
3254       }
3255       break;
3256     case SPF_ABS:
3257       IsUnaryAbs = true;
3258       Opc = ISD::ABS;
3259       break;
3260     case SPF_NABS:
3261       // TODO: we need to produce sub(0, abs(X)).
3262     default: break;
3263     }
3264 
3265     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3266         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3267          (UseScalarMinMax &&
3268           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3269         // If the underlying comparison instruction is used by any other
3270         // instruction, the consumed instructions won't be destroyed, so it is
3271         // not profitable to convert to a min/max.
3272         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3273       OpCode = Opc;
3274       LHSVal = getValue(LHS);
3275       RHSVal = getValue(RHS);
3276       BaseOps.clear();
3277     }
3278 
3279     if (IsUnaryAbs) {
3280       OpCode = Opc;
3281       LHSVal = getValue(LHS);
3282       BaseOps.clear();
3283     }
3284   }
3285 
3286   if (IsUnaryAbs) {
3287     for (unsigned i = 0; i != NumValues; ++i) {
3288       Values[i] =
3289           DAG.getNode(OpCode, getCurSDLoc(),
3290                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3291                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3292     }
3293   } else {
3294     for (unsigned i = 0; i != NumValues; ++i) {
3295       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3296       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3297       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3298       Values[i] = DAG.getNode(
3299           OpCode, getCurSDLoc(),
3300           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3301     }
3302   }
3303 
3304   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3305                            DAG.getVTList(ValueVTs), Values));
3306 }
3307 
3308 void SelectionDAGBuilder::visitTrunc(const User &I) {
3309   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3310   SDValue N = getValue(I.getOperand(0));
3311   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3312                                                         I.getType());
3313   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3314 }
3315 
3316 void SelectionDAGBuilder::visitZExt(const User &I) {
3317   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3318   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3319   SDValue N = getValue(I.getOperand(0));
3320   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3321                                                         I.getType());
3322   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3323 }
3324 
3325 void SelectionDAGBuilder::visitSExt(const User &I) {
3326   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3327   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3328   SDValue N = getValue(I.getOperand(0));
3329   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3330                                                         I.getType());
3331   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3332 }
3333 
3334 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3335   // FPTrunc is never a no-op cast, no need to check
3336   SDValue N = getValue(I.getOperand(0));
3337   SDLoc dl = getCurSDLoc();
3338   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3339   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3340   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3341                            DAG.getTargetConstant(
3342                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3343 }
3344 
3345 void SelectionDAGBuilder::visitFPExt(const User &I) {
3346   // FPExt is never a no-op cast, no need to check
3347   SDValue N = getValue(I.getOperand(0));
3348   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3349                                                         I.getType());
3350   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3351 }
3352 
3353 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3354   // FPToUI is never a no-op cast, no need to check
3355   SDValue N = getValue(I.getOperand(0));
3356   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3357                                                         I.getType());
3358   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3359 }
3360 
3361 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3362   // FPToSI is never a no-op cast, no need to check
3363   SDValue N = getValue(I.getOperand(0));
3364   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3365                                                         I.getType());
3366   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3367 }
3368 
3369 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3370   // UIToFP is never a no-op cast, no need to check
3371   SDValue N = getValue(I.getOperand(0));
3372   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3373                                                         I.getType());
3374   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3375 }
3376 
3377 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3378   // SIToFP is never a no-op cast, no need to check
3379   SDValue N = getValue(I.getOperand(0));
3380   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3381                                                         I.getType());
3382   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3383 }
3384 
3385 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3386   // What to do depends on the size of the integer and the size of the pointer.
3387   // We can either truncate, zero extend, or no-op, accordingly.
3388   SDValue N = getValue(I.getOperand(0));
3389   auto &TLI = DAG.getTargetLoweringInfo();
3390   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3391                                                         I.getType());
3392   EVT PtrMemVT =
3393       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3394   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3395   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3396   setValue(&I, N);
3397 }
3398 
3399 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3400   // What to do depends on the size of the integer and the size of the pointer.
3401   // We can either truncate, zero extend, or no-op, accordingly.
3402   SDValue N = getValue(I.getOperand(0));
3403   auto &TLI = DAG.getTargetLoweringInfo();
3404   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3405   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3406   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3407   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3408   setValue(&I, N);
3409 }
3410 
3411 void SelectionDAGBuilder::visitBitCast(const User &I) {
3412   SDValue N = getValue(I.getOperand(0));
3413   SDLoc dl = getCurSDLoc();
3414   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3415                                                         I.getType());
3416 
3417   // BitCast assures us that source and destination are the same size so this is
3418   // either a BITCAST or a no-op.
3419   if (DestVT != N.getValueType())
3420     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3421                              DestVT, N)); // convert types.
3422   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3423   // might fold any kind of constant expression to an integer constant and that
3424   // is not what we are looking for. Only recognize a bitcast of a genuine
3425   // constant integer as an opaque constant.
3426   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3427     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3428                                  /*isOpaque*/true));
3429   else
3430     setValue(&I, N);            // noop cast.
3431 }
3432 
3433 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3435   const Value *SV = I.getOperand(0);
3436   SDValue N = getValue(SV);
3437   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3438 
3439   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3440   unsigned DestAS = I.getType()->getPointerAddressSpace();
3441 
3442   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3443     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3444 
3445   setValue(&I, N);
3446 }
3447 
3448 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3450   SDValue InVec = getValue(I.getOperand(0));
3451   SDValue InVal = getValue(I.getOperand(1));
3452   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3453                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3454   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3455                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3456                            InVec, InVal, InIdx));
3457 }
3458 
3459 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3460   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3461   SDValue InVec = getValue(I.getOperand(0));
3462   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3463                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3464   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3465                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3466                            InVec, InIdx));
3467 }
3468 
3469 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3470   SDValue Src1 = getValue(I.getOperand(0));
3471   SDValue Src2 = getValue(I.getOperand(1));
3472   ArrayRef<int> Mask;
3473   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3474     Mask = SVI->getShuffleMask();
3475   else
3476     Mask = cast<ConstantExpr>(I).getShuffleMask();
3477   SDLoc DL = getCurSDLoc();
3478   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3479   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3480   EVT SrcVT = Src1.getValueType();
3481 
3482   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3483       VT.isScalableVector()) {
3484     // Canonical splat form of first element of first input vector.
3485     SDValue FirstElt =
3486         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3487                     DAG.getVectorIdxConstant(0, DL));
3488     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3489     return;
3490   }
3491 
3492   // For now, we only handle splats for scalable vectors.
3493   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3494   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3495   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3496 
3497   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3498   unsigned MaskNumElts = Mask.size();
3499 
3500   if (SrcNumElts == MaskNumElts) {
3501     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3502     return;
3503   }
3504 
3505   // Normalize the shuffle vector since mask and vector length don't match.
3506   if (SrcNumElts < MaskNumElts) {
3507     // Mask is longer than the source vectors. We can use concatenate vector to
3508     // make the mask and vectors lengths match.
3509 
3510     if (MaskNumElts % SrcNumElts == 0) {
3511       // Mask length is a multiple of the source vector length.
3512       // Check if the shuffle is some kind of concatenation of the input
3513       // vectors.
3514       unsigned NumConcat = MaskNumElts / SrcNumElts;
3515       bool IsConcat = true;
3516       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3517       for (unsigned i = 0; i != MaskNumElts; ++i) {
3518         int Idx = Mask[i];
3519         if (Idx < 0)
3520           continue;
3521         // Ensure the indices in each SrcVT sized piece are sequential and that
3522         // the same source is used for the whole piece.
3523         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3524             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3525              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3526           IsConcat = false;
3527           break;
3528         }
3529         // Remember which source this index came from.
3530         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3531       }
3532 
3533       // The shuffle is concatenating multiple vectors together. Just emit
3534       // a CONCAT_VECTORS operation.
3535       if (IsConcat) {
3536         SmallVector<SDValue, 8> ConcatOps;
3537         for (auto Src : ConcatSrcs) {
3538           if (Src < 0)
3539             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3540           else if (Src == 0)
3541             ConcatOps.push_back(Src1);
3542           else
3543             ConcatOps.push_back(Src2);
3544         }
3545         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3546         return;
3547       }
3548     }
3549 
3550     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3551     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3552     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3553                                     PaddedMaskNumElts);
3554 
3555     // Pad both vectors with undefs to make them the same length as the mask.
3556     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3557 
3558     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3559     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3560     MOps1[0] = Src1;
3561     MOps2[0] = Src2;
3562 
3563     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3564     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3565 
3566     // Readjust mask for new input vector length.
3567     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3568     for (unsigned i = 0; i != MaskNumElts; ++i) {
3569       int Idx = Mask[i];
3570       if (Idx >= (int)SrcNumElts)
3571         Idx -= SrcNumElts - PaddedMaskNumElts;
3572       MappedOps[i] = Idx;
3573     }
3574 
3575     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3576 
3577     // If the concatenated vector was padded, extract a subvector with the
3578     // correct number of elements.
3579     if (MaskNumElts != PaddedMaskNumElts)
3580       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3581                            DAG.getVectorIdxConstant(0, DL));
3582 
3583     setValue(&I, Result);
3584     return;
3585   }
3586 
3587   if (SrcNumElts > MaskNumElts) {
3588     // Analyze the access pattern of the vector to see if we can extract
3589     // two subvectors and do the shuffle.
3590     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3591     bool CanExtract = true;
3592     for (int Idx : Mask) {
3593       unsigned Input = 0;
3594       if (Idx < 0)
3595         continue;
3596 
3597       if (Idx >= (int)SrcNumElts) {
3598         Input = 1;
3599         Idx -= SrcNumElts;
3600       }
3601 
3602       // If all the indices come from the same MaskNumElts sized portion of
3603       // the sources we can use extract. Also make sure the extract wouldn't
3604       // extract past the end of the source.
3605       int NewStartIdx = alignDown(Idx, MaskNumElts);
3606       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3607           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3608         CanExtract = false;
3609       // Make sure we always update StartIdx as we use it to track if all
3610       // elements are undef.
3611       StartIdx[Input] = NewStartIdx;
3612     }
3613 
3614     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3615       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3616       return;
3617     }
3618     if (CanExtract) {
3619       // Extract appropriate subvector and generate a vector shuffle
3620       for (unsigned Input = 0; Input < 2; ++Input) {
3621         SDValue &Src = Input == 0 ? Src1 : Src2;
3622         if (StartIdx[Input] < 0)
3623           Src = DAG.getUNDEF(VT);
3624         else {
3625           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3626                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3627         }
3628       }
3629 
3630       // Calculate new mask.
3631       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3632       for (int &Idx : MappedOps) {
3633         if (Idx >= (int)SrcNumElts)
3634           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3635         else if (Idx >= 0)
3636           Idx -= StartIdx[0];
3637       }
3638 
3639       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3640       return;
3641     }
3642   }
3643 
3644   // We can't use either concat vectors or extract subvectors so fall back to
3645   // replacing the shuffle with extract and build vector.
3646   // to insert and build vector.
3647   EVT EltVT = VT.getVectorElementType();
3648   SmallVector<SDValue,8> Ops;
3649   for (int Idx : Mask) {
3650     SDValue Res;
3651 
3652     if (Idx < 0) {
3653       Res = DAG.getUNDEF(EltVT);
3654     } else {
3655       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3656       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3657 
3658       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3659                         DAG.getVectorIdxConstant(Idx, DL));
3660     }
3661 
3662     Ops.push_back(Res);
3663   }
3664 
3665   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3666 }
3667 
3668 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3669   ArrayRef<unsigned> Indices;
3670   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3671     Indices = IV->getIndices();
3672   else
3673     Indices = cast<ConstantExpr>(&I)->getIndices();
3674 
3675   const Value *Op0 = I.getOperand(0);
3676   const Value *Op1 = I.getOperand(1);
3677   Type *AggTy = I.getType();
3678   Type *ValTy = Op1->getType();
3679   bool IntoUndef = isa<UndefValue>(Op0);
3680   bool FromUndef = isa<UndefValue>(Op1);
3681 
3682   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3683 
3684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3685   SmallVector<EVT, 4> AggValueVTs;
3686   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3687   SmallVector<EVT, 4> ValValueVTs;
3688   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3689 
3690   unsigned NumAggValues = AggValueVTs.size();
3691   unsigned NumValValues = ValValueVTs.size();
3692   SmallVector<SDValue, 4> Values(NumAggValues);
3693 
3694   // Ignore an insertvalue that produces an empty object
3695   if (!NumAggValues) {
3696     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3697     return;
3698   }
3699 
3700   SDValue Agg = getValue(Op0);
3701   unsigned i = 0;
3702   // Copy the beginning value(s) from the original aggregate.
3703   for (; i != LinearIndex; ++i)
3704     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3705                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3706   // Copy values from the inserted value(s).
3707   if (NumValValues) {
3708     SDValue Val = getValue(Op1);
3709     for (; i != LinearIndex + NumValValues; ++i)
3710       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3711                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3712   }
3713   // Copy remaining value(s) from the original aggregate.
3714   for (; i != NumAggValues; ++i)
3715     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3716                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3717 
3718   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3719                            DAG.getVTList(AggValueVTs), Values));
3720 }
3721 
3722 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3723   ArrayRef<unsigned> Indices;
3724   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3725     Indices = EV->getIndices();
3726   else
3727     Indices = cast<ConstantExpr>(&I)->getIndices();
3728 
3729   const Value *Op0 = I.getOperand(0);
3730   Type *AggTy = Op0->getType();
3731   Type *ValTy = I.getType();
3732   bool OutOfUndef = isa<UndefValue>(Op0);
3733 
3734   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3735 
3736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3737   SmallVector<EVT, 4> ValValueVTs;
3738   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3739 
3740   unsigned NumValValues = ValValueVTs.size();
3741 
3742   // Ignore a extractvalue that produces an empty object
3743   if (!NumValValues) {
3744     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3745     return;
3746   }
3747 
3748   SmallVector<SDValue, 4> Values(NumValValues);
3749 
3750   SDValue Agg = getValue(Op0);
3751   // Copy out the selected value(s).
3752   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3753     Values[i - LinearIndex] =
3754       OutOfUndef ?
3755         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3756         SDValue(Agg.getNode(), Agg.getResNo() + i);
3757 
3758   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3759                            DAG.getVTList(ValValueVTs), Values));
3760 }
3761 
3762 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3763   Value *Op0 = I.getOperand(0);
3764   // Note that the pointer operand may be a vector of pointers. Take the scalar
3765   // element which holds a pointer.
3766   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3767   SDValue N = getValue(Op0);
3768   SDLoc dl = getCurSDLoc();
3769   auto &TLI = DAG.getTargetLoweringInfo();
3770   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3771   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3772 
3773   // Normalize Vector GEP - all scalar operands should be converted to the
3774   // splat vector.
3775   bool IsVectorGEP = I.getType()->isVectorTy();
3776   ElementCount VectorElementCount =
3777       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3778                   : ElementCount(0, false);
3779 
3780   if (IsVectorGEP && !N.getValueType().isVector()) {
3781     LLVMContext &Context = *DAG.getContext();
3782     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3783     if (VectorElementCount.Scalable)
3784       N = DAG.getSplatVector(VT, dl, N);
3785     else
3786       N = DAG.getSplatBuildVector(VT, dl, N);
3787   }
3788 
3789   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3790        GTI != E; ++GTI) {
3791     const Value *Idx = GTI.getOperand();
3792     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3793       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3794       if (Field) {
3795         // N = N + Offset
3796         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3797 
3798         // In an inbounds GEP with an offset that is nonnegative even when
3799         // interpreted as signed, assume there is no unsigned overflow.
3800         SDNodeFlags Flags;
3801         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3802           Flags.setNoUnsignedWrap(true);
3803 
3804         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3805                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3806       }
3807     } else {
3808       // IdxSize is the width of the arithmetic according to IR semantics.
3809       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3810       // (and fix up the result later).
3811       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3812       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3813       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3814       // We intentionally mask away the high bits here; ElementSize may not
3815       // fit in IdxTy.
3816       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3817       bool ElementScalable = ElementSize.isScalable();
3818 
3819       // If this is a scalar constant or a splat vector of constants,
3820       // handle it quickly.
3821       const auto *C = dyn_cast<Constant>(Idx);
3822       if (C && isa<VectorType>(C->getType()))
3823         C = C->getSplatValue();
3824 
3825       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3826       if (CI && CI->isZero())
3827         continue;
3828       if (CI && !ElementScalable) {
3829         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3830         LLVMContext &Context = *DAG.getContext();
3831         SDValue OffsVal;
3832         if (IsVectorGEP)
3833           OffsVal = DAG.getConstant(
3834               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3835         else
3836           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3837 
3838         // In an inbounds GEP with an offset that is nonnegative even when
3839         // interpreted as signed, assume there is no unsigned overflow.
3840         SDNodeFlags Flags;
3841         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3842           Flags.setNoUnsignedWrap(true);
3843 
3844         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3845 
3846         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3847         continue;
3848       }
3849 
3850       // N = N + Idx * ElementMul;
3851       SDValue IdxN = getValue(Idx);
3852 
3853       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3854         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3855                                   VectorElementCount);
3856         if (VectorElementCount.Scalable)
3857           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3858         else
3859           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3860       }
3861 
3862       // If the index is smaller or larger than intptr_t, truncate or extend
3863       // it.
3864       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3865 
3866       if (ElementScalable) {
3867         EVT VScaleTy = N.getValueType().getScalarType();
3868         SDValue VScale = DAG.getNode(
3869             ISD::VSCALE, dl, VScaleTy,
3870             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3871         if (IsVectorGEP)
3872           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3873         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3874       } else {
3875         // If this is a multiply by a power of two, turn it into a shl
3876         // immediately.  This is a very common case.
3877         if (ElementMul != 1) {
3878           if (ElementMul.isPowerOf2()) {
3879             unsigned Amt = ElementMul.logBase2();
3880             IdxN = DAG.getNode(ISD::SHL, dl,
3881                                N.getValueType(), IdxN,
3882                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3883           } else {
3884             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3885                                             IdxN.getValueType());
3886             IdxN = DAG.getNode(ISD::MUL, dl,
3887                                N.getValueType(), IdxN, Scale);
3888           }
3889         }
3890       }
3891 
3892       N = DAG.getNode(ISD::ADD, dl,
3893                       N.getValueType(), N, IdxN);
3894     }
3895   }
3896 
3897   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3898     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3899 
3900   setValue(&I, N);
3901 }
3902 
3903 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3904   // If this is a fixed sized alloca in the entry block of the function,
3905   // allocate it statically on the stack.
3906   if (FuncInfo.StaticAllocaMap.count(&I))
3907     return;   // getValue will auto-populate this.
3908 
3909   SDLoc dl = getCurSDLoc();
3910   Type *Ty = I.getAllocatedType();
3911   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3912   auto &DL = DAG.getDataLayout();
3913   uint64_t TySize = DL.getTypeAllocSize(Ty);
3914   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3915 
3916   SDValue AllocSize = getValue(I.getArraySize());
3917 
3918   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3919   if (AllocSize.getValueType() != IntPtr)
3920     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3921 
3922   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3923                           AllocSize,
3924                           DAG.getConstant(TySize, dl, IntPtr));
3925 
3926   // Handle alignment.  If the requested alignment is less than or equal to
3927   // the stack alignment, ignore it.  If the size is greater than or equal to
3928   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3929   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3930   if (*Alignment <= StackAlign)
3931     Alignment = None;
3932 
3933   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3934   // Round the size of the allocation up to the stack alignment size
3935   // by add SA-1 to the size. This doesn't overflow because we're computing
3936   // an address inside an alloca.
3937   SDNodeFlags Flags;
3938   Flags.setNoUnsignedWrap(true);
3939   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3940                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3941 
3942   // Mask out the low bits for alignment purposes.
3943   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3944                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3945 
3946   SDValue Ops[] = {
3947       getRoot(), AllocSize,
3948       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3949   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3950   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3951   setValue(&I, DSA);
3952   DAG.setRoot(DSA.getValue(1));
3953 
3954   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3955 }
3956 
3957 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3958   if (I.isAtomic())
3959     return visitAtomicLoad(I);
3960 
3961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3962   const Value *SV = I.getOperand(0);
3963   if (TLI.supportSwiftError()) {
3964     // Swifterror values can come from either a function parameter with
3965     // swifterror attribute or an alloca with swifterror attribute.
3966     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3967       if (Arg->hasSwiftErrorAttr())
3968         return visitLoadFromSwiftError(I);
3969     }
3970 
3971     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3972       if (Alloca->isSwiftError())
3973         return visitLoadFromSwiftError(I);
3974     }
3975   }
3976 
3977   SDValue Ptr = getValue(SV);
3978 
3979   Type *Ty = I.getType();
3980   Align Alignment = I.getAlign();
3981 
3982   AAMDNodes AAInfo;
3983   I.getAAMetadata(AAInfo);
3984   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3985 
3986   SmallVector<EVT, 4> ValueVTs, MemVTs;
3987   SmallVector<uint64_t, 4> Offsets;
3988   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3989   unsigned NumValues = ValueVTs.size();
3990   if (NumValues == 0)
3991     return;
3992 
3993   bool isVolatile = I.isVolatile();
3994 
3995   SDValue Root;
3996   bool ConstantMemory = false;
3997   if (isVolatile)
3998     // Serialize volatile loads with other side effects.
3999     Root = getRoot();
4000   else if (NumValues > MaxParallelChains)
4001     Root = getMemoryRoot();
4002   else if (AA &&
4003            AA->pointsToConstantMemory(MemoryLocation(
4004                SV,
4005                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4006                AAInfo))) {
4007     // Do not serialize (non-volatile) loads of constant memory with anything.
4008     Root = DAG.getEntryNode();
4009     ConstantMemory = true;
4010   } else {
4011     // Do not serialize non-volatile loads against each other.
4012     Root = DAG.getRoot();
4013   }
4014 
4015   SDLoc dl = getCurSDLoc();
4016 
4017   if (isVolatile)
4018     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4019 
4020   // An aggregate load cannot wrap around the address space, so offsets to its
4021   // parts don't wrap either.
4022   SDNodeFlags Flags;
4023   Flags.setNoUnsignedWrap(true);
4024 
4025   SmallVector<SDValue, 4> Values(NumValues);
4026   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4027   EVT PtrVT = Ptr.getValueType();
4028 
4029   MachineMemOperand::Flags MMOFlags
4030     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4031 
4032   unsigned ChainI = 0;
4033   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4034     // Serializing loads here may result in excessive register pressure, and
4035     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4036     // could recover a bit by hoisting nodes upward in the chain by recognizing
4037     // they are side-effect free or do not alias. The optimizer should really
4038     // avoid this case by converting large object/array copies to llvm.memcpy
4039     // (MaxParallelChains should always remain as failsafe).
4040     if (ChainI == MaxParallelChains) {
4041       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4042       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4043                                   makeArrayRef(Chains.data(), ChainI));
4044       Root = Chain;
4045       ChainI = 0;
4046     }
4047     SDValue A = DAG.getNode(ISD::ADD, dl,
4048                             PtrVT, Ptr,
4049                             DAG.getConstant(Offsets[i], dl, PtrVT),
4050                             Flags);
4051 
4052     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4053                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4054                             MMOFlags, AAInfo, Ranges);
4055     Chains[ChainI] = L.getValue(1);
4056 
4057     if (MemVTs[i] != ValueVTs[i])
4058       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4059 
4060     Values[i] = L;
4061   }
4062 
4063   if (!ConstantMemory) {
4064     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4065                                 makeArrayRef(Chains.data(), ChainI));
4066     if (isVolatile)
4067       DAG.setRoot(Chain);
4068     else
4069       PendingLoads.push_back(Chain);
4070   }
4071 
4072   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4073                            DAG.getVTList(ValueVTs), Values));
4074 }
4075 
4076 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4077   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4078          "call visitStoreToSwiftError when backend supports swifterror");
4079 
4080   SmallVector<EVT, 4> ValueVTs;
4081   SmallVector<uint64_t, 4> Offsets;
4082   const Value *SrcV = I.getOperand(0);
4083   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4084                   SrcV->getType(), ValueVTs, &Offsets);
4085   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4086          "expect a single EVT for swifterror");
4087 
4088   SDValue Src = getValue(SrcV);
4089   // Create a virtual register, then update the virtual register.
4090   Register VReg =
4091       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4092   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4093   // Chain can be getRoot or getControlRoot.
4094   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4095                                       SDValue(Src.getNode(), Src.getResNo()));
4096   DAG.setRoot(CopyNode);
4097 }
4098 
4099 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4100   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4101          "call visitLoadFromSwiftError when backend supports swifterror");
4102 
4103   assert(!I.isVolatile() &&
4104          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4105          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4106          "Support volatile, non temporal, invariant for load_from_swift_error");
4107 
4108   const Value *SV = I.getOperand(0);
4109   Type *Ty = I.getType();
4110   AAMDNodes AAInfo;
4111   I.getAAMetadata(AAInfo);
4112   assert(
4113       (!AA ||
4114        !AA->pointsToConstantMemory(MemoryLocation(
4115            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4116            AAInfo))) &&
4117       "load_from_swift_error should not be constant memory");
4118 
4119   SmallVector<EVT, 4> ValueVTs;
4120   SmallVector<uint64_t, 4> Offsets;
4121   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4122                   ValueVTs, &Offsets);
4123   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4124          "expect a single EVT for swifterror");
4125 
4126   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4127   SDValue L = DAG.getCopyFromReg(
4128       getRoot(), getCurSDLoc(),
4129       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4130 
4131   setValue(&I, L);
4132 }
4133 
4134 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4135   if (I.isAtomic())
4136     return visitAtomicStore(I);
4137 
4138   const Value *SrcV = I.getOperand(0);
4139   const Value *PtrV = I.getOperand(1);
4140 
4141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4142   if (TLI.supportSwiftError()) {
4143     // Swifterror values can come from either a function parameter with
4144     // swifterror attribute or an alloca with swifterror attribute.
4145     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4146       if (Arg->hasSwiftErrorAttr())
4147         return visitStoreToSwiftError(I);
4148     }
4149 
4150     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4151       if (Alloca->isSwiftError())
4152         return visitStoreToSwiftError(I);
4153     }
4154   }
4155 
4156   SmallVector<EVT, 4> ValueVTs, MemVTs;
4157   SmallVector<uint64_t, 4> Offsets;
4158   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4159                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4160   unsigned NumValues = ValueVTs.size();
4161   if (NumValues == 0)
4162     return;
4163 
4164   // Get the lowered operands. Note that we do this after
4165   // checking if NumResults is zero, because with zero results
4166   // the operands won't have values in the map.
4167   SDValue Src = getValue(SrcV);
4168   SDValue Ptr = getValue(PtrV);
4169 
4170   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4171   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4172   SDLoc dl = getCurSDLoc();
4173   Align Alignment = I.getAlign();
4174   AAMDNodes AAInfo;
4175   I.getAAMetadata(AAInfo);
4176 
4177   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4178 
4179   // An aggregate load cannot wrap around the address space, so offsets to its
4180   // parts don't wrap either.
4181   SDNodeFlags Flags;
4182   Flags.setNoUnsignedWrap(true);
4183 
4184   unsigned ChainI = 0;
4185   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4186     // See visitLoad comments.
4187     if (ChainI == MaxParallelChains) {
4188       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4189                                   makeArrayRef(Chains.data(), ChainI));
4190       Root = Chain;
4191       ChainI = 0;
4192     }
4193     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4194     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4195     if (MemVTs[i] != ValueVTs[i])
4196       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4197     SDValue St =
4198         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4199                      Alignment, MMOFlags, AAInfo);
4200     Chains[ChainI] = St;
4201   }
4202 
4203   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4204                                   makeArrayRef(Chains.data(), ChainI));
4205   DAG.setRoot(StoreNode);
4206 }
4207 
4208 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4209                                            bool IsCompressing) {
4210   SDLoc sdl = getCurSDLoc();
4211 
4212   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4213                                MaybeAlign &Alignment) {
4214     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4215     Src0 = I.getArgOperand(0);
4216     Ptr = I.getArgOperand(1);
4217     Alignment =
4218         MaybeAlign(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4219     Mask = I.getArgOperand(3);
4220   };
4221   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4222                                     MaybeAlign &Alignment) {
4223     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4224     Src0 = I.getArgOperand(0);
4225     Ptr = I.getArgOperand(1);
4226     Mask = I.getArgOperand(2);
4227     Alignment = None;
4228   };
4229 
4230   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4231   MaybeAlign Alignment;
4232   if (IsCompressing)
4233     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4234   else
4235     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4236 
4237   SDValue Ptr = getValue(PtrOperand);
4238   SDValue Src0 = getValue(Src0Operand);
4239   SDValue Mask = getValue(MaskOperand);
4240   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4241 
4242   EVT VT = Src0.getValueType();
4243   if (!Alignment)
4244     Alignment = DAG.getEVTAlign(VT);
4245 
4246   AAMDNodes AAInfo;
4247   I.getAAMetadata(AAInfo);
4248 
4249   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4250       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4251       // TODO: Make MachineMemOperands aware of scalable
4252       // vectors.
4253       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4254   SDValue StoreNode =
4255       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4256                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4257   DAG.setRoot(StoreNode);
4258   setValue(&I, StoreNode);
4259 }
4260 
4261 // Get a uniform base for the Gather/Scatter intrinsic.
4262 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4263 // We try to represent it as a base pointer + vector of indices.
4264 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4265 // The first operand of the GEP may be a single pointer or a vector of pointers
4266 // Example:
4267 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4268 //  or
4269 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4270 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4271 //
4272 // When the first GEP operand is a single pointer - it is the uniform base we
4273 // are looking for. If first operand of the GEP is a splat vector - we
4274 // extract the splat value and use it as a uniform base.
4275 // In all other cases the function returns 'false'.
4276 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4277                            ISD::MemIndexType &IndexType, SDValue &Scale,
4278                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4279   SelectionDAG& DAG = SDB->DAG;
4280   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4281   const DataLayout &DL = DAG.getDataLayout();
4282 
4283   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4284 
4285   // Handle splat constant pointer.
4286   if (auto *C = dyn_cast<Constant>(Ptr)) {
4287     C = C->getSplatValue();
4288     if (!C)
4289       return false;
4290 
4291     Base = SDB->getValue(C);
4292 
4293     unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements();
4294     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4295     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4296     IndexType = ISD::SIGNED_SCALED;
4297     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4298     return true;
4299   }
4300 
4301   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4302   if (!GEP || GEP->getParent() != CurBB)
4303     return false;
4304 
4305   if (GEP->getNumOperands() != 2)
4306     return false;
4307 
4308   const Value *BasePtr = GEP->getPointerOperand();
4309   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4310 
4311   // Make sure the base is scalar and the index is a vector.
4312   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4313     return false;
4314 
4315   Base = SDB->getValue(BasePtr);
4316   Index = SDB->getValue(IndexVal);
4317   IndexType = ISD::SIGNED_SCALED;
4318   Scale = DAG.getTargetConstant(
4319               DL.getTypeAllocSize(GEP->getResultElementType()),
4320               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4321   return true;
4322 }
4323 
4324 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4325   SDLoc sdl = getCurSDLoc();
4326 
4327   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4328   const Value *Ptr = I.getArgOperand(1);
4329   SDValue Src0 = getValue(I.getArgOperand(0));
4330   SDValue Mask = getValue(I.getArgOperand(3));
4331   EVT VT = Src0.getValueType();
4332   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(2))->getZExtValue());
4333   if (!Alignment)
4334     Alignment = DAG.getEVTAlign(VT);
4335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4336 
4337   AAMDNodes AAInfo;
4338   I.getAAMetadata(AAInfo);
4339 
4340   SDValue Base;
4341   SDValue Index;
4342   ISD::MemIndexType IndexType;
4343   SDValue Scale;
4344   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4345                                     I.getParent());
4346 
4347   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4348   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4349       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4350       // TODO: Make MachineMemOperands aware of scalable
4351       // vectors.
4352       MemoryLocation::UnknownSize, *Alignment, AAInfo);
4353   if (!UniformBase) {
4354     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4355     Index = getValue(Ptr);
4356     IndexType = ISD::SIGNED_SCALED;
4357     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4358   }
4359   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4360   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4361                                          Ops, MMO, IndexType);
4362   DAG.setRoot(Scatter);
4363   setValue(&I, Scatter);
4364 }
4365 
4366 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4367   SDLoc sdl = getCurSDLoc();
4368 
4369   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4370                               MaybeAlign &Alignment) {
4371     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4372     Ptr = I.getArgOperand(0);
4373     Alignment =
4374         MaybeAlign(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4375     Mask = I.getArgOperand(2);
4376     Src0 = I.getArgOperand(3);
4377   };
4378   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4379                                  MaybeAlign &Alignment) {
4380     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4381     Ptr = I.getArgOperand(0);
4382     Alignment = None;
4383     Mask = I.getArgOperand(1);
4384     Src0 = I.getArgOperand(2);
4385   };
4386 
4387   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4388   MaybeAlign Alignment;
4389   if (IsExpanding)
4390     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4391   else
4392     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4393 
4394   SDValue Ptr = getValue(PtrOperand);
4395   SDValue Src0 = getValue(Src0Operand);
4396   SDValue Mask = getValue(MaskOperand);
4397   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4398 
4399   EVT VT = Src0.getValueType();
4400   if (!Alignment)
4401     Alignment = DAG.getEVTAlign(VT);
4402 
4403   AAMDNodes AAInfo;
4404   I.getAAMetadata(AAInfo);
4405   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4406 
4407   // Do not serialize masked loads of constant memory with anything.
4408   MemoryLocation ML;
4409   if (VT.isScalableVector())
4410     ML = MemoryLocation(PtrOperand);
4411   else
4412     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4413                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4414                            AAInfo);
4415   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4416 
4417   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4418 
4419   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4420       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4421       // TODO: Make MachineMemOperands aware of scalable
4422       // vectors.
4423       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4424 
4425   SDValue Load =
4426       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4427                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4428   if (AddToChain)
4429     PendingLoads.push_back(Load.getValue(1));
4430   setValue(&I, Load);
4431 }
4432 
4433 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4434   SDLoc sdl = getCurSDLoc();
4435 
4436   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4437   const Value *Ptr = I.getArgOperand(0);
4438   SDValue Src0 = getValue(I.getArgOperand(3));
4439   SDValue Mask = getValue(I.getArgOperand(2));
4440 
4441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4442   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4443   MaybeAlign Alignment(cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
4444   if (!Alignment)
4445     Alignment = DAG.getEVTAlign(VT);
4446 
4447   AAMDNodes AAInfo;
4448   I.getAAMetadata(AAInfo);
4449   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4450 
4451   SDValue Root = DAG.getRoot();
4452   SDValue Base;
4453   SDValue Index;
4454   ISD::MemIndexType IndexType;
4455   SDValue Scale;
4456   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4457                                     I.getParent());
4458   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4459   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4460       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4461       // TODO: Make MachineMemOperands aware of scalable
4462       // vectors.
4463       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4464 
4465   if (!UniformBase) {
4466     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4467     Index = getValue(Ptr);
4468     IndexType = ISD::SIGNED_SCALED;
4469     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4470   }
4471   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4472   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4473                                        Ops, MMO, IndexType);
4474 
4475   PendingLoads.push_back(Gather.getValue(1));
4476   setValue(&I, Gather);
4477 }
4478 
4479 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4480   SDLoc dl = getCurSDLoc();
4481   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4482   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4483   SyncScope::ID SSID = I.getSyncScopeID();
4484 
4485   SDValue InChain = getRoot();
4486 
4487   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4488   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4489 
4490   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4491   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4492 
4493   MachineFunction &MF = DAG.getMachineFunction();
4494   MachineMemOperand *MMO = MF.getMachineMemOperand(
4495       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4496       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4497       FailureOrdering);
4498 
4499   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4500                                    dl, MemVT, VTs, InChain,
4501                                    getValue(I.getPointerOperand()),
4502                                    getValue(I.getCompareOperand()),
4503                                    getValue(I.getNewValOperand()), MMO);
4504 
4505   SDValue OutChain = L.getValue(2);
4506 
4507   setValue(&I, L);
4508   DAG.setRoot(OutChain);
4509 }
4510 
4511 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4512   SDLoc dl = getCurSDLoc();
4513   ISD::NodeType NT;
4514   switch (I.getOperation()) {
4515   default: llvm_unreachable("Unknown atomicrmw operation");
4516   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4517   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4518   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4519   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4520   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4521   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4522   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4523   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4524   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4525   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4526   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4527   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4528   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4529   }
4530   AtomicOrdering Ordering = I.getOrdering();
4531   SyncScope::ID SSID = I.getSyncScopeID();
4532 
4533   SDValue InChain = getRoot();
4534 
4535   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4537   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4538 
4539   MachineFunction &MF = DAG.getMachineFunction();
4540   MachineMemOperand *MMO = MF.getMachineMemOperand(
4541       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4542       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4543 
4544   SDValue L =
4545     DAG.getAtomic(NT, dl, MemVT, InChain,
4546                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4547                   MMO);
4548 
4549   SDValue OutChain = L.getValue(1);
4550 
4551   setValue(&I, L);
4552   DAG.setRoot(OutChain);
4553 }
4554 
4555 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4556   SDLoc dl = getCurSDLoc();
4557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4558   SDValue Ops[3];
4559   Ops[0] = getRoot();
4560   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4561                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4562   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4563                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4564   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4565 }
4566 
4567 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4568   SDLoc dl = getCurSDLoc();
4569   AtomicOrdering Order = I.getOrdering();
4570   SyncScope::ID SSID = I.getSyncScopeID();
4571 
4572   SDValue InChain = getRoot();
4573 
4574   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4575   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4576   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4577 
4578   if (!TLI.supportsUnalignedAtomics() &&
4579       I.getAlignment() < MemVT.getSizeInBits() / 8)
4580     report_fatal_error("Cannot generate unaligned atomic load");
4581 
4582   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4583 
4584   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4585       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4586       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4587 
4588   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4589 
4590   SDValue Ptr = getValue(I.getPointerOperand());
4591 
4592   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4593     // TODO: Once this is better exercised by tests, it should be merged with
4594     // the normal path for loads to prevent future divergence.
4595     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4596     if (MemVT != VT)
4597       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4598 
4599     setValue(&I, L);
4600     SDValue OutChain = L.getValue(1);
4601     if (!I.isUnordered())
4602       DAG.setRoot(OutChain);
4603     else
4604       PendingLoads.push_back(OutChain);
4605     return;
4606   }
4607 
4608   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4609                             Ptr, MMO);
4610 
4611   SDValue OutChain = L.getValue(1);
4612   if (MemVT != VT)
4613     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4614 
4615   setValue(&I, L);
4616   DAG.setRoot(OutChain);
4617 }
4618 
4619 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4620   SDLoc dl = getCurSDLoc();
4621 
4622   AtomicOrdering Ordering = I.getOrdering();
4623   SyncScope::ID SSID = I.getSyncScopeID();
4624 
4625   SDValue InChain = getRoot();
4626 
4627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4628   EVT MemVT =
4629       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4630 
4631   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4632     report_fatal_error("Cannot generate unaligned atomic store");
4633 
4634   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4635 
4636   MachineFunction &MF = DAG.getMachineFunction();
4637   MachineMemOperand *MMO = MF.getMachineMemOperand(
4638       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4639       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4640 
4641   SDValue Val = getValue(I.getValueOperand());
4642   if (Val.getValueType() != MemVT)
4643     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4644   SDValue Ptr = getValue(I.getPointerOperand());
4645 
4646   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4647     // TODO: Once this is better exercised by tests, it should be merged with
4648     // the normal path for stores to prevent future divergence.
4649     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4650     DAG.setRoot(S);
4651     return;
4652   }
4653   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4654                                    Ptr, Val, MMO);
4655 
4656 
4657   DAG.setRoot(OutChain);
4658 }
4659 
4660 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4661 /// node.
4662 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4663                                                unsigned Intrinsic) {
4664   // Ignore the callsite's attributes. A specific call site may be marked with
4665   // readnone, but the lowering code will expect the chain based on the
4666   // definition.
4667   const Function *F = I.getCalledFunction();
4668   bool HasChain = !F->doesNotAccessMemory();
4669   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4670 
4671   // Build the operand list.
4672   SmallVector<SDValue, 8> Ops;
4673   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4674     if (OnlyLoad) {
4675       // We don't need to serialize loads against other loads.
4676       Ops.push_back(DAG.getRoot());
4677     } else {
4678       Ops.push_back(getRoot());
4679     }
4680   }
4681 
4682   // Info is set by getTgtMemInstrinsic
4683   TargetLowering::IntrinsicInfo Info;
4684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4685   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4686                                                DAG.getMachineFunction(),
4687                                                Intrinsic);
4688 
4689   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4690   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4691       Info.opc == ISD::INTRINSIC_W_CHAIN)
4692     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4693                                         TLI.getPointerTy(DAG.getDataLayout())));
4694 
4695   // Add all operands of the call to the operand list.
4696   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4697     const Value *Arg = I.getArgOperand(i);
4698     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4699       Ops.push_back(getValue(Arg));
4700       continue;
4701     }
4702 
4703     // Use TargetConstant instead of a regular constant for immarg.
4704     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4705     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4706       assert(CI->getBitWidth() <= 64 &&
4707              "large intrinsic immediates not handled");
4708       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4709     } else {
4710       Ops.push_back(
4711           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4712     }
4713   }
4714 
4715   SmallVector<EVT, 4> ValueVTs;
4716   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4717 
4718   if (HasChain)
4719     ValueVTs.push_back(MVT::Other);
4720 
4721   SDVTList VTs = DAG.getVTList(ValueVTs);
4722 
4723   // Create the node.
4724   SDValue Result;
4725   if (IsTgtIntrinsic) {
4726     // This is target intrinsic that touches memory
4727     AAMDNodes AAInfo;
4728     I.getAAMetadata(AAInfo);
4729     Result =
4730         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4731                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4732                                 Info.align, Info.flags, Info.size, AAInfo);
4733   } else if (!HasChain) {
4734     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4735   } else if (!I.getType()->isVoidTy()) {
4736     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4737   } else {
4738     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4739   }
4740 
4741   if (HasChain) {
4742     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4743     if (OnlyLoad)
4744       PendingLoads.push_back(Chain);
4745     else
4746       DAG.setRoot(Chain);
4747   }
4748 
4749   if (!I.getType()->isVoidTy()) {
4750     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4751       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4752       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4753     } else
4754       Result = lowerRangeToAssertZExt(DAG, I, Result);
4755 
4756     MaybeAlign Alignment = I.getRetAlign();
4757     if (!Alignment)
4758       Alignment = F->getAttributes().getRetAlignment();
4759     // Insert `assertalign` node if there's an alignment.
4760     if (InsertAssertAlign && Alignment) {
4761       Result =
4762           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4763     }
4764 
4765     setValue(&I, Result);
4766   }
4767 }
4768 
4769 /// GetSignificand - Get the significand and build it into a floating-point
4770 /// number with exponent of 1:
4771 ///
4772 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4773 ///
4774 /// where Op is the hexadecimal representation of floating point value.
4775 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4776   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4777                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4778   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4779                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4780   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4781 }
4782 
4783 /// GetExponent - Get the exponent:
4784 ///
4785 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4786 ///
4787 /// where Op is the hexadecimal representation of floating point value.
4788 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4789                            const TargetLowering &TLI, const SDLoc &dl) {
4790   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4791                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4792   SDValue t1 = DAG.getNode(
4793       ISD::SRL, dl, MVT::i32, t0,
4794       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4795   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4796                            DAG.getConstant(127, dl, MVT::i32));
4797   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4798 }
4799 
4800 /// getF32Constant - Get 32-bit floating point constant.
4801 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4802                               const SDLoc &dl) {
4803   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4804                            MVT::f32);
4805 }
4806 
4807 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4808                                        SelectionDAG &DAG) {
4809   // TODO: What fast-math-flags should be set on the floating-point nodes?
4810 
4811   //   IntegerPartOfX = ((int32_t)(t0);
4812   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4813 
4814   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4815   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4816   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4817 
4818   //   IntegerPartOfX <<= 23;
4819   IntegerPartOfX = DAG.getNode(
4820       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4821       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4822                                   DAG.getDataLayout())));
4823 
4824   SDValue TwoToFractionalPartOfX;
4825   if (LimitFloatPrecision <= 6) {
4826     // For floating-point precision of 6:
4827     //
4828     //   TwoToFractionalPartOfX =
4829     //     0.997535578f +
4830     //       (0.735607626f + 0.252464424f * x) * x;
4831     //
4832     // error 0.0144103317, which is 6 bits
4833     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4834                              getF32Constant(DAG, 0x3e814304, dl));
4835     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4836                              getF32Constant(DAG, 0x3f3c50c8, dl));
4837     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4838     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4839                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4840   } else if (LimitFloatPrecision <= 12) {
4841     // For floating-point precision of 12:
4842     //
4843     //   TwoToFractionalPartOfX =
4844     //     0.999892986f +
4845     //       (0.696457318f +
4846     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4847     //
4848     // error 0.000107046256, which is 13 to 14 bits
4849     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4850                              getF32Constant(DAG, 0x3da235e3, dl));
4851     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4852                              getF32Constant(DAG, 0x3e65b8f3, dl));
4853     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4854     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4855                              getF32Constant(DAG, 0x3f324b07, dl));
4856     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4857     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4858                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4859   } else { // LimitFloatPrecision <= 18
4860     // For floating-point precision of 18:
4861     //
4862     //   TwoToFractionalPartOfX =
4863     //     0.999999982f +
4864     //       (0.693148872f +
4865     //         (0.240227044f +
4866     //           (0.554906021e-1f +
4867     //             (0.961591928e-2f +
4868     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4869     // error 2.47208000*10^(-7), which is better than 18 bits
4870     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4871                              getF32Constant(DAG, 0x3924b03e, dl));
4872     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4873                              getF32Constant(DAG, 0x3ab24b87, dl));
4874     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4875     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4876                              getF32Constant(DAG, 0x3c1d8c17, dl));
4877     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4878     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4879                              getF32Constant(DAG, 0x3d634a1d, dl));
4880     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4881     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4882                              getF32Constant(DAG, 0x3e75fe14, dl));
4883     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4884     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4885                               getF32Constant(DAG, 0x3f317234, dl));
4886     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4887     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4888                                          getF32Constant(DAG, 0x3f800000, dl));
4889   }
4890 
4891   // Add the exponent into the result in integer domain.
4892   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4893   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4894                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4895 }
4896 
4897 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4898 /// limited-precision mode.
4899 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4900                          const TargetLowering &TLI) {
4901   if (Op.getValueType() == MVT::f32 &&
4902       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4903 
4904     // Put the exponent in the right bit position for later addition to the
4905     // final result:
4906     //
4907     // t0 = Op * log2(e)
4908 
4909     // TODO: What fast-math-flags should be set here?
4910     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4911                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4912     return getLimitedPrecisionExp2(t0, dl, DAG);
4913   }
4914 
4915   // No special expansion.
4916   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4917 }
4918 
4919 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4920 /// limited-precision mode.
4921 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4922                          const TargetLowering &TLI) {
4923   // TODO: What fast-math-flags should be set on the floating-point nodes?
4924 
4925   if (Op.getValueType() == MVT::f32 &&
4926       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4927     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4928 
4929     // Scale the exponent by log(2).
4930     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4931     SDValue LogOfExponent =
4932         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4933                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4934 
4935     // Get the significand and build it into a floating-point number with
4936     // exponent of 1.
4937     SDValue X = GetSignificand(DAG, Op1, dl);
4938 
4939     SDValue LogOfMantissa;
4940     if (LimitFloatPrecision <= 6) {
4941       // For floating-point precision of 6:
4942       //
4943       //   LogofMantissa =
4944       //     -1.1609546f +
4945       //       (1.4034025f - 0.23903021f * x) * x;
4946       //
4947       // error 0.0034276066, which is better than 8 bits
4948       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4949                                getF32Constant(DAG, 0xbe74c456, dl));
4950       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4951                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4952       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4953       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4954                                   getF32Constant(DAG, 0x3f949a29, dl));
4955     } else if (LimitFloatPrecision <= 12) {
4956       // For floating-point precision of 12:
4957       //
4958       //   LogOfMantissa =
4959       //     -1.7417939f +
4960       //       (2.8212026f +
4961       //         (-1.4699568f +
4962       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4963       //
4964       // error 0.000061011436, which is 14 bits
4965       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4966                                getF32Constant(DAG, 0xbd67b6d6, dl));
4967       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4968                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4969       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4970       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4971                                getF32Constant(DAG, 0x3fbc278b, dl));
4972       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4973       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4974                                getF32Constant(DAG, 0x40348e95, dl));
4975       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4976       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4977                                   getF32Constant(DAG, 0x3fdef31a, dl));
4978     } else { // LimitFloatPrecision <= 18
4979       // For floating-point precision of 18:
4980       //
4981       //   LogOfMantissa =
4982       //     -2.1072184f +
4983       //       (4.2372794f +
4984       //         (-3.7029485f +
4985       //           (2.2781945f +
4986       //             (-0.87823314f +
4987       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4988       //
4989       // error 0.0000023660568, which is better than 18 bits
4990       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4991                                getF32Constant(DAG, 0xbc91e5ac, dl));
4992       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4993                                getF32Constant(DAG, 0x3e4350aa, dl));
4994       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4995       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4996                                getF32Constant(DAG, 0x3f60d3e3, dl));
4997       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4998       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4999                                getF32Constant(DAG, 0x4011cdf0, dl));
5000       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5001       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5002                                getF32Constant(DAG, 0x406cfd1c, dl));
5003       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5004       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5005                                getF32Constant(DAG, 0x408797cb, dl));
5006       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5007       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5008                                   getF32Constant(DAG, 0x4006dcab, dl));
5009     }
5010 
5011     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5012   }
5013 
5014   // No special expansion.
5015   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5016 }
5017 
5018 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5019 /// limited-precision mode.
5020 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5021                           const TargetLowering &TLI) {
5022   // TODO: What fast-math-flags should be set on the floating-point nodes?
5023 
5024   if (Op.getValueType() == MVT::f32 &&
5025       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5026     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5027 
5028     // Get the exponent.
5029     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5030 
5031     // Get the significand and build it into a floating-point number with
5032     // exponent of 1.
5033     SDValue X = GetSignificand(DAG, Op1, dl);
5034 
5035     // Different possible minimax approximations of significand in
5036     // floating-point for various degrees of accuracy over [1,2].
5037     SDValue Log2ofMantissa;
5038     if (LimitFloatPrecision <= 6) {
5039       // For floating-point precision of 6:
5040       //
5041       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5042       //
5043       // error 0.0049451742, which is more than 7 bits
5044       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5045                                getF32Constant(DAG, 0xbeb08fe0, dl));
5046       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5047                                getF32Constant(DAG, 0x40019463, dl));
5048       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5049       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5050                                    getF32Constant(DAG, 0x3fd6633d, dl));
5051     } else if (LimitFloatPrecision <= 12) {
5052       // For floating-point precision of 12:
5053       //
5054       //   Log2ofMantissa =
5055       //     -2.51285454f +
5056       //       (4.07009056f +
5057       //         (-2.12067489f +
5058       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5059       //
5060       // error 0.0000876136000, which is better than 13 bits
5061       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5062                                getF32Constant(DAG, 0xbda7262e, dl));
5063       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5064                                getF32Constant(DAG, 0x3f25280b, dl));
5065       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5066       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5067                                getF32Constant(DAG, 0x4007b923, dl));
5068       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5069       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5070                                getF32Constant(DAG, 0x40823e2f, dl));
5071       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5072       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5073                                    getF32Constant(DAG, 0x4020d29c, dl));
5074     } else { // LimitFloatPrecision <= 18
5075       // For floating-point precision of 18:
5076       //
5077       //   Log2ofMantissa =
5078       //     -3.0400495f +
5079       //       (6.1129976f +
5080       //         (-5.3420409f +
5081       //           (3.2865683f +
5082       //             (-1.2669343f +
5083       //               (0.27515199f -
5084       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5085       //
5086       // error 0.0000018516, which is better than 18 bits
5087       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5088                                getF32Constant(DAG, 0xbcd2769e, dl));
5089       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5090                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5091       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5092       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5093                                getF32Constant(DAG, 0x3fa22ae7, dl));
5094       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5095       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5096                                getF32Constant(DAG, 0x40525723, dl));
5097       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5098       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5099                                getF32Constant(DAG, 0x40aaf200, dl));
5100       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5101       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5102                                getF32Constant(DAG, 0x40c39dad, dl));
5103       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5104       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5105                                    getF32Constant(DAG, 0x4042902c, dl));
5106     }
5107 
5108     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5109   }
5110 
5111   // No special expansion.
5112   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5113 }
5114 
5115 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5116 /// limited-precision mode.
5117 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5118                            const TargetLowering &TLI) {
5119   // TODO: What fast-math-flags should be set on the floating-point nodes?
5120 
5121   if (Op.getValueType() == MVT::f32 &&
5122       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5123     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5124 
5125     // Scale the exponent by log10(2) [0.30102999f].
5126     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5127     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5128                                         getF32Constant(DAG, 0x3e9a209a, dl));
5129 
5130     // Get the significand and build it into a floating-point number with
5131     // exponent of 1.
5132     SDValue X = GetSignificand(DAG, Op1, dl);
5133 
5134     SDValue Log10ofMantissa;
5135     if (LimitFloatPrecision <= 6) {
5136       // For floating-point precision of 6:
5137       //
5138       //   Log10ofMantissa =
5139       //     -0.50419619f +
5140       //       (0.60948995f - 0.10380950f * x) * x;
5141       //
5142       // error 0.0014886165, which is 6 bits
5143       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5144                                getF32Constant(DAG, 0xbdd49a13, dl));
5145       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5146                                getF32Constant(DAG, 0x3f1c0789, dl));
5147       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5148       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5149                                     getF32Constant(DAG, 0x3f011300, dl));
5150     } else if (LimitFloatPrecision <= 12) {
5151       // For floating-point precision of 12:
5152       //
5153       //   Log10ofMantissa =
5154       //     -0.64831180f +
5155       //       (0.91751397f +
5156       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5157       //
5158       // error 0.00019228036, which is better than 12 bits
5159       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5160                                getF32Constant(DAG, 0x3d431f31, dl));
5161       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5162                                getF32Constant(DAG, 0x3ea21fb2, dl));
5163       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5164       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5165                                getF32Constant(DAG, 0x3f6ae232, dl));
5166       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5167       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5168                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5169     } else { // LimitFloatPrecision <= 18
5170       // For floating-point precision of 18:
5171       //
5172       //   Log10ofMantissa =
5173       //     -0.84299375f +
5174       //       (1.5327582f +
5175       //         (-1.0688956f +
5176       //           (0.49102474f +
5177       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5178       //
5179       // error 0.0000037995730, which is better than 18 bits
5180       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5181                                getF32Constant(DAG, 0x3c5d51ce, dl));
5182       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5183                                getF32Constant(DAG, 0x3e00685a, dl));
5184       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5185       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5186                                getF32Constant(DAG, 0x3efb6798, dl));
5187       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5188       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5189                                getF32Constant(DAG, 0x3f88d192, dl));
5190       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5191       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5192                                getF32Constant(DAG, 0x3fc4316c, dl));
5193       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5194       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5195                                     getF32Constant(DAG, 0x3f57ce70, dl));
5196     }
5197 
5198     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5199   }
5200 
5201   // No special expansion.
5202   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5203 }
5204 
5205 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5206 /// limited-precision mode.
5207 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5208                           const TargetLowering &TLI) {
5209   if (Op.getValueType() == MVT::f32 &&
5210       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5211     return getLimitedPrecisionExp2(Op, dl, DAG);
5212 
5213   // No special expansion.
5214   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5215 }
5216 
5217 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5218 /// limited-precision mode with x == 10.0f.
5219 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5220                          SelectionDAG &DAG, const TargetLowering &TLI) {
5221   bool IsExp10 = false;
5222   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5223       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5224     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5225       APFloat Ten(10.0f);
5226       IsExp10 = LHSC->isExactlyValue(Ten);
5227     }
5228   }
5229 
5230   // TODO: What fast-math-flags should be set on the FMUL node?
5231   if (IsExp10) {
5232     // Put the exponent in the right bit position for later addition to the
5233     // final result:
5234     //
5235     //   #define LOG2OF10 3.3219281f
5236     //   t0 = Op * LOG2OF10;
5237     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5238                              getF32Constant(DAG, 0x40549a78, dl));
5239     return getLimitedPrecisionExp2(t0, dl, DAG);
5240   }
5241 
5242   // No special expansion.
5243   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5244 }
5245 
5246 /// ExpandPowI - Expand a llvm.powi intrinsic.
5247 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5248                           SelectionDAG &DAG) {
5249   // If RHS is a constant, we can expand this out to a multiplication tree,
5250   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5251   // optimizing for size, we only want to do this if the expansion would produce
5252   // a small number of multiplies, otherwise we do the full expansion.
5253   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5254     // Get the exponent as a positive value.
5255     unsigned Val = RHSC->getSExtValue();
5256     if ((int)Val < 0) Val = -Val;
5257 
5258     // powi(x, 0) -> 1.0
5259     if (Val == 0)
5260       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5261 
5262     bool OptForSize = DAG.shouldOptForSize();
5263     if (!OptForSize ||
5264         // If optimizing for size, don't insert too many multiplies.
5265         // This inserts up to 5 multiplies.
5266         countPopulation(Val) + Log2_32(Val) < 7) {
5267       // We use the simple binary decomposition method to generate the multiply
5268       // sequence.  There are more optimal ways to do this (for example,
5269       // powi(x,15) generates one more multiply than it should), but this has
5270       // the benefit of being both really simple and much better than a libcall.
5271       SDValue Res;  // Logically starts equal to 1.0
5272       SDValue CurSquare = LHS;
5273       // TODO: Intrinsics should have fast-math-flags that propagate to these
5274       // nodes.
5275       while (Val) {
5276         if (Val & 1) {
5277           if (Res.getNode())
5278             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5279           else
5280             Res = CurSquare;  // 1.0*CurSquare.
5281         }
5282 
5283         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5284                                 CurSquare, CurSquare);
5285         Val >>= 1;
5286       }
5287 
5288       // If the original was negative, invert the result, producing 1/(x*x*x).
5289       if (RHSC->getSExtValue() < 0)
5290         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5291                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5292       return Res;
5293     }
5294   }
5295 
5296   // Otherwise, expand to a libcall.
5297   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5298 }
5299 
5300 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5301                             SDValue LHS, SDValue RHS, SDValue Scale,
5302                             SelectionDAG &DAG, const TargetLowering &TLI) {
5303   EVT VT = LHS.getValueType();
5304   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5305   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5306   LLVMContext &Ctx = *DAG.getContext();
5307 
5308   // If the type is legal but the operation isn't, this node might survive all
5309   // the way to operation legalization. If we end up there and we do not have
5310   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5311   // node.
5312 
5313   // Coax the legalizer into expanding the node during type legalization instead
5314   // by bumping the size by one bit. This will force it to Promote, enabling the
5315   // early expansion and avoiding the need to expand later.
5316 
5317   // We don't have to do this if Scale is 0; that can always be expanded, unless
5318   // it's a saturating signed operation. Those can experience true integer
5319   // division overflow, a case which we must avoid.
5320 
5321   // FIXME: We wouldn't have to do this (or any of the early
5322   // expansion/promotion) if it was possible to expand a libcall of an
5323   // illegal type during operation legalization. But it's not, so things
5324   // get a bit hacky.
5325   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5326   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5327       (TLI.isTypeLegal(VT) ||
5328        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5329     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5330         Opcode, VT, ScaleInt);
5331     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5332       EVT PromVT;
5333       if (VT.isScalarInteger())
5334         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5335       else if (VT.isVector()) {
5336         PromVT = VT.getVectorElementType();
5337         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5338         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5339       } else
5340         llvm_unreachable("Wrong VT for DIVFIX?");
5341       if (Signed) {
5342         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5343         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5344       } else {
5345         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5346         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5347       }
5348       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5349       // For saturating operations, we need to shift up the LHS to get the
5350       // proper saturation width, and then shift down again afterwards.
5351       if (Saturating)
5352         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5353                           DAG.getConstant(1, DL, ShiftTy));
5354       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5355       if (Saturating)
5356         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5357                           DAG.getConstant(1, DL, ShiftTy));
5358       return DAG.getZExtOrTrunc(Res, DL, VT);
5359     }
5360   }
5361 
5362   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5363 }
5364 
5365 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5366 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5367 static void
5368 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5369                      const SDValue &N) {
5370   switch (N.getOpcode()) {
5371   case ISD::CopyFromReg: {
5372     SDValue Op = N.getOperand(1);
5373     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5374                       Op.getValueType().getSizeInBits());
5375     return;
5376   }
5377   case ISD::BITCAST:
5378   case ISD::AssertZext:
5379   case ISD::AssertSext:
5380   case ISD::TRUNCATE:
5381     getUnderlyingArgRegs(Regs, N.getOperand(0));
5382     return;
5383   case ISD::BUILD_PAIR:
5384   case ISD::BUILD_VECTOR:
5385   case ISD::CONCAT_VECTORS:
5386     for (SDValue Op : N->op_values())
5387       getUnderlyingArgRegs(Regs, Op);
5388     return;
5389   default:
5390     return;
5391   }
5392 }
5393 
5394 /// If the DbgValueInst is a dbg_value of a function argument, create the
5395 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5396 /// instruction selection, they will be inserted to the entry BB.
5397 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5398     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5399     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5400   const Argument *Arg = dyn_cast<Argument>(V);
5401   if (!Arg)
5402     return false;
5403 
5404   if (!IsDbgDeclare) {
5405     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5406     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5407     // the entry block.
5408     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5409     if (!IsInEntryBlock)
5410       return false;
5411 
5412     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5413     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5414     // variable that also is a param.
5415     //
5416     // Although, if we are at the top of the entry block already, we can still
5417     // emit using ArgDbgValue. This might catch some situations when the
5418     // dbg.value refers to an argument that isn't used in the entry block, so
5419     // any CopyToReg node would be optimized out and the only way to express
5420     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5421     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5422     // we should only emit as ArgDbgValue if the Variable is an argument to the
5423     // current function, and the dbg.value intrinsic is found in the entry
5424     // block.
5425     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5426         !DL->getInlinedAt();
5427     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5428     if (!IsInPrologue && !VariableIsFunctionInputArg)
5429       return false;
5430 
5431     // Here we assume that a function argument on IR level only can be used to
5432     // describe one input parameter on source level. If we for example have
5433     // source code like this
5434     //
5435     //    struct A { long x, y; };
5436     //    void foo(struct A a, long b) {
5437     //      ...
5438     //      b = a.x;
5439     //      ...
5440     //    }
5441     //
5442     // and IR like this
5443     //
5444     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5445     //  entry:
5446     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5447     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5448     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5449     //    ...
5450     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5451     //    ...
5452     //
5453     // then the last dbg.value is describing a parameter "b" using a value that
5454     // is an argument. But since we already has used %a1 to describe a parameter
5455     // we should not handle that last dbg.value here (that would result in an
5456     // incorrect hoisting of the DBG_VALUE to the function entry).
5457     // Notice that we allow one dbg.value per IR level argument, to accommodate
5458     // for the situation with fragments above.
5459     if (VariableIsFunctionInputArg) {
5460       unsigned ArgNo = Arg->getArgNo();
5461       if (ArgNo >= FuncInfo.DescribedArgs.size())
5462         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5463       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5464         return false;
5465       FuncInfo.DescribedArgs.set(ArgNo);
5466     }
5467   }
5468 
5469   MachineFunction &MF = DAG.getMachineFunction();
5470   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5471 
5472   bool IsIndirect = false;
5473   Optional<MachineOperand> Op;
5474   // Some arguments' frame index is recorded during argument lowering.
5475   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5476   if (FI != std::numeric_limits<int>::max())
5477     Op = MachineOperand::CreateFI(FI);
5478 
5479   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5480   if (!Op && N.getNode()) {
5481     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5482     Register Reg;
5483     if (ArgRegsAndSizes.size() == 1)
5484       Reg = ArgRegsAndSizes.front().first;
5485 
5486     if (Reg && Reg.isVirtual()) {
5487       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5488       Register PR = RegInfo.getLiveInPhysReg(Reg);
5489       if (PR)
5490         Reg = PR;
5491     }
5492     if (Reg) {
5493       Op = MachineOperand::CreateReg(Reg, false);
5494       IsIndirect = IsDbgDeclare;
5495     }
5496   }
5497 
5498   if (!Op && N.getNode()) {
5499     // Check if frame index is available.
5500     SDValue LCandidate = peekThroughBitcasts(N);
5501     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5502       if (FrameIndexSDNode *FINode =
5503           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5504         Op = MachineOperand::CreateFI(FINode->getIndex());
5505   }
5506 
5507   if (!Op) {
5508     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5509     auto splitMultiRegDbgValue
5510       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5511       unsigned Offset = 0;
5512       for (auto RegAndSize : SplitRegs) {
5513         // If the expression is already a fragment, the current register
5514         // offset+size might extend beyond the fragment. In this case, only
5515         // the register bits that are inside the fragment are relevant.
5516         int RegFragmentSizeInBits = RegAndSize.second;
5517         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5518           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5519           // The register is entirely outside the expression fragment,
5520           // so is irrelevant for debug info.
5521           if (Offset >= ExprFragmentSizeInBits)
5522             break;
5523           // The register is partially outside the expression fragment, only
5524           // the low bits within the fragment are relevant for debug info.
5525           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5526             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5527           }
5528         }
5529 
5530         auto FragmentExpr = DIExpression::createFragmentExpression(
5531             Expr, Offset, RegFragmentSizeInBits);
5532         Offset += RegAndSize.second;
5533         // If a valid fragment expression cannot be created, the variable's
5534         // correct value cannot be determined and so it is set as Undef.
5535         if (!FragmentExpr) {
5536           SDDbgValue *SDV = DAG.getConstantDbgValue(
5537               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5538           DAG.AddDbgValue(SDV, nullptr, false);
5539           continue;
5540         }
5541         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5542         FuncInfo.ArgDbgValues.push_back(
5543           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5544                   RegAndSize.first, Variable, *FragmentExpr));
5545       }
5546     };
5547 
5548     // Check if ValueMap has reg number.
5549     DenseMap<const Value *, Register>::const_iterator
5550       VMI = FuncInfo.ValueMap.find(V);
5551     if (VMI != FuncInfo.ValueMap.end()) {
5552       const auto &TLI = DAG.getTargetLoweringInfo();
5553       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5554                        V->getType(), getABIRegCopyCC(V));
5555       if (RFV.occupiesMultipleRegs()) {
5556         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5557         return true;
5558       }
5559 
5560       Op = MachineOperand::CreateReg(VMI->second, false);
5561       IsIndirect = IsDbgDeclare;
5562     } else if (ArgRegsAndSizes.size() > 1) {
5563       // This was split due to the calling convention, and no virtual register
5564       // mapping exists for the value.
5565       splitMultiRegDbgValue(ArgRegsAndSizes);
5566       return true;
5567     }
5568   }
5569 
5570   if (!Op)
5571     return false;
5572 
5573   assert(Variable->isValidLocationForIntrinsic(DL) &&
5574          "Expected inlined-at fields to agree");
5575   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5576   FuncInfo.ArgDbgValues.push_back(
5577       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5578               *Op, Variable, Expr));
5579 
5580   return true;
5581 }
5582 
5583 /// Return the appropriate SDDbgValue based on N.
5584 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5585                                              DILocalVariable *Variable,
5586                                              DIExpression *Expr,
5587                                              const DebugLoc &dl,
5588                                              unsigned DbgSDNodeOrder) {
5589   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5590     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5591     // stack slot locations.
5592     //
5593     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5594     // debug values here after optimization:
5595     //
5596     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5597     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5598     //
5599     // Both describe the direct values of their associated variables.
5600     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5601                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5602   }
5603   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5604                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5605 }
5606 
5607 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5608   switch (Intrinsic) {
5609   case Intrinsic::smul_fix:
5610     return ISD::SMULFIX;
5611   case Intrinsic::umul_fix:
5612     return ISD::UMULFIX;
5613   case Intrinsic::smul_fix_sat:
5614     return ISD::SMULFIXSAT;
5615   case Intrinsic::umul_fix_sat:
5616     return ISD::UMULFIXSAT;
5617   case Intrinsic::sdiv_fix:
5618     return ISD::SDIVFIX;
5619   case Intrinsic::udiv_fix:
5620     return ISD::UDIVFIX;
5621   case Intrinsic::sdiv_fix_sat:
5622     return ISD::SDIVFIXSAT;
5623   case Intrinsic::udiv_fix_sat:
5624     return ISD::UDIVFIXSAT;
5625   default:
5626     llvm_unreachable("Unhandled fixed point intrinsic");
5627   }
5628 }
5629 
5630 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5631                                            const char *FunctionName) {
5632   assert(FunctionName && "FunctionName must not be nullptr");
5633   SDValue Callee = DAG.getExternalSymbol(
5634       FunctionName,
5635       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5636   LowerCallTo(I, Callee, I.isTailCall());
5637 }
5638 
5639 /// Given a @llvm.call.preallocated.setup, return the corresponding
5640 /// preallocated call.
5641 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5642   assert(cast<CallBase>(PreallocatedSetup)
5643                  ->getCalledFunction()
5644                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5645          "expected call_preallocated_setup Value");
5646   for (auto *U : PreallocatedSetup->users()) {
5647     auto *UseCall = cast<CallBase>(U);
5648     const Function *Fn = UseCall->getCalledFunction();
5649     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5650       return UseCall;
5651     }
5652   }
5653   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5654 }
5655 
5656 /// Lower the call to the specified intrinsic function.
5657 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5658                                              unsigned Intrinsic) {
5659   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5660   SDLoc sdl = getCurSDLoc();
5661   DebugLoc dl = getCurDebugLoc();
5662   SDValue Res;
5663 
5664   switch (Intrinsic) {
5665   default:
5666     // By default, turn this into a target intrinsic node.
5667     visitTargetIntrinsic(I, Intrinsic);
5668     return;
5669   case Intrinsic::vscale: {
5670     match(&I, m_VScale(DAG.getDataLayout()));
5671     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5672     setValue(&I,
5673              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5674     return;
5675   }
5676   case Intrinsic::vastart:  visitVAStart(I); return;
5677   case Intrinsic::vaend:    visitVAEnd(I); return;
5678   case Intrinsic::vacopy:   visitVACopy(I); return;
5679   case Intrinsic::returnaddress:
5680     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5681                              TLI.getPointerTy(DAG.getDataLayout()),
5682                              getValue(I.getArgOperand(0))));
5683     return;
5684   case Intrinsic::addressofreturnaddress:
5685     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5686                              TLI.getPointerTy(DAG.getDataLayout())));
5687     return;
5688   case Intrinsic::sponentry:
5689     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5690                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5691     return;
5692   case Intrinsic::frameaddress:
5693     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5694                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5695                              getValue(I.getArgOperand(0))));
5696     return;
5697   case Intrinsic::read_register: {
5698     Value *Reg = I.getArgOperand(0);
5699     SDValue Chain = getRoot();
5700     SDValue RegName =
5701         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5702     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5703     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5704       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5705     setValue(&I, Res);
5706     DAG.setRoot(Res.getValue(1));
5707     return;
5708   }
5709   case Intrinsic::write_register: {
5710     Value *Reg = I.getArgOperand(0);
5711     Value *RegValue = I.getArgOperand(1);
5712     SDValue Chain = getRoot();
5713     SDValue RegName =
5714         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5715     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5716                             RegName, getValue(RegValue)));
5717     return;
5718   }
5719   case Intrinsic::memcpy: {
5720     const auto &MCI = cast<MemCpyInst>(I);
5721     SDValue Op1 = getValue(I.getArgOperand(0));
5722     SDValue Op2 = getValue(I.getArgOperand(1));
5723     SDValue Op3 = getValue(I.getArgOperand(2));
5724     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5725     Align DstAlign = MCI.getDestAlign().valueOrOne();
5726     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5727     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5728     bool isVol = MCI.isVolatile();
5729     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5730     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5731     // node.
5732     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5733     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5734                                /* AlwaysInline */ false, isTC,
5735                                MachinePointerInfo(I.getArgOperand(0)),
5736                                MachinePointerInfo(I.getArgOperand(1)));
5737     updateDAGForMaybeTailCall(MC);
5738     return;
5739   }
5740   case Intrinsic::memcpy_inline: {
5741     const auto &MCI = cast<MemCpyInlineInst>(I);
5742     SDValue Dst = getValue(I.getArgOperand(0));
5743     SDValue Src = getValue(I.getArgOperand(1));
5744     SDValue Size = getValue(I.getArgOperand(2));
5745     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5746     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5747     Align DstAlign = MCI.getDestAlign().valueOrOne();
5748     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5749     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5750     bool isVol = MCI.isVolatile();
5751     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5752     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5753     // node.
5754     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5755                                /* AlwaysInline */ true, isTC,
5756                                MachinePointerInfo(I.getArgOperand(0)),
5757                                MachinePointerInfo(I.getArgOperand(1)));
5758     updateDAGForMaybeTailCall(MC);
5759     return;
5760   }
5761   case Intrinsic::memset: {
5762     const auto &MSI = cast<MemSetInst>(I);
5763     SDValue Op1 = getValue(I.getArgOperand(0));
5764     SDValue Op2 = getValue(I.getArgOperand(1));
5765     SDValue Op3 = getValue(I.getArgOperand(2));
5766     // @llvm.memset defines 0 and 1 to both mean no alignment.
5767     Align Alignment = MSI.getDestAlign().valueOrOne();
5768     bool isVol = MSI.isVolatile();
5769     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5770     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5771     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5772                                MachinePointerInfo(I.getArgOperand(0)));
5773     updateDAGForMaybeTailCall(MS);
5774     return;
5775   }
5776   case Intrinsic::memmove: {
5777     const auto &MMI = cast<MemMoveInst>(I);
5778     SDValue Op1 = getValue(I.getArgOperand(0));
5779     SDValue Op2 = getValue(I.getArgOperand(1));
5780     SDValue Op3 = getValue(I.getArgOperand(2));
5781     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5782     Align DstAlign = MMI.getDestAlign().valueOrOne();
5783     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5784     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5785     bool isVol = MMI.isVolatile();
5786     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5787     // FIXME: Support passing different dest/src alignments to the memmove DAG
5788     // node.
5789     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5790     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5791                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5792                                 MachinePointerInfo(I.getArgOperand(1)));
5793     updateDAGForMaybeTailCall(MM);
5794     return;
5795   }
5796   case Intrinsic::memcpy_element_unordered_atomic: {
5797     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5798     SDValue Dst = getValue(MI.getRawDest());
5799     SDValue Src = getValue(MI.getRawSource());
5800     SDValue Length = getValue(MI.getLength());
5801 
5802     unsigned DstAlign = MI.getDestAlignment();
5803     unsigned SrcAlign = MI.getSourceAlignment();
5804     Type *LengthTy = MI.getLength()->getType();
5805     unsigned ElemSz = MI.getElementSizeInBytes();
5806     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5807     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5808                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5809                                      MachinePointerInfo(MI.getRawDest()),
5810                                      MachinePointerInfo(MI.getRawSource()));
5811     updateDAGForMaybeTailCall(MC);
5812     return;
5813   }
5814   case Intrinsic::memmove_element_unordered_atomic: {
5815     auto &MI = cast<AtomicMemMoveInst>(I);
5816     SDValue Dst = getValue(MI.getRawDest());
5817     SDValue Src = getValue(MI.getRawSource());
5818     SDValue Length = getValue(MI.getLength());
5819 
5820     unsigned DstAlign = MI.getDestAlignment();
5821     unsigned SrcAlign = MI.getSourceAlignment();
5822     Type *LengthTy = MI.getLength()->getType();
5823     unsigned ElemSz = MI.getElementSizeInBytes();
5824     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5825     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5826                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5827                                       MachinePointerInfo(MI.getRawDest()),
5828                                       MachinePointerInfo(MI.getRawSource()));
5829     updateDAGForMaybeTailCall(MC);
5830     return;
5831   }
5832   case Intrinsic::memset_element_unordered_atomic: {
5833     auto &MI = cast<AtomicMemSetInst>(I);
5834     SDValue Dst = getValue(MI.getRawDest());
5835     SDValue Val = getValue(MI.getValue());
5836     SDValue Length = getValue(MI.getLength());
5837 
5838     unsigned DstAlign = MI.getDestAlignment();
5839     Type *LengthTy = MI.getLength()->getType();
5840     unsigned ElemSz = MI.getElementSizeInBytes();
5841     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5842     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5843                                      LengthTy, ElemSz, isTC,
5844                                      MachinePointerInfo(MI.getRawDest()));
5845     updateDAGForMaybeTailCall(MC);
5846     return;
5847   }
5848   case Intrinsic::call_preallocated_setup: {
5849     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5850     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5851     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5852                               getRoot(), SrcValue);
5853     setValue(&I, Res);
5854     DAG.setRoot(Res);
5855     return;
5856   }
5857   case Intrinsic::call_preallocated_arg: {
5858     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5859     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5860     SDValue Ops[3];
5861     Ops[0] = getRoot();
5862     Ops[1] = SrcValue;
5863     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5864                                    MVT::i32); // arg index
5865     SDValue Res = DAG.getNode(
5866         ISD::PREALLOCATED_ARG, sdl,
5867         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5868     setValue(&I, Res);
5869     DAG.setRoot(Res.getValue(1));
5870     return;
5871   }
5872   case Intrinsic::dbg_addr:
5873   case Intrinsic::dbg_declare: {
5874     const auto &DI = cast<DbgVariableIntrinsic>(I);
5875     DILocalVariable *Variable = DI.getVariable();
5876     DIExpression *Expression = DI.getExpression();
5877     dropDanglingDebugInfo(Variable, Expression);
5878     assert(Variable && "Missing variable");
5879     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5880                       << "\n");
5881     // Check if address has undef value.
5882     const Value *Address = DI.getVariableLocation();
5883     if (!Address || isa<UndefValue>(Address) ||
5884         (Address->use_empty() && !isa<Argument>(Address))) {
5885       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5886                         << " (bad/undef/unused-arg address)\n");
5887       return;
5888     }
5889 
5890     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5891 
5892     // Check if this variable can be described by a frame index, typically
5893     // either as a static alloca or a byval parameter.
5894     int FI = std::numeric_limits<int>::max();
5895     if (const auto *AI =
5896             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5897       if (AI->isStaticAlloca()) {
5898         auto I = FuncInfo.StaticAllocaMap.find(AI);
5899         if (I != FuncInfo.StaticAllocaMap.end())
5900           FI = I->second;
5901       }
5902     } else if (const auto *Arg = dyn_cast<Argument>(
5903                    Address->stripInBoundsConstantOffsets())) {
5904       FI = FuncInfo.getArgumentFrameIndex(Arg);
5905     }
5906 
5907     // llvm.dbg.addr is control dependent and always generates indirect
5908     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5909     // the MachineFunction variable table.
5910     if (FI != std::numeric_limits<int>::max()) {
5911       if (Intrinsic == Intrinsic::dbg_addr) {
5912         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5913             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5914         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5915       } else {
5916         LLVM_DEBUG(dbgs() << "Skipping " << DI
5917                           << " (variable info stashed in MF side table)\n");
5918       }
5919       return;
5920     }
5921 
5922     SDValue &N = NodeMap[Address];
5923     if (!N.getNode() && isa<Argument>(Address))
5924       // Check unused arguments map.
5925       N = UnusedArgNodeMap[Address];
5926     SDDbgValue *SDV;
5927     if (N.getNode()) {
5928       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5929         Address = BCI->getOperand(0);
5930       // Parameters are handled specially.
5931       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5932       if (isParameter && FINode) {
5933         // Byval parameter. We have a frame index at this point.
5934         SDV =
5935             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5936                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5937       } else if (isa<Argument>(Address)) {
5938         // Address is an argument, so try to emit its dbg value using
5939         // virtual register info from the FuncInfo.ValueMap.
5940         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5941         return;
5942       } else {
5943         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5944                               true, dl, SDNodeOrder);
5945       }
5946       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5947     } else {
5948       // If Address is an argument then try to emit its dbg value using
5949       // virtual register info from the FuncInfo.ValueMap.
5950       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5951                                     N)) {
5952         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5953                           << " (could not emit func-arg dbg_value)\n");
5954       }
5955     }
5956     return;
5957   }
5958   case Intrinsic::dbg_label: {
5959     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5960     DILabel *Label = DI.getLabel();
5961     assert(Label && "Missing label");
5962 
5963     SDDbgLabel *SDV;
5964     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5965     DAG.AddDbgLabel(SDV);
5966     return;
5967   }
5968   case Intrinsic::dbg_value: {
5969     const DbgValueInst &DI = cast<DbgValueInst>(I);
5970     assert(DI.getVariable() && "Missing variable");
5971 
5972     DILocalVariable *Variable = DI.getVariable();
5973     DIExpression *Expression = DI.getExpression();
5974     dropDanglingDebugInfo(Variable, Expression);
5975     const Value *V = DI.getValue();
5976     if (!V)
5977       return;
5978 
5979     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5980         SDNodeOrder))
5981       return;
5982 
5983     // TODO: Dangling debug info will eventually either be resolved or produce
5984     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5985     // between the original dbg.value location and its resolved DBG_VALUE, which
5986     // we should ideally fill with an extra Undef DBG_VALUE.
5987 
5988     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5989     return;
5990   }
5991 
5992   case Intrinsic::eh_typeid_for: {
5993     // Find the type id for the given typeinfo.
5994     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5995     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5996     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5997     setValue(&I, Res);
5998     return;
5999   }
6000 
6001   case Intrinsic::eh_return_i32:
6002   case Intrinsic::eh_return_i64:
6003     DAG.getMachineFunction().setCallsEHReturn(true);
6004     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6005                             MVT::Other,
6006                             getControlRoot(),
6007                             getValue(I.getArgOperand(0)),
6008                             getValue(I.getArgOperand(1))));
6009     return;
6010   case Intrinsic::eh_unwind_init:
6011     DAG.getMachineFunction().setCallsUnwindInit(true);
6012     return;
6013   case Intrinsic::eh_dwarf_cfa:
6014     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6015                              TLI.getPointerTy(DAG.getDataLayout()),
6016                              getValue(I.getArgOperand(0))));
6017     return;
6018   case Intrinsic::eh_sjlj_callsite: {
6019     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6020     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6021     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6022     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6023 
6024     MMI.setCurrentCallSite(CI->getZExtValue());
6025     return;
6026   }
6027   case Intrinsic::eh_sjlj_functioncontext: {
6028     // Get and store the index of the function context.
6029     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6030     AllocaInst *FnCtx =
6031       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6032     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6033     MFI.setFunctionContextIndex(FI);
6034     return;
6035   }
6036   case Intrinsic::eh_sjlj_setjmp: {
6037     SDValue Ops[2];
6038     Ops[0] = getRoot();
6039     Ops[1] = getValue(I.getArgOperand(0));
6040     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6041                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6042     setValue(&I, Op.getValue(0));
6043     DAG.setRoot(Op.getValue(1));
6044     return;
6045   }
6046   case Intrinsic::eh_sjlj_longjmp:
6047     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6048                             getRoot(), getValue(I.getArgOperand(0))));
6049     return;
6050   case Intrinsic::eh_sjlj_setup_dispatch:
6051     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6052                             getRoot()));
6053     return;
6054   case Intrinsic::masked_gather:
6055     visitMaskedGather(I);
6056     return;
6057   case Intrinsic::masked_load:
6058     visitMaskedLoad(I);
6059     return;
6060   case Intrinsic::masked_scatter:
6061     visitMaskedScatter(I);
6062     return;
6063   case Intrinsic::masked_store:
6064     visitMaskedStore(I);
6065     return;
6066   case Intrinsic::masked_expandload:
6067     visitMaskedLoad(I, true /* IsExpanding */);
6068     return;
6069   case Intrinsic::masked_compressstore:
6070     visitMaskedStore(I, true /* IsCompressing */);
6071     return;
6072   case Intrinsic::powi:
6073     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6074                             getValue(I.getArgOperand(1)), DAG));
6075     return;
6076   case Intrinsic::log:
6077     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6078     return;
6079   case Intrinsic::log2:
6080     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6081     return;
6082   case Intrinsic::log10:
6083     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6084     return;
6085   case Intrinsic::exp:
6086     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6087     return;
6088   case Intrinsic::exp2:
6089     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6090     return;
6091   case Intrinsic::pow:
6092     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6093                            getValue(I.getArgOperand(1)), DAG, TLI));
6094     return;
6095   case Intrinsic::sqrt:
6096   case Intrinsic::fabs:
6097   case Intrinsic::sin:
6098   case Intrinsic::cos:
6099   case Intrinsic::floor:
6100   case Intrinsic::ceil:
6101   case Intrinsic::trunc:
6102   case Intrinsic::rint:
6103   case Intrinsic::nearbyint:
6104   case Intrinsic::round:
6105   case Intrinsic::roundeven:
6106   case Intrinsic::canonicalize: {
6107     unsigned Opcode;
6108     switch (Intrinsic) {
6109     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6110     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6111     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6112     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6113     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6114     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6115     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6116     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6117     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6118     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6119     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6120     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6121     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6122     }
6123 
6124     setValue(&I, DAG.getNode(Opcode, sdl,
6125                              getValue(I.getArgOperand(0)).getValueType(),
6126                              getValue(I.getArgOperand(0))));
6127     return;
6128   }
6129   case Intrinsic::lround:
6130   case Intrinsic::llround:
6131   case Intrinsic::lrint:
6132   case Intrinsic::llrint: {
6133     unsigned Opcode;
6134     switch (Intrinsic) {
6135     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6136     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6137     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6138     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6139     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6140     }
6141 
6142     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6143     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6144                              getValue(I.getArgOperand(0))));
6145     return;
6146   }
6147   case Intrinsic::minnum:
6148     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6149                              getValue(I.getArgOperand(0)).getValueType(),
6150                              getValue(I.getArgOperand(0)),
6151                              getValue(I.getArgOperand(1))));
6152     return;
6153   case Intrinsic::maxnum:
6154     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6155                              getValue(I.getArgOperand(0)).getValueType(),
6156                              getValue(I.getArgOperand(0)),
6157                              getValue(I.getArgOperand(1))));
6158     return;
6159   case Intrinsic::minimum:
6160     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6161                              getValue(I.getArgOperand(0)).getValueType(),
6162                              getValue(I.getArgOperand(0)),
6163                              getValue(I.getArgOperand(1))));
6164     return;
6165   case Intrinsic::maximum:
6166     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6167                              getValue(I.getArgOperand(0)).getValueType(),
6168                              getValue(I.getArgOperand(0)),
6169                              getValue(I.getArgOperand(1))));
6170     return;
6171   case Intrinsic::copysign:
6172     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6173                              getValue(I.getArgOperand(0)).getValueType(),
6174                              getValue(I.getArgOperand(0)),
6175                              getValue(I.getArgOperand(1))));
6176     return;
6177   case Intrinsic::fma:
6178     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6179                              getValue(I.getArgOperand(0)).getValueType(),
6180                              getValue(I.getArgOperand(0)),
6181                              getValue(I.getArgOperand(1)),
6182                              getValue(I.getArgOperand(2))));
6183     return;
6184 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6185   case Intrinsic::INTRINSIC:
6186 #include "llvm/IR/ConstrainedOps.def"
6187     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6188     return;
6189   case Intrinsic::fmuladd: {
6190     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6191     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6192         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6193       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6194                                getValue(I.getArgOperand(0)).getValueType(),
6195                                getValue(I.getArgOperand(0)),
6196                                getValue(I.getArgOperand(1)),
6197                                getValue(I.getArgOperand(2))));
6198     } else {
6199       // TODO: Intrinsic calls should have fast-math-flags.
6200       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6201                                 getValue(I.getArgOperand(0)).getValueType(),
6202                                 getValue(I.getArgOperand(0)),
6203                                 getValue(I.getArgOperand(1)));
6204       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6205                                 getValue(I.getArgOperand(0)).getValueType(),
6206                                 Mul,
6207                                 getValue(I.getArgOperand(2)));
6208       setValue(&I, Add);
6209     }
6210     return;
6211   }
6212   case Intrinsic::convert_to_fp16:
6213     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6214                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6215                                          getValue(I.getArgOperand(0)),
6216                                          DAG.getTargetConstant(0, sdl,
6217                                                                MVT::i32))));
6218     return;
6219   case Intrinsic::convert_from_fp16:
6220     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6221                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6222                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6223                                          getValue(I.getArgOperand(0)))));
6224     return;
6225   case Intrinsic::pcmarker: {
6226     SDValue Tmp = getValue(I.getArgOperand(0));
6227     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6228     return;
6229   }
6230   case Intrinsic::readcyclecounter: {
6231     SDValue Op = getRoot();
6232     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6233                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6234     setValue(&I, Res);
6235     DAG.setRoot(Res.getValue(1));
6236     return;
6237   }
6238   case Intrinsic::bitreverse:
6239     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6240                              getValue(I.getArgOperand(0)).getValueType(),
6241                              getValue(I.getArgOperand(0))));
6242     return;
6243   case Intrinsic::bswap:
6244     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6245                              getValue(I.getArgOperand(0)).getValueType(),
6246                              getValue(I.getArgOperand(0))));
6247     return;
6248   case Intrinsic::cttz: {
6249     SDValue Arg = getValue(I.getArgOperand(0));
6250     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6251     EVT Ty = Arg.getValueType();
6252     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6253                              sdl, Ty, Arg));
6254     return;
6255   }
6256   case Intrinsic::ctlz: {
6257     SDValue Arg = getValue(I.getArgOperand(0));
6258     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6259     EVT Ty = Arg.getValueType();
6260     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6261                              sdl, Ty, Arg));
6262     return;
6263   }
6264   case Intrinsic::ctpop: {
6265     SDValue Arg = getValue(I.getArgOperand(0));
6266     EVT Ty = Arg.getValueType();
6267     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6268     return;
6269   }
6270   case Intrinsic::fshl:
6271   case Intrinsic::fshr: {
6272     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6273     SDValue X = getValue(I.getArgOperand(0));
6274     SDValue Y = getValue(I.getArgOperand(1));
6275     SDValue Z = getValue(I.getArgOperand(2));
6276     EVT VT = X.getValueType();
6277     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6278     SDValue Zero = DAG.getConstant(0, sdl, VT);
6279     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6280 
6281     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6282     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6283       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6284       return;
6285     }
6286 
6287     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6288     // avoid the select that is necessary in the general case to filter out
6289     // the 0-shift possibility that leads to UB.
6290     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6291       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6292       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6293         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6294         return;
6295       }
6296 
6297       // Some targets only rotate one way. Try the opposite direction.
6298       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6299       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6300         // Negate the shift amount because it is safe to ignore the high bits.
6301         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6302         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6303         return;
6304       }
6305 
6306       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6307       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6308       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6309       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6310       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6311       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6312       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6313       return;
6314     }
6315 
6316     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6317     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6318     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6319     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6320     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6321     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6322 
6323     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6324     // and that is undefined. We must compare and select to avoid UB.
6325     EVT CCVT = MVT::i1;
6326     if (VT.isVector())
6327       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6328 
6329     // For fshl, 0-shift returns the 1st arg (X).
6330     // For fshr, 0-shift returns the 2nd arg (Y).
6331     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6332     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6333     return;
6334   }
6335   case Intrinsic::sadd_sat: {
6336     SDValue Op1 = getValue(I.getArgOperand(0));
6337     SDValue Op2 = getValue(I.getArgOperand(1));
6338     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6339     return;
6340   }
6341   case Intrinsic::uadd_sat: {
6342     SDValue Op1 = getValue(I.getArgOperand(0));
6343     SDValue Op2 = getValue(I.getArgOperand(1));
6344     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6345     return;
6346   }
6347   case Intrinsic::ssub_sat: {
6348     SDValue Op1 = getValue(I.getArgOperand(0));
6349     SDValue Op2 = getValue(I.getArgOperand(1));
6350     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6351     return;
6352   }
6353   case Intrinsic::usub_sat: {
6354     SDValue Op1 = getValue(I.getArgOperand(0));
6355     SDValue Op2 = getValue(I.getArgOperand(1));
6356     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6357     return;
6358   }
6359   case Intrinsic::smul_fix:
6360   case Intrinsic::umul_fix:
6361   case Intrinsic::smul_fix_sat:
6362   case Intrinsic::umul_fix_sat: {
6363     SDValue Op1 = getValue(I.getArgOperand(0));
6364     SDValue Op2 = getValue(I.getArgOperand(1));
6365     SDValue Op3 = getValue(I.getArgOperand(2));
6366     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6367                              Op1.getValueType(), Op1, Op2, Op3));
6368     return;
6369   }
6370   case Intrinsic::sdiv_fix:
6371   case Intrinsic::udiv_fix:
6372   case Intrinsic::sdiv_fix_sat:
6373   case Intrinsic::udiv_fix_sat: {
6374     SDValue Op1 = getValue(I.getArgOperand(0));
6375     SDValue Op2 = getValue(I.getArgOperand(1));
6376     SDValue Op3 = getValue(I.getArgOperand(2));
6377     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6378                               Op1, Op2, Op3, DAG, TLI));
6379     return;
6380   }
6381   case Intrinsic::stacksave: {
6382     SDValue Op = getRoot();
6383     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6384     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6385     setValue(&I, Res);
6386     DAG.setRoot(Res.getValue(1));
6387     return;
6388   }
6389   case Intrinsic::stackrestore:
6390     Res = getValue(I.getArgOperand(0));
6391     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6392     return;
6393   case Intrinsic::get_dynamic_area_offset: {
6394     SDValue Op = getRoot();
6395     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6396     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6397     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6398     // target.
6399     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6400       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6401                          " intrinsic!");
6402     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6403                       Op);
6404     DAG.setRoot(Op);
6405     setValue(&I, Res);
6406     return;
6407   }
6408   case Intrinsic::stackguard: {
6409     MachineFunction &MF = DAG.getMachineFunction();
6410     const Module &M = *MF.getFunction().getParent();
6411     SDValue Chain = getRoot();
6412     if (TLI.useLoadStackGuardNode()) {
6413       Res = getLoadStackGuard(DAG, sdl, Chain);
6414     } else {
6415       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6416       const Value *Global = TLI.getSDagStackGuard(M);
6417       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6418       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6419                         MachinePointerInfo(Global, 0), Align,
6420                         MachineMemOperand::MOVolatile);
6421     }
6422     if (TLI.useStackGuardXorFP())
6423       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6424     DAG.setRoot(Chain);
6425     setValue(&I, Res);
6426     return;
6427   }
6428   case Intrinsic::stackprotector: {
6429     // Emit code into the DAG to store the stack guard onto the stack.
6430     MachineFunction &MF = DAG.getMachineFunction();
6431     MachineFrameInfo &MFI = MF.getFrameInfo();
6432     SDValue Src, Chain = getRoot();
6433 
6434     if (TLI.useLoadStackGuardNode())
6435       Src = getLoadStackGuard(DAG, sdl, Chain);
6436     else
6437       Src = getValue(I.getArgOperand(0));   // The guard's value.
6438 
6439     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6440 
6441     int FI = FuncInfo.StaticAllocaMap[Slot];
6442     MFI.setStackProtectorIndex(FI);
6443     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6444 
6445     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6446 
6447     // Store the stack protector onto the stack.
6448     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6449                                                  DAG.getMachineFunction(), FI),
6450                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6451     setValue(&I, Res);
6452     DAG.setRoot(Res);
6453     return;
6454   }
6455   case Intrinsic::objectsize:
6456     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6457 
6458   case Intrinsic::is_constant:
6459     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6460 
6461   case Intrinsic::annotation:
6462   case Intrinsic::ptr_annotation:
6463   case Intrinsic::launder_invariant_group:
6464   case Intrinsic::strip_invariant_group:
6465     // Drop the intrinsic, but forward the value
6466     setValue(&I, getValue(I.getOperand(0)));
6467     return;
6468   case Intrinsic::assume:
6469   case Intrinsic::var_annotation:
6470   case Intrinsic::sideeffect:
6471     // Discard annotate attributes, assumptions, and artificial side-effects.
6472     return;
6473 
6474   case Intrinsic::codeview_annotation: {
6475     // Emit a label associated with this metadata.
6476     MachineFunction &MF = DAG.getMachineFunction();
6477     MCSymbol *Label =
6478         MF.getMMI().getContext().createTempSymbol("annotation", true);
6479     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6480     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6481     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6482     DAG.setRoot(Res);
6483     return;
6484   }
6485 
6486   case Intrinsic::init_trampoline: {
6487     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6488 
6489     SDValue Ops[6];
6490     Ops[0] = getRoot();
6491     Ops[1] = getValue(I.getArgOperand(0));
6492     Ops[2] = getValue(I.getArgOperand(1));
6493     Ops[3] = getValue(I.getArgOperand(2));
6494     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6495     Ops[5] = DAG.getSrcValue(F);
6496 
6497     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6498 
6499     DAG.setRoot(Res);
6500     return;
6501   }
6502   case Intrinsic::adjust_trampoline:
6503     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6504                              TLI.getPointerTy(DAG.getDataLayout()),
6505                              getValue(I.getArgOperand(0))));
6506     return;
6507   case Intrinsic::gcroot: {
6508     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6509            "only valid in functions with gc specified, enforced by Verifier");
6510     assert(GFI && "implied by previous");
6511     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6512     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6513 
6514     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6515     GFI->addStackRoot(FI->getIndex(), TypeMap);
6516     return;
6517   }
6518   case Intrinsic::gcread:
6519   case Intrinsic::gcwrite:
6520     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6521   case Intrinsic::flt_rounds:
6522     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6523     setValue(&I, Res);
6524     DAG.setRoot(Res.getValue(1));
6525     return;
6526 
6527   case Intrinsic::expect:
6528     // Just replace __builtin_expect(exp, c) with EXP.
6529     setValue(&I, getValue(I.getArgOperand(0)));
6530     return;
6531 
6532   case Intrinsic::debugtrap:
6533   case Intrinsic::trap: {
6534     StringRef TrapFuncName =
6535         I.getAttributes()
6536             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6537             .getValueAsString();
6538     if (TrapFuncName.empty()) {
6539       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6540         ISD::TRAP : ISD::DEBUGTRAP;
6541       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6542       return;
6543     }
6544     TargetLowering::ArgListTy Args;
6545 
6546     TargetLowering::CallLoweringInfo CLI(DAG);
6547     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6548         CallingConv::C, I.getType(),
6549         DAG.getExternalSymbol(TrapFuncName.data(),
6550                               TLI.getPointerTy(DAG.getDataLayout())),
6551         std::move(Args));
6552 
6553     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6554     DAG.setRoot(Result.second);
6555     return;
6556   }
6557 
6558   case Intrinsic::uadd_with_overflow:
6559   case Intrinsic::sadd_with_overflow:
6560   case Intrinsic::usub_with_overflow:
6561   case Intrinsic::ssub_with_overflow:
6562   case Intrinsic::umul_with_overflow:
6563   case Intrinsic::smul_with_overflow: {
6564     ISD::NodeType Op;
6565     switch (Intrinsic) {
6566     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6567     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6568     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6569     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6570     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6571     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6572     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6573     }
6574     SDValue Op1 = getValue(I.getArgOperand(0));
6575     SDValue Op2 = getValue(I.getArgOperand(1));
6576 
6577     EVT ResultVT = Op1.getValueType();
6578     EVT OverflowVT = MVT::i1;
6579     if (ResultVT.isVector())
6580       OverflowVT = EVT::getVectorVT(
6581           *Context, OverflowVT, ResultVT.getVectorNumElements());
6582 
6583     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6584     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6585     return;
6586   }
6587   case Intrinsic::prefetch: {
6588     SDValue Ops[5];
6589     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6590     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6591     Ops[0] = DAG.getRoot();
6592     Ops[1] = getValue(I.getArgOperand(0));
6593     Ops[2] = getValue(I.getArgOperand(1));
6594     Ops[3] = getValue(I.getArgOperand(2));
6595     Ops[4] = getValue(I.getArgOperand(3));
6596     SDValue Result = DAG.getMemIntrinsicNode(
6597         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6598         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6599         /* align */ None, Flags);
6600 
6601     // Chain the prefetch in parallell with any pending loads, to stay out of
6602     // the way of later optimizations.
6603     PendingLoads.push_back(Result);
6604     Result = getRoot();
6605     DAG.setRoot(Result);
6606     return;
6607   }
6608   case Intrinsic::lifetime_start:
6609   case Intrinsic::lifetime_end: {
6610     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6611     // Stack coloring is not enabled in O0, discard region information.
6612     if (TM.getOptLevel() == CodeGenOpt::None)
6613       return;
6614 
6615     const int64_t ObjectSize =
6616         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6617     Value *const ObjectPtr = I.getArgOperand(1);
6618     SmallVector<const Value *, 4> Allocas;
6619     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6620 
6621     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6622            E = Allocas.end(); Object != E; ++Object) {
6623       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6624 
6625       // Could not find an Alloca.
6626       if (!LifetimeObject)
6627         continue;
6628 
6629       // First check that the Alloca is static, otherwise it won't have a
6630       // valid frame index.
6631       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6632       if (SI == FuncInfo.StaticAllocaMap.end())
6633         return;
6634 
6635       const int FrameIndex = SI->second;
6636       int64_t Offset;
6637       if (GetPointerBaseWithConstantOffset(
6638               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6639         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6640       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6641                                 Offset);
6642       DAG.setRoot(Res);
6643     }
6644     return;
6645   }
6646   case Intrinsic::invariant_start:
6647     // Discard region information.
6648     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6649     return;
6650   case Intrinsic::invariant_end:
6651     // Discard region information.
6652     return;
6653   case Intrinsic::clear_cache:
6654     /// FunctionName may be null.
6655     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6656       lowerCallToExternalSymbol(I, FunctionName);
6657     return;
6658   case Intrinsic::donothing:
6659     // ignore
6660     return;
6661   case Intrinsic::experimental_stackmap:
6662     visitStackmap(I);
6663     return;
6664   case Intrinsic::experimental_patchpoint_void:
6665   case Intrinsic::experimental_patchpoint_i64:
6666     visitPatchpoint(I);
6667     return;
6668   case Intrinsic::experimental_gc_statepoint:
6669     LowerStatepoint(cast<GCStatepointInst>(I));
6670     return;
6671   case Intrinsic::experimental_gc_result:
6672     visitGCResult(cast<GCResultInst>(I));
6673     return;
6674   case Intrinsic::experimental_gc_relocate:
6675     visitGCRelocate(cast<GCRelocateInst>(I));
6676     return;
6677   case Intrinsic::instrprof_increment:
6678     llvm_unreachable("instrprof failed to lower an increment");
6679   case Intrinsic::instrprof_value_profile:
6680     llvm_unreachable("instrprof failed to lower a value profiling call");
6681   case Intrinsic::localescape: {
6682     MachineFunction &MF = DAG.getMachineFunction();
6683     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6684 
6685     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6686     // is the same on all targets.
6687     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6688       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6689       if (isa<ConstantPointerNull>(Arg))
6690         continue; // Skip null pointers. They represent a hole in index space.
6691       AllocaInst *Slot = cast<AllocaInst>(Arg);
6692       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6693              "can only escape static allocas");
6694       int FI = FuncInfo.StaticAllocaMap[Slot];
6695       MCSymbol *FrameAllocSym =
6696           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6697               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6698       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6699               TII->get(TargetOpcode::LOCAL_ESCAPE))
6700           .addSym(FrameAllocSym)
6701           .addFrameIndex(FI);
6702     }
6703 
6704     return;
6705   }
6706 
6707   case Intrinsic::localrecover: {
6708     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6709     MachineFunction &MF = DAG.getMachineFunction();
6710 
6711     // Get the symbol that defines the frame offset.
6712     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6713     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6714     unsigned IdxVal =
6715         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6716     MCSymbol *FrameAllocSym =
6717         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6718             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6719 
6720     Value *FP = I.getArgOperand(1);
6721     SDValue FPVal = getValue(FP);
6722     EVT PtrVT = FPVal.getValueType();
6723 
6724     // Create a MCSymbol for the label to avoid any target lowering
6725     // that would make this PC relative.
6726     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6727     SDValue OffsetVal =
6728         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6729 
6730     // Add the offset to the FP.
6731     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6732     setValue(&I, Add);
6733 
6734     return;
6735   }
6736 
6737   case Intrinsic::eh_exceptionpointer:
6738   case Intrinsic::eh_exceptioncode: {
6739     // Get the exception pointer vreg, copy from it, and resize it to fit.
6740     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6741     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6742     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6743     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6744     SDValue N =
6745         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6746     if (Intrinsic == Intrinsic::eh_exceptioncode)
6747       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6748     setValue(&I, N);
6749     return;
6750   }
6751   case Intrinsic::xray_customevent: {
6752     // Here we want to make sure that the intrinsic behaves as if it has a
6753     // specific calling convention, and only for x86_64.
6754     // FIXME: Support other platforms later.
6755     const auto &Triple = DAG.getTarget().getTargetTriple();
6756     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6757       return;
6758 
6759     SDLoc DL = getCurSDLoc();
6760     SmallVector<SDValue, 8> Ops;
6761 
6762     // We want to say that we always want the arguments in registers.
6763     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6764     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6765     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6766     SDValue Chain = getRoot();
6767     Ops.push_back(LogEntryVal);
6768     Ops.push_back(StrSizeVal);
6769     Ops.push_back(Chain);
6770 
6771     // We need to enforce the calling convention for the callsite, so that
6772     // argument ordering is enforced correctly, and that register allocation can
6773     // see that some registers may be assumed clobbered and have to preserve
6774     // them across calls to the intrinsic.
6775     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6776                                            DL, NodeTys, Ops);
6777     SDValue patchableNode = SDValue(MN, 0);
6778     DAG.setRoot(patchableNode);
6779     setValue(&I, patchableNode);
6780     return;
6781   }
6782   case Intrinsic::xray_typedevent: {
6783     // Here we want to make sure that the intrinsic behaves as if it has a
6784     // specific calling convention, and only for x86_64.
6785     // FIXME: Support other platforms later.
6786     const auto &Triple = DAG.getTarget().getTargetTriple();
6787     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6788       return;
6789 
6790     SDLoc DL = getCurSDLoc();
6791     SmallVector<SDValue, 8> Ops;
6792 
6793     // We want to say that we always want the arguments in registers.
6794     // It's unclear to me how manipulating the selection DAG here forces callers
6795     // to provide arguments in registers instead of on the stack.
6796     SDValue LogTypeId = getValue(I.getArgOperand(0));
6797     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6798     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6799     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6800     SDValue Chain = getRoot();
6801     Ops.push_back(LogTypeId);
6802     Ops.push_back(LogEntryVal);
6803     Ops.push_back(StrSizeVal);
6804     Ops.push_back(Chain);
6805 
6806     // We need to enforce the calling convention for the callsite, so that
6807     // argument ordering is enforced correctly, and that register allocation can
6808     // see that some registers may be assumed clobbered and have to preserve
6809     // them across calls to the intrinsic.
6810     MachineSDNode *MN = DAG.getMachineNode(
6811         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6812     SDValue patchableNode = SDValue(MN, 0);
6813     DAG.setRoot(patchableNode);
6814     setValue(&I, patchableNode);
6815     return;
6816   }
6817   case Intrinsic::experimental_deoptimize:
6818     LowerDeoptimizeCall(&I);
6819     return;
6820 
6821   case Intrinsic::experimental_vector_reduce_v2_fadd:
6822   case Intrinsic::experimental_vector_reduce_v2_fmul:
6823   case Intrinsic::experimental_vector_reduce_add:
6824   case Intrinsic::experimental_vector_reduce_mul:
6825   case Intrinsic::experimental_vector_reduce_and:
6826   case Intrinsic::experimental_vector_reduce_or:
6827   case Intrinsic::experimental_vector_reduce_xor:
6828   case Intrinsic::experimental_vector_reduce_smax:
6829   case Intrinsic::experimental_vector_reduce_smin:
6830   case Intrinsic::experimental_vector_reduce_umax:
6831   case Intrinsic::experimental_vector_reduce_umin:
6832   case Intrinsic::experimental_vector_reduce_fmax:
6833   case Intrinsic::experimental_vector_reduce_fmin:
6834     visitVectorReduce(I, Intrinsic);
6835     return;
6836 
6837   case Intrinsic::icall_branch_funnel: {
6838     SmallVector<SDValue, 16> Ops;
6839     Ops.push_back(getValue(I.getArgOperand(0)));
6840 
6841     int64_t Offset;
6842     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6843         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6844     if (!Base)
6845       report_fatal_error(
6846           "llvm.icall.branch.funnel operand must be a GlobalValue");
6847     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6848 
6849     struct BranchFunnelTarget {
6850       int64_t Offset;
6851       SDValue Target;
6852     };
6853     SmallVector<BranchFunnelTarget, 8> Targets;
6854 
6855     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6856       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6857           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6858       if (ElemBase != Base)
6859         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6860                            "to the same GlobalValue");
6861 
6862       SDValue Val = getValue(I.getArgOperand(Op + 1));
6863       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6864       if (!GA)
6865         report_fatal_error(
6866             "llvm.icall.branch.funnel operand must be a GlobalValue");
6867       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6868                                      GA->getGlobal(), getCurSDLoc(),
6869                                      Val.getValueType(), GA->getOffset())});
6870     }
6871     llvm::sort(Targets,
6872                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6873                  return T1.Offset < T2.Offset;
6874                });
6875 
6876     for (auto &T : Targets) {
6877       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6878       Ops.push_back(T.Target);
6879     }
6880 
6881     Ops.push_back(DAG.getRoot()); // Chain
6882     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6883                                  getCurSDLoc(), MVT::Other, Ops),
6884               0);
6885     DAG.setRoot(N);
6886     setValue(&I, N);
6887     HasTailCall = true;
6888     return;
6889   }
6890 
6891   case Intrinsic::wasm_landingpad_index:
6892     // Information this intrinsic contained has been transferred to
6893     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6894     // delete it now.
6895     return;
6896 
6897   case Intrinsic::aarch64_settag:
6898   case Intrinsic::aarch64_settag_zero: {
6899     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6900     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6901     SDValue Val = TSI.EmitTargetCodeForSetTag(
6902         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6903         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6904         ZeroMemory);
6905     DAG.setRoot(Val);
6906     setValue(&I, Val);
6907     return;
6908   }
6909   case Intrinsic::ptrmask: {
6910     SDValue Ptr = getValue(I.getOperand(0));
6911     SDValue Const = getValue(I.getOperand(1));
6912 
6913     EVT PtrVT = Ptr.getValueType();
6914     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
6915                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
6916     return;
6917   }
6918   case Intrinsic::get_active_lane_mask: {
6919     auto DL = getCurSDLoc();
6920     SDValue Index = getValue(I.getOperand(0));
6921     SDValue BTC = getValue(I.getOperand(1));
6922     Type *ElementTy = I.getOperand(0)->getType();
6923     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6924     unsigned VecWidth = VT.getVectorNumElements();
6925 
6926     SmallVector<SDValue, 16> OpsBTC;
6927     SmallVector<SDValue, 16> OpsIndex;
6928     SmallVector<SDValue, 16> OpsStepConstants;
6929     for (unsigned i = 0; i < VecWidth; i++) {
6930       OpsBTC.push_back(BTC);
6931       OpsIndex.push_back(Index);
6932       OpsStepConstants.push_back(DAG.getConstant(i, DL, MVT::getVT(ElementTy)));
6933     }
6934 
6935     EVT CCVT = MVT::i1;
6936     CCVT = EVT::getVectorVT(I.getContext(), CCVT, VecWidth);
6937 
6938     auto VecTy = MVT::getVT(FixedVectorType::get(ElementTy, VecWidth));
6939     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
6940     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
6941     SDValue VectorInduction = DAG.getNode(
6942        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
6943     SDValue VectorBTC = DAG.getBuildVector(VecTy, DL, OpsBTC);
6944     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
6945                                  VectorBTC, ISD::CondCode::SETULE);
6946     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
6947                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
6948                              SetCC));
6949     return;
6950   }
6951   }
6952 }
6953 
6954 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6955     const ConstrainedFPIntrinsic &FPI) {
6956   SDLoc sdl = getCurSDLoc();
6957 
6958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6959   SmallVector<EVT, 4> ValueVTs;
6960   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6961   ValueVTs.push_back(MVT::Other); // Out chain
6962 
6963   // We do not need to serialize constrained FP intrinsics against
6964   // each other or against (nonvolatile) loads, so they can be
6965   // chained like loads.
6966   SDValue Chain = DAG.getRoot();
6967   SmallVector<SDValue, 4> Opers;
6968   Opers.push_back(Chain);
6969   if (FPI.isUnaryOp()) {
6970     Opers.push_back(getValue(FPI.getArgOperand(0)));
6971   } else if (FPI.isTernaryOp()) {
6972     Opers.push_back(getValue(FPI.getArgOperand(0)));
6973     Opers.push_back(getValue(FPI.getArgOperand(1)));
6974     Opers.push_back(getValue(FPI.getArgOperand(2)));
6975   } else {
6976     Opers.push_back(getValue(FPI.getArgOperand(0)));
6977     Opers.push_back(getValue(FPI.getArgOperand(1)));
6978   }
6979 
6980   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
6981     assert(Result.getNode()->getNumValues() == 2);
6982 
6983     // Push node to the appropriate list so that future instructions can be
6984     // chained up correctly.
6985     SDValue OutChain = Result.getValue(1);
6986     switch (EB) {
6987     case fp::ExceptionBehavior::ebIgnore:
6988       // The only reason why ebIgnore nodes still need to be chained is that
6989       // they might depend on the current rounding mode, and therefore must
6990       // not be moved across instruction that may change that mode.
6991       LLVM_FALLTHROUGH;
6992     case fp::ExceptionBehavior::ebMayTrap:
6993       // These must not be moved across calls or instructions that may change
6994       // floating-point exception masks.
6995       PendingConstrainedFP.push_back(OutChain);
6996       break;
6997     case fp::ExceptionBehavior::ebStrict:
6998       // These must not be moved across calls or instructions that may change
6999       // floating-point exception masks or read floating-point exception flags.
7000       // In addition, they cannot be optimized out even if unused.
7001       PendingConstrainedFPStrict.push_back(OutChain);
7002       break;
7003     }
7004   };
7005 
7006   SDVTList VTs = DAG.getVTList(ValueVTs);
7007   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7008 
7009   SDNodeFlags Flags;
7010   if (EB == fp::ExceptionBehavior::ebIgnore)
7011     Flags.setNoFPExcept(true);
7012 
7013   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7014     Flags.copyFMF(*FPOp);
7015 
7016   unsigned Opcode;
7017   switch (FPI.getIntrinsicID()) {
7018   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7019 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7020   case Intrinsic::INTRINSIC:                                                   \
7021     Opcode = ISD::STRICT_##DAGN;                                               \
7022     break;
7023 #include "llvm/IR/ConstrainedOps.def"
7024   case Intrinsic::experimental_constrained_fmuladd: {
7025     Opcode = ISD::STRICT_FMA;
7026     // Break fmuladd into fmul and fadd.
7027     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7028         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7029                                         ValueVTs[0])) {
7030       Opers.pop_back();
7031       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7032       pushOutChain(Mul, EB);
7033       Opcode = ISD::STRICT_FADD;
7034       Opers.clear();
7035       Opers.push_back(Mul.getValue(1));
7036       Opers.push_back(Mul.getValue(0));
7037       Opers.push_back(getValue(FPI.getArgOperand(2)));
7038     }
7039     break;
7040   }
7041   }
7042 
7043   // A few strict DAG nodes carry additional operands that are not
7044   // set up by the default code above.
7045   switch (Opcode) {
7046   default: break;
7047   case ISD::STRICT_FP_ROUND:
7048     Opers.push_back(
7049         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7050     break;
7051   case ISD::STRICT_FSETCC:
7052   case ISD::STRICT_FSETCCS: {
7053     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7054     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7055     break;
7056   }
7057   }
7058 
7059   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7060   pushOutChain(Result, EB);
7061 
7062   SDValue FPResult = Result.getValue(0);
7063   setValue(&FPI, FPResult);
7064 }
7065 
7066 std::pair<SDValue, SDValue>
7067 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7068                                     const BasicBlock *EHPadBB) {
7069   MachineFunction &MF = DAG.getMachineFunction();
7070   MachineModuleInfo &MMI = MF.getMMI();
7071   MCSymbol *BeginLabel = nullptr;
7072 
7073   if (EHPadBB) {
7074     // Insert a label before the invoke call to mark the try range.  This can be
7075     // used to detect deletion of the invoke via the MachineModuleInfo.
7076     BeginLabel = MMI.getContext().createTempSymbol();
7077 
7078     // For SjLj, keep track of which landing pads go with which invokes
7079     // so as to maintain the ordering of pads in the LSDA.
7080     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7081     if (CallSiteIndex) {
7082       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7083       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7084 
7085       // Now that the call site is handled, stop tracking it.
7086       MMI.setCurrentCallSite(0);
7087     }
7088 
7089     // Both PendingLoads and PendingExports must be flushed here;
7090     // this call might not return.
7091     (void)getRoot();
7092     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7093 
7094     CLI.setChain(getRoot());
7095   }
7096   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7097   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7098 
7099   assert((CLI.IsTailCall || Result.second.getNode()) &&
7100          "Non-null chain expected with non-tail call!");
7101   assert((Result.second.getNode() || !Result.first.getNode()) &&
7102          "Null value expected with tail call!");
7103 
7104   if (!Result.second.getNode()) {
7105     // As a special case, a null chain means that a tail call has been emitted
7106     // and the DAG root is already updated.
7107     HasTailCall = true;
7108 
7109     // Since there's no actual continuation from this block, nothing can be
7110     // relying on us setting vregs for them.
7111     PendingExports.clear();
7112   } else {
7113     DAG.setRoot(Result.second);
7114   }
7115 
7116   if (EHPadBB) {
7117     // Insert a label at the end of the invoke call to mark the try range.  This
7118     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7119     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7120     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7121 
7122     // Inform MachineModuleInfo of range.
7123     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7124     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7125     // actually use outlined funclets and their LSDA info style.
7126     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7127       assert(CLI.CB);
7128       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7129       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7130     } else if (!isScopedEHPersonality(Pers)) {
7131       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7132     }
7133   }
7134 
7135   return Result;
7136 }
7137 
7138 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7139                                       bool isTailCall,
7140                                       const BasicBlock *EHPadBB) {
7141   auto &DL = DAG.getDataLayout();
7142   FunctionType *FTy = CB.getFunctionType();
7143   Type *RetTy = CB.getType();
7144 
7145   TargetLowering::ArgListTy Args;
7146   Args.reserve(CB.arg_size());
7147 
7148   const Value *SwiftErrorVal = nullptr;
7149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7150 
7151   if (isTailCall) {
7152     // Avoid emitting tail calls in functions with the disable-tail-calls
7153     // attribute.
7154     auto *Caller = CB.getParent()->getParent();
7155     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7156         "true")
7157       isTailCall = false;
7158 
7159     // We can't tail call inside a function with a swifterror argument. Lowering
7160     // does not support this yet. It would have to move into the swifterror
7161     // register before the call.
7162     if (TLI.supportSwiftError() &&
7163         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7164       isTailCall = false;
7165   }
7166 
7167   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7168     TargetLowering::ArgListEntry Entry;
7169     const Value *V = *I;
7170 
7171     // Skip empty types
7172     if (V->getType()->isEmptyTy())
7173       continue;
7174 
7175     SDValue ArgNode = getValue(V);
7176     Entry.Node = ArgNode; Entry.Ty = V->getType();
7177 
7178     Entry.setAttributes(&CB, I - CB.arg_begin());
7179 
7180     // Use swifterror virtual register as input to the call.
7181     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7182       SwiftErrorVal = V;
7183       // We find the virtual register for the actual swifterror argument.
7184       // Instead of using the Value, we use the virtual register instead.
7185       Entry.Node =
7186           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7187                           EVT(TLI.getPointerTy(DL)));
7188     }
7189 
7190     Args.push_back(Entry);
7191 
7192     // If we have an explicit sret argument that is an Instruction, (i.e., it
7193     // might point to function-local memory), we can't meaningfully tail-call.
7194     if (Entry.IsSRet && isa<Instruction>(V))
7195       isTailCall = false;
7196   }
7197 
7198   // If call site has a cfguardtarget operand bundle, create and add an
7199   // additional ArgListEntry.
7200   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7201     TargetLowering::ArgListEntry Entry;
7202     Value *V = Bundle->Inputs[0];
7203     SDValue ArgNode = getValue(V);
7204     Entry.Node = ArgNode;
7205     Entry.Ty = V->getType();
7206     Entry.IsCFGuardTarget = true;
7207     Args.push_back(Entry);
7208   }
7209 
7210   // Check if target-independent constraints permit a tail call here.
7211   // Target-dependent constraints are checked within TLI->LowerCallTo.
7212   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7213     isTailCall = false;
7214 
7215   // Disable tail calls if there is an swifterror argument. Targets have not
7216   // been updated to support tail calls.
7217   if (TLI.supportSwiftError() && SwiftErrorVal)
7218     isTailCall = false;
7219 
7220   TargetLowering::CallLoweringInfo CLI(DAG);
7221   CLI.setDebugLoc(getCurSDLoc())
7222       .setChain(getRoot())
7223       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7224       .setTailCall(isTailCall)
7225       .setConvergent(CB.isConvergent())
7226       .setIsPreallocated(
7227           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7228   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7229 
7230   if (Result.first.getNode()) {
7231     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7232     setValue(&CB, Result.first);
7233   }
7234 
7235   // The last element of CLI.InVals has the SDValue for swifterror return.
7236   // Here we copy it to a virtual register and update SwiftErrorMap for
7237   // book-keeping.
7238   if (SwiftErrorVal && TLI.supportSwiftError()) {
7239     // Get the last element of InVals.
7240     SDValue Src = CLI.InVals.back();
7241     Register VReg =
7242         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7243     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7244     DAG.setRoot(CopyNode);
7245   }
7246 }
7247 
7248 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7249                              SelectionDAGBuilder &Builder) {
7250   // Check to see if this load can be trivially constant folded, e.g. if the
7251   // input is from a string literal.
7252   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7253     // Cast pointer to the type we really want to load.
7254     Type *LoadTy =
7255         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7256     if (LoadVT.isVector())
7257       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7258 
7259     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7260                                          PointerType::getUnqual(LoadTy));
7261 
7262     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7263             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7264       return Builder.getValue(LoadCst);
7265   }
7266 
7267   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7268   // still constant memory, the input chain can be the entry node.
7269   SDValue Root;
7270   bool ConstantMemory = false;
7271 
7272   // Do not serialize (non-volatile) loads of constant memory with anything.
7273   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7274     Root = Builder.DAG.getEntryNode();
7275     ConstantMemory = true;
7276   } else {
7277     // Do not serialize non-volatile loads against each other.
7278     Root = Builder.DAG.getRoot();
7279   }
7280 
7281   SDValue Ptr = Builder.getValue(PtrVal);
7282   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7283                                         Ptr, MachinePointerInfo(PtrVal),
7284                                         /* Alignment = */ 1);
7285 
7286   if (!ConstantMemory)
7287     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7288   return LoadVal;
7289 }
7290 
7291 /// Record the value for an instruction that produces an integer result,
7292 /// converting the type where necessary.
7293 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7294                                                   SDValue Value,
7295                                                   bool IsSigned) {
7296   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7297                                                     I.getType(), true);
7298   if (IsSigned)
7299     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7300   else
7301     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7302   setValue(&I, Value);
7303 }
7304 
7305 /// See if we can lower a memcmp call into an optimized form. If so, return
7306 /// true and lower it. Otherwise return false, and it will be lowered like a
7307 /// normal call.
7308 /// The caller already checked that \p I calls the appropriate LibFunc with a
7309 /// correct prototype.
7310 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7311   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7312   const Value *Size = I.getArgOperand(2);
7313   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7314   if (CSize && CSize->getZExtValue() == 0) {
7315     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7316                                                           I.getType(), true);
7317     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7318     return true;
7319   }
7320 
7321   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7322   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7323       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7324       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7325   if (Res.first.getNode()) {
7326     processIntegerCallValue(I, Res.first, true);
7327     PendingLoads.push_back(Res.second);
7328     return true;
7329   }
7330 
7331   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7332   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7333   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7334     return false;
7335 
7336   // If the target has a fast compare for the given size, it will return a
7337   // preferred load type for that size. Require that the load VT is legal and
7338   // that the target supports unaligned loads of that type. Otherwise, return
7339   // INVALID.
7340   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7341     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7342     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7343     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7344       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7345       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7346       // TODO: Check alignment of src and dest ptrs.
7347       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7348       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7349       if (!TLI.isTypeLegal(LVT) ||
7350           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7351           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7352         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7353     }
7354 
7355     return LVT;
7356   };
7357 
7358   // This turns into unaligned loads. We only do this if the target natively
7359   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7360   // we'll only produce a small number of byte loads.
7361   MVT LoadVT;
7362   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7363   switch (NumBitsToCompare) {
7364   default:
7365     return false;
7366   case 16:
7367     LoadVT = MVT::i16;
7368     break;
7369   case 32:
7370     LoadVT = MVT::i32;
7371     break;
7372   case 64:
7373   case 128:
7374   case 256:
7375     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7376     break;
7377   }
7378 
7379   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7380     return false;
7381 
7382   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7383   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7384 
7385   // Bitcast to a wide integer type if the loads are vectors.
7386   if (LoadVT.isVector()) {
7387     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7388     LoadL = DAG.getBitcast(CmpVT, LoadL);
7389     LoadR = DAG.getBitcast(CmpVT, LoadR);
7390   }
7391 
7392   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7393   processIntegerCallValue(I, Cmp, false);
7394   return true;
7395 }
7396 
7397 /// See if we can lower a memchr call into an optimized form. If so, return
7398 /// true and lower it. Otherwise return false, and it will be lowered like a
7399 /// normal call.
7400 /// The caller already checked that \p I calls the appropriate LibFunc with a
7401 /// correct prototype.
7402 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7403   const Value *Src = I.getArgOperand(0);
7404   const Value *Char = I.getArgOperand(1);
7405   const Value *Length = I.getArgOperand(2);
7406 
7407   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7408   std::pair<SDValue, SDValue> Res =
7409     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7410                                 getValue(Src), getValue(Char), getValue(Length),
7411                                 MachinePointerInfo(Src));
7412   if (Res.first.getNode()) {
7413     setValue(&I, Res.first);
7414     PendingLoads.push_back(Res.second);
7415     return true;
7416   }
7417 
7418   return false;
7419 }
7420 
7421 /// See if we can lower a mempcpy call into an optimized form. If so, return
7422 /// true and lower it. Otherwise return false, and it will be lowered like a
7423 /// normal call.
7424 /// The caller already checked that \p I calls the appropriate LibFunc with a
7425 /// correct prototype.
7426 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7427   SDValue Dst = getValue(I.getArgOperand(0));
7428   SDValue Src = getValue(I.getArgOperand(1));
7429   SDValue Size = getValue(I.getArgOperand(2));
7430 
7431   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7432   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7433   // DAG::getMemcpy needs Alignment to be defined.
7434   Align Alignment = std::min(DstAlign, SrcAlign);
7435 
7436   bool isVol = false;
7437   SDLoc sdl = getCurSDLoc();
7438 
7439   // In the mempcpy context we need to pass in a false value for isTailCall
7440   // because the return pointer needs to be adjusted by the size of
7441   // the copied memory.
7442   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7443   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7444                              /*isTailCall=*/false,
7445                              MachinePointerInfo(I.getArgOperand(0)),
7446                              MachinePointerInfo(I.getArgOperand(1)));
7447   assert(MC.getNode() != nullptr &&
7448          "** memcpy should not be lowered as TailCall in mempcpy context **");
7449   DAG.setRoot(MC);
7450 
7451   // Check if Size needs to be truncated or extended.
7452   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7453 
7454   // Adjust return pointer to point just past the last dst byte.
7455   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7456                                     Dst, Size);
7457   setValue(&I, DstPlusSize);
7458   return true;
7459 }
7460 
7461 /// See if we can lower a strcpy call into an optimized form.  If so, return
7462 /// true and lower it, otherwise return false and it will be lowered like a
7463 /// normal call.
7464 /// The caller already checked that \p I calls the appropriate LibFunc with a
7465 /// correct prototype.
7466 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7467   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7468 
7469   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7470   std::pair<SDValue, SDValue> Res =
7471     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7472                                 getValue(Arg0), getValue(Arg1),
7473                                 MachinePointerInfo(Arg0),
7474                                 MachinePointerInfo(Arg1), isStpcpy);
7475   if (Res.first.getNode()) {
7476     setValue(&I, Res.first);
7477     DAG.setRoot(Res.second);
7478     return true;
7479   }
7480 
7481   return false;
7482 }
7483 
7484 /// See if we can lower a strcmp call into an optimized form.  If so, return
7485 /// true and lower it, otherwise return false and it will be lowered like a
7486 /// normal call.
7487 /// The caller already checked that \p I calls the appropriate LibFunc with a
7488 /// correct prototype.
7489 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7490   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7491 
7492   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7493   std::pair<SDValue, SDValue> Res =
7494     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7495                                 getValue(Arg0), getValue(Arg1),
7496                                 MachinePointerInfo(Arg0),
7497                                 MachinePointerInfo(Arg1));
7498   if (Res.first.getNode()) {
7499     processIntegerCallValue(I, Res.first, true);
7500     PendingLoads.push_back(Res.second);
7501     return true;
7502   }
7503 
7504   return false;
7505 }
7506 
7507 /// See if we can lower a strlen call into an optimized form.  If so, return
7508 /// true and lower it, otherwise return false and it will be lowered like a
7509 /// normal call.
7510 /// The caller already checked that \p I calls the appropriate LibFunc with a
7511 /// correct prototype.
7512 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7513   const Value *Arg0 = I.getArgOperand(0);
7514 
7515   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7516   std::pair<SDValue, SDValue> Res =
7517     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7518                                 getValue(Arg0), MachinePointerInfo(Arg0));
7519   if (Res.first.getNode()) {
7520     processIntegerCallValue(I, Res.first, false);
7521     PendingLoads.push_back(Res.second);
7522     return true;
7523   }
7524 
7525   return false;
7526 }
7527 
7528 /// See if we can lower a strnlen call into an optimized form.  If so, return
7529 /// true and lower it, otherwise return false and it will be lowered like a
7530 /// normal call.
7531 /// The caller already checked that \p I calls the appropriate LibFunc with a
7532 /// correct prototype.
7533 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7534   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7535 
7536   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7537   std::pair<SDValue, SDValue> Res =
7538     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7539                                  getValue(Arg0), getValue(Arg1),
7540                                  MachinePointerInfo(Arg0));
7541   if (Res.first.getNode()) {
7542     processIntegerCallValue(I, Res.first, false);
7543     PendingLoads.push_back(Res.second);
7544     return true;
7545   }
7546 
7547   return false;
7548 }
7549 
7550 /// See if we can lower a unary floating-point operation into an SDNode with
7551 /// the specified Opcode.  If so, return true and lower it, otherwise return
7552 /// false and it will be lowered like a normal call.
7553 /// The caller already checked that \p I calls the appropriate LibFunc with a
7554 /// correct prototype.
7555 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7556                                               unsigned Opcode) {
7557   // We already checked this call's prototype; verify it doesn't modify errno.
7558   if (!I.onlyReadsMemory())
7559     return false;
7560 
7561   SDValue Tmp = getValue(I.getArgOperand(0));
7562   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7563   return true;
7564 }
7565 
7566 /// See if we can lower a binary floating-point operation into an SDNode with
7567 /// the specified Opcode. If so, return true and lower it. Otherwise return
7568 /// false, and it will be lowered like a normal call.
7569 /// The caller already checked that \p I calls the appropriate LibFunc with a
7570 /// correct prototype.
7571 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7572                                                unsigned Opcode) {
7573   // We already checked this call's prototype; verify it doesn't modify errno.
7574   if (!I.onlyReadsMemory())
7575     return false;
7576 
7577   SDValue Tmp0 = getValue(I.getArgOperand(0));
7578   SDValue Tmp1 = getValue(I.getArgOperand(1));
7579   EVT VT = Tmp0.getValueType();
7580   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7581   return true;
7582 }
7583 
7584 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7585   // Handle inline assembly differently.
7586   if (I.isInlineAsm()) {
7587     visitInlineAsm(I);
7588     return;
7589   }
7590 
7591   if (Function *F = I.getCalledFunction()) {
7592     if (F->isDeclaration()) {
7593       // Is this an LLVM intrinsic or a target-specific intrinsic?
7594       unsigned IID = F->getIntrinsicID();
7595       if (!IID)
7596         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7597           IID = II->getIntrinsicID(F);
7598 
7599       if (IID) {
7600         visitIntrinsicCall(I, IID);
7601         return;
7602       }
7603     }
7604 
7605     // Check for well-known libc/libm calls.  If the function is internal, it
7606     // can't be a library call.  Don't do the check if marked as nobuiltin for
7607     // some reason or the call site requires strict floating point semantics.
7608     LibFunc Func;
7609     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7610         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7611         LibInfo->hasOptimizedCodeGen(Func)) {
7612       switch (Func) {
7613       default: break;
7614       case LibFunc_copysign:
7615       case LibFunc_copysignf:
7616       case LibFunc_copysignl:
7617         // We already checked this call's prototype; verify it doesn't modify
7618         // errno.
7619         if (I.onlyReadsMemory()) {
7620           SDValue LHS = getValue(I.getArgOperand(0));
7621           SDValue RHS = getValue(I.getArgOperand(1));
7622           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7623                                    LHS.getValueType(), LHS, RHS));
7624           return;
7625         }
7626         break;
7627       case LibFunc_fabs:
7628       case LibFunc_fabsf:
7629       case LibFunc_fabsl:
7630         if (visitUnaryFloatCall(I, ISD::FABS))
7631           return;
7632         break;
7633       case LibFunc_fmin:
7634       case LibFunc_fminf:
7635       case LibFunc_fminl:
7636         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7637           return;
7638         break;
7639       case LibFunc_fmax:
7640       case LibFunc_fmaxf:
7641       case LibFunc_fmaxl:
7642         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7643           return;
7644         break;
7645       case LibFunc_sin:
7646       case LibFunc_sinf:
7647       case LibFunc_sinl:
7648         if (visitUnaryFloatCall(I, ISD::FSIN))
7649           return;
7650         break;
7651       case LibFunc_cos:
7652       case LibFunc_cosf:
7653       case LibFunc_cosl:
7654         if (visitUnaryFloatCall(I, ISD::FCOS))
7655           return;
7656         break;
7657       case LibFunc_sqrt:
7658       case LibFunc_sqrtf:
7659       case LibFunc_sqrtl:
7660       case LibFunc_sqrt_finite:
7661       case LibFunc_sqrtf_finite:
7662       case LibFunc_sqrtl_finite:
7663         if (visitUnaryFloatCall(I, ISD::FSQRT))
7664           return;
7665         break;
7666       case LibFunc_floor:
7667       case LibFunc_floorf:
7668       case LibFunc_floorl:
7669         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7670           return;
7671         break;
7672       case LibFunc_nearbyint:
7673       case LibFunc_nearbyintf:
7674       case LibFunc_nearbyintl:
7675         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7676           return;
7677         break;
7678       case LibFunc_ceil:
7679       case LibFunc_ceilf:
7680       case LibFunc_ceill:
7681         if (visitUnaryFloatCall(I, ISD::FCEIL))
7682           return;
7683         break;
7684       case LibFunc_rint:
7685       case LibFunc_rintf:
7686       case LibFunc_rintl:
7687         if (visitUnaryFloatCall(I, ISD::FRINT))
7688           return;
7689         break;
7690       case LibFunc_round:
7691       case LibFunc_roundf:
7692       case LibFunc_roundl:
7693         if (visitUnaryFloatCall(I, ISD::FROUND))
7694           return;
7695         break;
7696       case LibFunc_trunc:
7697       case LibFunc_truncf:
7698       case LibFunc_truncl:
7699         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7700           return;
7701         break;
7702       case LibFunc_log2:
7703       case LibFunc_log2f:
7704       case LibFunc_log2l:
7705         if (visitUnaryFloatCall(I, ISD::FLOG2))
7706           return;
7707         break;
7708       case LibFunc_exp2:
7709       case LibFunc_exp2f:
7710       case LibFunc_exp2l:
7711         if (visitUnaryFloatCall(I, ISD::FEXP2))
7712           return;
7713         break;
7714       case LibFunc_memcmp:
7715         if (visitMemCmpCall(I))
7716           return;
7717         break;
7718       case LibFunc_mempcpy:
7719         if (visitMemPCpyCall(I))
7720           return;
7721         break;
7722       case LibFunc_memchr:
7723         if (visitMemChrCall(I))
7724           return;
7725         break;
7726       case LibFunc_strcpy:
7727         if (visitStrCpyCall(I, false))
7728           return;
7729         break;
7730       case LibFunc_stpcpy:
7731         if (visitStrCpyCall(I, true))
7732           return;
7733         break;
7734       case LibFunc_strcmp:
7735         if (visitStrCmpCall(I))
7736           return;
7737         break;
7738       case LibFunc_strlen:
7739         if (visitStrLenCall(I))
7740           return;
7741         break;
7742       case LibFunc_strnlen:
7743         if (visitStrNLenCall(I))
7744           return;
7745         break;
7746       }
7747     }
7748   }
7749 
7750   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7751   // have to do anything here to lower funclet bundles.
7752   // CFGuardTarget bundles are lowered in LowerCallTo.
7753   assert(!I.hasOperandBundlesOtherThan(
7754              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7755               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) &&
7756          "Cannot lower calls with arbitrary operand bundles!");
7757 
7758   SDValue Callee = getValue(I.getCalledOperand());
7759 
7760   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7761     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7762   else
7763     // Check if we can potentially perform a tail call. More detailed checking
7764     // is be done within LowerCallTo, after more information about the call is
7765     // known.
7766     LowerCallTo(I, Callee, I.isTailCall());
7767 }
7768 
7769 namespace {
7770 
7771 /// AsmOperandInfo - This contains information for each constraint that we are
7772 /// lowering.
7773 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7774 public:
7775   /// CallOperand - If this is the result output operand or a clobber
7776   /// this is null, otherwise it is the incoming operand to the CallInst.
7777   /// This gets modified as the asm is processed.
7778   SDValue CallOperand;
7779 
7780   /// AssignedRegs - If this is a register or register class operand, this
7781   /// contains the set of register corresponding to the operand.
7782   RegsForValue AssignedRegs;
7783 
7784   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7785     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7786   }
7787 
7788   /// Whether or not this operand accesses memory
7789   bool hasMemory(const TargetLowering &TLI) const {
7790     // Indirect operand accesses access memory.
7791     if (isIndirect)
7792       return true;
7793 
7794     for (const auto &Code : Codes)
7795       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7796         return true;
7797 
7798     return false;
7799   }
7800 
7801   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7802   /// corresponds to.  If there is no Value* for this operand, it returns
7803   /// MVT::Other.
7804   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7805                            const DataLayout &DL) const {
7806     if (!CallOperandVal) return MVT::Other;
7807 
7808     if (isa<BasicBlock>(CallOperandVal))
7809       return TLI.getProgramPointerTy(DL);
7810 
7811     llvm::Type *OpTy = CallOperandVal->getType();
7812 
7813     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7814     // If this is an indirect operand, the operand is a pointer to the
7815     // accessed type.
7816     if (isIndirect) {
7817       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7818       if (!PtrTy)
7819         report_fatal_error("Indirect operand for inline asm not a pointer!");
7820       OpTy = PtrTy->getElementType();
7821     }
7822 
7823     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7824     if (StructType *STy = dyn_cast<StructType>(OpTy))
7825       if (STy->getNumElements() == 1)
7826         OpTy = STy->getElementType(0);
7827 
7828     // If OpTy is not a single value, it may be a struct/union that we
7829     // can tile with integers.
7830     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7831       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7832       switch (BitSize) {
7833       default: break;
7834       case 1:
7835       case 8:
7836       case 16:
7837       case 32:
7838       case 64:
7839       case 128:
7840         OpTy = IntegerType::get(Context, BitSize);
7841         break;
7842       }
7843     }
7844 
7845     return TLI.getValueType(DL, OpTy, true);
7846   }
7847 };
7848 
7849 
7850 } // end anonymous namespace
7851 
7852 /// Make sure that the output operand \p OpInfo and its corresponding input
7853 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7854 /// out).
7855 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7856                                SDISelAsmOperandInfo &MatchingOpInfo,
7857                                SelectionDAG &DAG) {
7858   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7859     return;
7860 
7861   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7862   const auto &TLI = DAG.getTargetLoweringInfo();
7863 
7864   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7865       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7866                                        OpInfo.ConstraintVT);
7867   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7868       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7869                                        MatchingOpInfo.ConstraintVT);
7870   if ((OpInfo.ConstraintVT.isInteger() !=
7871        MatchingOpInfo.ConstraintVT.isInteger()) ||
7872       (MatchRC.second != InputRC.second)) {
7873     // FIXME: error out in a more elegant fashion
7874     report_fatal_error("Unsupported asm: input constraint"
7875                        " with a matching output constraint of"
7876                        " incompatible type!");
7877   }
7878   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7879 }
7880 
7881 /// Get a direct memory input to behave well as an indirect operand.
7882 /// This may introduce stores, hence the need for a \p Chain.
7883 /// \return The (possibly updated) chain.
7884 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7885                                         SDISelAsmOperandInfo &OpInfo,
7886                                         SelectionDAG &DAG) {
7887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7888 
7889   // If we don't have an indirect input, put it in the constpool if we can,
7890   // otherwise spill it to a stack slot.
7891   // TODO: This isn't quite right. We need to handle these according to
7892   // the addressing mode that the constraint wants. Also, this may take
7893   // an additional register for the computation and we don't want that
7894   // either.
7895 
7896   // If the operand is a float, integer, or vector constant, spill to a
7897   // constant pool entry to get its address.
7898   const Value *OpVal = OpInfo.CallOperandVal;
7899   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7900       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7901     OpInfo.CallOperand = DAG.getConstantPool(
7902         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7903     return Chain;
7904   }
7905 
7906   // Otherwise, create a stack slot and emit a store to it before the asm.
7907   Type *Ty = OpVal->getType();
7908   auto &DL = DAG.getDataLayout();
7909   uint64_t TySize = DL.getTypeAllocSize(Ty);
7910   MachineFunction &MF = DAG.getMachineFunction();
7911   int SSFI = MF.getFrameInfo().CreateStackObject(
7912       TySize, DL.getPrefTypeAlign(Ty), false);
7913   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7914   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7915                             MachinePointerInfo::getFixedStack(MF, SSFI),
7916                             TLI.getMemValueType(DL, Ty));
7917   OpInfo.CallOperand = StackSlot;
7918 
7919   return Chain;
7920 }
7921 
7922 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7923 /// specified operand.  We prefer to assign virtual registers, to allow the
7924 /// register allocator to handle the assignment process.  However, if the asm
7925 /// uses features that we can't model on machineinstrs, we have SDISel do the
7926 /// allocation.  This produces generally horrible, but correct, code.
7927 ///
7928 ///   OpInfo describes the operand
7929 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7930 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7931                                  SDISelAsmOperandInfo &OpInfo,
7932                                  SDISelAsmOperandInfo &RefOpInfo) {
7933   LLVMContext &Context = *DAG.getContext();
7934   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7935 
7936   MachineFunction &MF = DAG.getMachineFunction();
7937   SmallVector<unsigned, 4> Regs;
7938   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7939 
7940   // No work to do for memory operations.
7941   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7942     return;
7943 
7944   // If this is a constraint for a single physreg, or a constraint for a
7945   // register class, find it.
7946   unsigned AssignedReg;
7947   const TargetRegisterClass *RC;
7948   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7949       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7950   // RC is unset only on failure. Return immediately.
7951   if (!RC)
7952     return;
7953 
7954   // Get the actual register value type.  This is important, because the user
7955   // may have asked for (e.g.) the AX register in i32 type.  We need to
7956   // remember that AX is actually i16 to get the right extension.
7957   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7958 
7959   if (OpInfo.ConstraintVT != MVT::Other) {
7960     // If this is an FP operand in an integer register (or visa versa), or more
7961     // generally if the operand value disagrees with the register class we plan
7962     // to stick it in, fix the operand type.
7963     //
7964     // If this is an input value, the bitcast to the new type is done now.
7965     // Bitcast for output value is done at the end of visitInlineAsm().
7966     if ((OpInfo.Type == InlineAsm::isOutput ||
7967          OpInfo.Type == InlineAsm::isInput) &&
7968         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7969       // Try to convert to the first EVT that the reg class contains.  If the
7970       // types are identical size, use a bitcast to convert (e.g. two differing
7971       // vector types).  Note: output bitcast is done at the end of
7972       // visitInlineAsm().
7973       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7974         // Exclude indirect inputs while they are unsupported because the code
7975         // to perform the load is missing and thus OpInfo.CallOperand still
7976         // refers to the input address rather than the pointed-to value.
7977         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7978           OpInfo.CallOperand =
7979               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7980         OpInfo.ConstraintVT = RegVT;
7981         // If the operand is an FP value and we want it in integer registers,
7982         // use the corresponding integer type. This turns an f64 value into
7983         // i64, which can be passed with two i32 values on a 32-bit machine.
7984       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7985         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7986         if (OpInfo.Type == InlineAsm::isInput)
7987           OpInfo.CallOperand =
7988               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7989         OpInfo.ConstraintVT = VT;
7990       }
7991     }
7992   }
7993 
7994   // No need to allocate a matching input constraint since the constraint it's
7995   // matching to has already been allocated.
7996   if (OpInfo.isMatchingInputConstraint())
7997     return;
7998 
7999   EVT ValueVT = OpInfo.ConstraintVT;
8000   if (OpInfo.ConstraintVT == MVT::Other)
8001     ValueVT = RegVT;
8002 
8003   // Initialize NumRegs.
8004   unsigned NumRegs = 1;
8005   if (OpInfo.ConstraintVT != MVT::Other)
8006     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8007 
8008   // If this is a constraint for a specific physical register, like {r17},
8009   // assign it now.
8010 
8011   // If this associated to a specific register, initialize iterator to correct
8012   // place. If virtual, make sure we have enough registers
8013 
8014   // Initialize iterator if necessary
8015   TargetRegisterClass::iterator I = RC->begin();
8016   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8017 
8018   // Do not check for single registers.
8019   if (AssignedReg) {
8020       for (; *I != AssignedReg; ++I)
8021         assert(I != RC->end() && "AssignedReg should be member of RC");
8022   }
8023 
8024   for (; NumRegs; --NumRegs, ++I) {
8025     assert(I != RC->end() && "Ran out of registers to allocate!");
8026     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8027     Regs.push_back(R);
8028   }
8029 
8030   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8031 }
8032 
8033 static unsigned
8034 findMatchingInlineAsmOperand(unsigned OperandNo,
8035                              const std::vector<SDValue> &AsmNodeOperands) {
8036   // Scan until we find the definition we already emitted of this operand.
8037   unsigned CurOp = InlineAsm::Op_FirstOperand;
8038   for (; OperandNo; --OperandNo) {
8039     // Advance to the next operand.
8040     unsigned OpFlag =
8041         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8042     assert((InlineAsm::isRegDefKind(OpFlag) ||
8043             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8044             InlineAsm::isMemKind(OpFlag)) &&
8045            "Skipped past definitions?");
8046     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8047   }
8048   return CurOp;
8049 }
8050 
8051 namespace {
8052 
8053 class ExtraFlags {
8054   unsigned Flags = 0;
8055 
8056 public:
8057   explicit ExtraFlags(const CallBase &Call) {
8058     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8059     if (IA->hasSideEffects())
8060       Flags |= InlineAsm::Extra_HasSideEffects;
8061     if (IA->isAlignStack())
8062       Flags |= InlineAsm::Extra_IsAlignStack;
8063     if (Call.isConvergent())
8064       Flags |= InlineAsm::Extra_IsConvergent;
8065     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8066   }
8067 
8068   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8069     // Ideally, we would only check against memory constraints.  However, the
8070     // meaning of an Other constraint can be target-specific and we can't easily
8071     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8072     // for Other constraints as well.
8073     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8074         OpInfo.ConstraintType == TargetLowering::C_Other) {
8075       if (OpInfo.Type == InlineAsm::isInput)
8076         Flags |= InlineAsm::Extra_MayLoad;
8077       else if (OpInfo.Type == InlineAsm::isOutput)
8078         Flags |= InlineAsm::Extra_MayStore;
8079       else if (OpInfo.Type == InlineAsm::isClobber)
8080         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8081     }
8082   }
8083 
8084   unsigned get() const { return Flags; }
8085 };
8086 
8087 } // end anonymous namespace
8088 
8089 /// visitInlineAsm - Handle a call to an InlineAsm object.
8090 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8091   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8092 
8093   /// ConstraintOperands - Information about all of the constraints.
8094   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8095 
8096   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8097   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8098       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8099 
8100   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8101   // AsmDialect, MayLoad, MayStore).
8102   bool HasSideEffect = IA->hasSideEffects();
8103   ExtraFlags ExtraInfo(Call);
8104 
8105   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8106   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8107   unsigned NumMatchingOps = 0;
8108   for (auto &T : TargetConstraints) {
8109     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8110     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8111 
8112     // Compute the value type for each operand.
8113     if (OpInfo.Type == InlineAsm::isInput ||
8114         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8115       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8116 
8117       // Process the call argument. BasicBlocks are labels, currently appearing
8118       // only in asm's.
8119       if (isa<CallBrInst>(Call) &&
8120           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8121                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8122                         NumMatchingOps) &&
8123           (NumMatchingOps == 0 ||
8124            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8125                         NumMatchingOps))) {
8126         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8127         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8128         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8129       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8130         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8131       } else {
8132         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8133       }
8134 
8135       OpInfo.ConstraintVT =
8136           OpInfo
8137               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8138               .getSimpleVT();
8139     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8140       // The return value of the call is this value.  As such, there is no
8141       // corresponding argument.
8142       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8143       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8144         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8145             DAG.getDataLayout(), STy->getElementType(ResNo));
8146       } else {
8147         assert(ResNo == 0 && "Asm only has one result!");
8148         OpInfo.ConstraintVT =
8149             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8150       }
8151       ++ResNo;
8152     } else {
8153       OpInfo.ConstraintVT = MVT::Other;
8154     }
8155 
8156     if (OpInfo.hasMatchingInput())
8157       ++NumMatchingOps;
8158 
8159     if (!HasSideEffect)
8160       HasSideEffect = OpInfo.hasMemory(TLI);
8161 
8162     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8163     // FIXME: Could we compute this on OpInfo rather than T?
8164 
8165     // Compute the constraint code and ConstraintType to use.
8166     TLI.ComputeConstraintToUse(T, SDValue());
8167 
8168     if (T.ConstraintType == TargetLowering::C_Immediate &&
8169         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8170       // We've delayed emitting a diagnostic like the "n" constraint because
8171       // inlining could cause an integer showing up.
8172       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8173                                           "' expects an integer constant "
8174                                           "expression");
8175 
8176     ExtraInfo.update(T);
8177   }
8178 
8179 
8180   // We won't need to flush pending loads if this asm doesn't touch
8181   // memory and is nonvolatile.
8182   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8183 
8184   bool IsCallBr = isa<CallBrInst>(Call);
8185   if (IsCallBr) {
8186     // If this is a callbr we need to flush pending exports since inlineasm_br
8187     // is a terminator. We need to do this before nodes are glued to
8188     // the inlineasm_br node.
8189     Chain = getControlRoot();
8190   }
8191 
8192   // Second pass over the constraints: compute which constraint option to use.
8193   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8194     // If this is an output operand with a matching input operand, look up the
8195     // matching input. If their types mismatch, e.g. one is an integer, the
8196     // other is floating point, or their sizes are different, flag it as an
8197     // error.
8198     if (OpInfo.hasMatchingInput()) {
8199       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8200       patchMatchingInput(OpInfo, Input, DAG);
8201     }
8202 
8203     // Compute the constraint code and ConstraintType to use.
8204     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8205 
8206     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8207         OpInfo.Type == InlineAsm::isClobber)
8208       continue;
8209 
8210     // If this is a memory input, and if the operand is not indirect, do what we
8211     // need to provide an address for the memory input.
8212     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8213         !OpInfo.isIndirect) {
8214       assert((OpInfo.isMultipleAlternative ||
8215               (OpInfo.Type == InlineAsm::isInput)) &&
8216              "Can only indirectify direct input operands!");
8217 
8218       // Memory operands really want the address of the value.
8219       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8220 
8221       // There is no longer a Value* corresponding to this operand.
8222       OpInfo.CallOperandVal = nullptr;
8223 
8224       // It is now an indirect operand.
8225       OpInfo.isIndirect = true;
8226     }
8227 
8228   }
8229 
8230   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8231   std::vector<SDValue> AsmNodeOperands;
8232   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8233   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8234       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8235 
8236   // If we have a !srcloc metadata node associated with it, we want to attach
8237   // this to the ultimately generated inline asm machineinstr.  To do this, we
8238   // pass in the third operand as this (potentially null) inline asm MDNode.
8239   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8240   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8241 
8242   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8243   // bits as operand 3.
8244   AsmNodeOperands.push_back(DAG.getTargetConstant(
8245       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8246 
8247   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8248   // this, assign virtual and physical registers for inputs and otput.
8249   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8250     // Assign Registers.
8251     SDISelAsmOperandInfo &RefOpInfo =
8252         OpInfo.isMatchingInputConstraint()
8253             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8254             : OpInfo;
8255     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8256 
8257     auto DetectWriteToReservedRegister = [&]() {
8258       const MachineFunction &MF = DAG.getMachineFunction();
8259       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8260       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8261         if (Register::isPhysicalRegister(Reg) &&
8262             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8263           const char *RegName = TRI.getName(Reg);
8264           emitInlineAsmError(Call, "write to reserved register '" +
8265                                        Twine(RegName) + "'");
8266           return true;
8267         }
8268       }
8269       return false;
8270     };
8271 
8272     switch (OpInfo.Type) {
8273     case InlineAsm::isOutput:
8274       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8275         unsigned ConstraintID =
8276             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8277         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8278                "Failed to convert memory constraint code to constraint id.");
8279 
8280         // Add information to the INLINEASM node to know about this output.
8281         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8282         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8283         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8284                                                         MVT::i32));
8285         AsmNodeOperands.push_back(OpInfo.CallOperand);
8286       } else {
8287         // Otherwise, this outputs to a register (directly for C_Register /
8288         // C_RegisterClass, and a target-defined fashion for
8289         // C_Immediate/C_Other). Find a register that we can use.
8290         if (OpInfo.AssignedRegs.Regs.empty()) {
8291           emitInlineAsmError(
8292               Call, "couldn't allocate output register for constraint '" +
8293                         Twine(OpInfo.ConstraintCode) + "'");
8294           return;
8295         }
8296 
8297         if (DetectWriteToReservedRegister())
8298           return;
8299 
8300         // Add information to the INLINEASM node to know that this register is
8301         // set.
8302         OpInfo.AssignedRegs.AddInlineAsmOperands(
8303             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8304                                   : InlineAsm::Kind_RegDef,
8305             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8306       }
8307       break;
8308 
8309     case InlineAsm::isInput: {
8310       SDValue InOperandVal = OpInfo.CallOperand;
8311 
8312       if (OpInfo.isMatchingInputConstraint()) {
8313         // If this is required to match an output register we have already set,
8314         // just use its register.
8315         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8316                                                   AsmNodeOperands);
8317         unsigned OpFlag =
8318           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8319         if (InlineAsm::isRegDefKind(OpFlag) ||
8320             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8321           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8322           if (OpInfo.isIndirect) {
8323             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8324             emitInlineAsmError(Call, "inline asm not supported yet: "
8325                                      "don't know how to handle tied "
8326                                      "indirect register inputs");
8327             return;
8328           }
8329 
8330           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8331           SmallVector<unsigned, 4> Regs;
8332 
8333           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8334             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8335             MachineRegisterInfo &RegInfo =
8336                 DAG.getMachineFunction().getRegInfo();
8337             for (unsigned i = 0; i != NumRegs; ++i)
8338               Regs.push_back(RegInfo.createVirtualRegister(RC));
8339           } else {
8340             emitInlineAsmError(Call,
8341                                "inline asm error: This value type register "
8342                                "class is not natively supported!");
8343             return;
8344           }
8345 
8346           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8347 
8348           SDLoc dl = getCurSDLoc();
8349           // Use the produced MatchedRegs object to
8350           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8351           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8352                                            true, OpInfo.getMatchedOperand(), dl,
8353                                            DAG, AsmNodeOperands);
8354           break;
8355         }
8356 
8357         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8358         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8359                "Unexpected number of operands");
8360         // Add information to the INLINEASM node to know about this input.
8361         // See InlineAsm.h isUseOperandTiedToDef.
8362         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8363         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8364                                                     OpInfo.getMatchedOperand());
8365         AsmNodeOperands.push_back(DAG.getTargetConstant(
8366             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8367         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8368         break;
8369       }
8370 
8371       // Treat indirect 'X' constraint as memory.
8372       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8373           OpInfo.isIndirect)
8374         OpInfo.ConstraintType = TargetLowering::C_Memory;
8375 
8376       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8377           OpInfo.ConstraintType == TargetLowering::C_Other) {
8378         std::vector<SDValue> Ops;
8379         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8380                                           Ops, DAG);
8381         if (Ops.empty()) {
8382           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8383             if (isa<ConstantSDNode>(InOperandVal)) {
8384               emitInlineAsmError(Call, "value out of range for constraint '" +
8385                                            Twine(OpInfo.ConstraintCode) + "'");
8386               return;
8387             }
8388 
8389           emitInlineAsmError(Call,
8390                              "invalid operand for inline asm constraint '" +
8391                                  Twine(OpInfo.ConstraintCode) + "'");
8392           return;
8393         }
8394 
8395         // Add information to the INLINEASM node to know about this input.
8396         unsigned ResOpType =
8397           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8398         AsmNodeOperands.push_back(DAG.getTargetConstant(
8399             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8400         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8401         break;
8402       }
8403 
8404       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8405         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8406         assert(InOperandVal.getValueType() ==
8407                    TLI.getPointerTy(DAG.getDataLayout()) &&
8408                "Memory operands expect pointer values");
8409 
8410         unsigned ConstraintID =
8411             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8412         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8413                "Failed to convert memory constraint code to constraint id.");
8414 
8415         // Add information to the INLINEASM node to know about this input.
8416         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8417         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8418         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8419                                                         getCurSDLoc(),
8420                                                         MVT::i32));
8421         AsmNodeOperands.push_back(InOperandVal);
8422         break;
8423       }
8424 
8425       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8426               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8427              "Unknown constraint type!");
8428 
8429       // TODO: Support this.
8430       if (OpInfo.isIndirect) {
8431         emitInlineAsmError(
8432             Call, "Don't know how to handle indirect register inputs yet "
8433                   "for constraint '" +
8434                       Twine(OpInfo.ConstraintCode) + "'");
8435         return;
8436       }
8437 
8438       // Copy the input into the appropriate registers.
8439       if (OpInfo.AssignedRegs.Regs.empty()) {
8440         emitInlineAsmError(Call,
8441                            "couldn't allocate input reg for constraint '" +
8442                                Twine(OpInfo.ConstraintCode) + "'");
8443         return;
8444       }
8445 
8446       if (DetectWriteToReservedRegister())
8447         return;
8448 
8449       SDLoc dl = getCurSDLoc();
8450 
8451       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8452                                         &Call);
8453 
8454       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8455                                                dl, DAG, AsmNodeOperands);
8456       break;
8457     }
8458     case InlineAsm::isClobber:
8459       // Add the clobbered value to the operand list, so that the register
8460       // allocator is aware that the physreg got clobbered.
8461       if (!OpInfo.AssignedRegs.Regs.empty())
8462         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8463                                                  false, 0, getCurSDLoc(), DAG,
8464                                                  AsmNodeOperands);
8465       break;
8466     }
8467   }
8468 
8469   // Finish up input operands.  Set the input chain and add the flag last.
8470   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8471   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8472 
8473   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8474   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8475                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8476   Flag = Chain.getValue(1);
8477 
8478   // Do additional work to generate outputs.
8479 
8480   SmallVector<EVT, 1> ResultVTs;
8481   SmallVector<SDValue, 1> ResultValues;
8482   SmallVector<SDValue, 8> OutChains;
8483 
8484   llvm::Type *CallResultType = Call.getType();
8485   ArrayRef<Type *> ResultTypes;
8486   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8487     ResultTypes = StructResult->elements();
8488   else if (!CallResultType->isVoidTy())
8489     ResultTypes = makeArrayRef(CallResultType);
8490 
8491   auto CurResultType = ResultTypes.begin();
8492   auto handleRegAssign = [&](SDValue V) {
8493     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8494     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8495     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8496     ++CurResultType;
8497     // If the type of the inline asm call site return value is different but has
8498     // same size as the type of the asm output bitcast it.  One example of this
8499     // is for vectors with different width / number of elements.  This can
8500     // happen for register classes that can contain multiple different value
8501     // types.  The preg or vreg allocated may not have the same VT as was
8502     // expected.
8503     //
8504     // This can also happen for a return value that disagrees with the register
8505     // class it is put in, eg. a double in a general-purpose register on a
8506     // 32-bit machine.
8507     if (ResultVT != V.getValueType() &&
8508         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8509       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8510     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8511              V.getValueType().isInteger()) {
8512       // If a result value was tied to an input value, the computed result
8513       // may have a wider width than the expected result.  Extract the
8514       // relevant portion.
8515       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8516     }
8517     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8518     ResultVTs.push_back(ResultVT);
8519     ResultValues.push_back(V);
8520   };
8521 
8522   // Deal with output operands.
8523   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8524     if (OpInfo.Type == InlineAsm::isOutput) {
8525       SDValue Val;
8526       // Skip trivial output operands.
8527       if (OpInfo.AssignedRegs.Regs.empty())
8528         continue;
8529 
8530       switch (OpInfo.ConstraintType) {
8531       case TargetLowering::C_Register:
8532       case TargetLowering::C_RegisterClass:
8533         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8534                                                   Chain, &Flag, &Call);
8535         break;
8536       case TargetLowering::C_Immediate:
8537       case TargetLowering::C_Other:
8538         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8539                                               OpInfo, DAG);
8540         break;
8541       case TargetLowering::C_Memory:
8542         break; // Already handled.
8543       case TargetLowering::C_Unknown:
8544         assert(false && "Unexpected unknown constraint");
8545       }
8546 
8547       // Indirect output manifest as stores. Record output chains.
8548       if (OpInfo.isIndirect) {
8549         const Value *Ptr = OpInfo.CallOperandVal;
8550         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8551         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8552                                      MachinePointerInfo(Ptr));
8553         OutChains.push_back(Store);
8554       } else {
8555         // generate CopyFromRegs to associated registers.
8556         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8557         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8558           for (const SDValue &V : Val->op_values())
8559             handleRegAssign(V);
8560         } else
8561           handleRegAssign(Val);
8562       }
8563     }
8564   }
8565 
8566   // Set results.
8567   if (!ResultValues.empty()) {
8568     assert(CurResultType == ResultTypes.end() &&
8569            "Mismatch in number of ResultTypes");
8570     assert(ResultValues.size() == ResultTypes.size() &&
8571            "Mismatch in number of output operands in asm result");
8572 
8573     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8574                             DAG.getVTList(ResultVTs), ResultValues);
8575     setValue(&Call, V);
8576   }
8577 
8578   // Collect store chains.
8579   if (!OutChains.empty())
8580     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8581 
8582   // Only Update Root if inline assembly has a memory effect.
8583   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8584     DAG.setRoot(Chain);
8585 }
8586 
8587 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8588                                              const Twine &Message) {
8589   LLVMContext &Ctx = *DAG.getContext();
8590   Ctx.emitError(&Call, Message);
8591 
8592   // Make sure we leave the DAG in a valid state
8593   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8594   SmallVector<EVT, 1> ValueVTs;
8595   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8596 
8597   if (ValueVTs.empty())
8598     return;
8599 
8600   SmallVector<SDValue, 1> Ops;
8601   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8602     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8603 
8604   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8605 }
8606 
8607 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8608   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8609                           MVT::Other, getRoot(),
8610                           getValue(I.getArgOperand(0)),
8611                           DAG.getSrcValue(I.getArgOperand(0))));
8612 }
8613 
8614 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8615   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8616   const DataLayout &DL = DAG.getDataLayout();
8617   SDValue V = DAG.getVAArg(
8618       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8619       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8620       DL.getABITypeAlign(I.getType()).value());
8621   DAG.setRoot(V.getValue(1));
8622 
8623   if (I.getType()->isPointerTy())
8624     V = DAG.getPtrExtOrTrunc(
8625         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8626   setValue(&I, V);
8627 }
8628 
8629 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8630   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8631                           MVT::Other, getRoot(),
8632                           getValue(I.getArgOperand(0)),
8633                           DAG.getSrcValue(I.getArgOperand(0))));
8634 }
8635 
8636 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8637   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8638                           MVT::Other, getRoot(),
8639                           getValue(I.getArgOperand(0)),
8640                           getValue(I.getArgOperand(1)),
8641                           DAG.getSrcValue(I.getArgOperand(0)),
8642                           DAG.getSrcValue(I.getArgOperand(1))));
8643 }
8644 
8645 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8646                                                     const Instruction &I,
8647                                                     SDValue Op) {
8648   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8649   if (!Range)
8650     return Op;
8651 
8652   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8653   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8654     return Op;
8655 
8656   APInt Lo = CR.getUnsignedMin();
8657   if (!Lo.isMinValue())
8658     return Op;
8659 
8660   APInt Hi = CR.getUnsignedMax();
8661   unsigned Bits = std::max(Hi.getActiveBits(),
8662                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8663 
8664   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8665 
8666   SDLoc SL = getCurSDLoc();
8667 
8668   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8669                              DAG.getValueType(SmallVT));
8670   unsigned NumVals = Op.getNode()->getNumValues();
8671   if (NumVals == 1)
8672     return ZExt;
8673 
8674   SmallVector<SDValue, 4> Ops;
8675 
8676   Ops.push_back(ZExt);
8677   for (unsigned I = 1; I != NumVals; ++I)
8678     Ops.push_back(Op.getValue(I));
8679 
8680   return DAG.getMergeValues(Ops, SL);
8681 }
8682 
8683 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8684 /// the call being lowered.
8685 ///
8686 /// This is a helper for lowering intrinsics that follow a target calling
8687 /// convention or require stack pointer adjustment. Only a subset of the
8688 /// intrinsic's operands need to participate in the calling convention.
8689 void SelectionDAGBuilder::populateCallLoweringInfo(
8690     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8691     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8692     bool IsPatchPoint) {
8693   TargetLowering::ArgListTy Args;
8694   Args.reserve(NumArgs);
8695 
8696   // Populate the argument list.
8697   // Attributes for args start at offset 1, after the return attribute.
8698   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8699        ArgI != ArgE; ++ArgI) {
8700     const Value *V = Call->getOperand(ArgI);
8701 
8702     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8703 
8704     TargetLowering::ArgListEntry Entry;
8705     Entry.Node = getValue(V);
8706     Entry.Ty = V->getType();
8707     Entry.setAttributes(Call, ArgI);
8708     Args.push_back(Entry);
8709   }
8710 
8711   CLI.setDebugLoc(getCurSDLoc())
8712       .setChain(getRoot())
8713       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8714       .setDiscardResult(Call->use_empty())
8715       .setIsPatchPoint(IsPatchPoint)
8716       .setIsPreallocated(
8717           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8718 }
8719 
8720 /// Add a stack map intrinsic call's live variable operands to a stackmap
8721 /// or patchpoint target node's operand list.
8722 ///
8723 /// Constants are converted to TargetConstants purely as an optimization to
8724 /// avoid constant materialization and register allocation.
8725 ///
8726 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8727 /// generate addess computation nodes, and so FinalizeISel can convert the
8728 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8729 /// address materialization and register allocation, but may also be required
8730 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8731 /// alloca in the entry block, then the runtime may assume that the alloca's
8732 /// StackMap location can be read immediately after compilation and that the
8733 /// location is valid at any point during execution (this is similar to the
8734 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8735 /// only available in a register, then the runtime would need to trap when
8736 /// execution reaches the StackMap in order to read the alloca's location.
8737 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8738                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8739                                 SelectionDAGBuilder &Builder) {
8740   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8741     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8742     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8743       Ops.push_back(
8744         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8745       Ops.push_back(
8746         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8747     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8748       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8749       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8750           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8751     } else
8752       Ops.push_back(OpVal);
8753   }
8754 }
8755 
8756 /// Lower llvm.experimental.stackmap directly to its target opcode.
8757 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8758   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8759   //                                  [live variables...])
8760 
8761   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8762 
8763   SDValue Chain, InFlag, Callee, NullPtr;
8764   SmallVector<SDValue, 32> Ops;
8765 
8766   SDLoc DL = getCurSDLoc();
8767   Callee = getValue(CI.getCalledOperand());
8768   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8769 
8770   // The stackmap intrinsic only records the live variables (the arguments
8771   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8772   // intrinsic, this won't be lowered to a function call. This means we don't
8773   // have to worry about calling conventions and target specific lowering code.
8774   // Instead we perform the call lowering right here.
8775   //
8776   // chain, flag = CALLSEQ_START(chain, 0, 0)
8777   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8778   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8779   //
8780   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8781   InFlag = Chain.getValue(1);
8782 
8783   // Add the <id> and <numBytes> constants.
8784   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8785   Ops.push_back(DAG.getTargetConstant(
8786                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8787   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8788   Ops.push_back(DAG.getTargetConstant(
8789                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8790                   MVT::i32));
8791 
8792   // Push live variables for the stack map.
8793   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8794 
8795   // We are not pushing any register mask info here on the operands list,
8796   // because the stackmap doesn't clobber anything.
8797 
8798   // Push the chain and the glue flag.
8799   Ops.push_back(Chain);
8800   Ops.push_back(InFlag);
8801 
8802   // Create the STACKMAP node.
8803   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8804   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8805   Chain = SDValue(SM, 0);
8806   InFlag = Chain.getValue(1);
8807 
8808   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8809 
8810   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8811 
8812   // Set the root to the target-lowered call chain.
8813   DAG.setRoot(Chain);
8814 
8815   // Inform the Frame Information that we have a stackmap in this function.
8816   FuncInfo.MF->getFrameInfo().setHasStackMap();
8817 }
8818 
8819 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8820 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8821                                           const BasicBlock *EHPadBB) {
8822   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8823   //                                                 i32 <numBytes>,
8824   //                                                 i8* <target>,
8825   //                                                 i32 <numArgs>,
8826   //                                                 [Args...],
8827   //                                                 [live variables...])
8828 
8829   CallingConv::ID CC = CB.getCallingConv();
8830   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8831   bool HasDef = !CB.getType()->isVoidTy();
8832   SDLoc dl = getCurSDLoc();
8833   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8834 
8835   // Handle immediate and symbolic callees.
8836   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8837     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8838                                    /*isTarget=*/true);
8839   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8840     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8841                                          SDLoc(SymbolicCallee),
8842                                          SymbolicCallee->getValueType(0));
8843 
8844   // Get the real number of arguments participating in the call <numArgs>
8845   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8846   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8847 
8848   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8849   // Intrinsics include all meta-operands up to but not including CC.
8850   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8851   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8852          "Not enough arguments provided to the patchpoint intrinsic");
8853 
8854   // For AnyRegCC the arguments are lowered later on manually.
8855   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8856   Type *ReturnTy =
8857       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
8858 
8859   TargetLowering::CallLoweringInfo CLI(DAG);
8860   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
8861                            ReturnTy, true);
8862   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8863 
8864   SDNode *CallEnd = Result.second.getNode();
8865   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8866     CallEnd = CallEnd->getOperand(0).getNode();
8867 
8868   /// Get a call instruction from the call sequence chain.
8869   /// Tail calls are not allowed.
8870   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8871          "Expected a callseq node.");
8872   SDNode *Call = CallEnd->getOperand(0).getNode();
8873   bool HasGlue = Call->getGluedNode();
8874 
8875   // Replace the target specific call node with the patchable intrinsic.
8876   SmallVector<SDValue, 8> Ops;
8877 
8878   // Add the <id> and <numBytes> constants.
8879   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
8880   Ops.push_back(DAG.getTargetConstant(
8881                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8882   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
8883   Ops.push_back(DAG.getTargetConstant(
8884                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8885                   MVT::i32));
8886 
8887   // Add the callee.
8888   Ops.push_back(Callee);
8889 
8890   // Adjust <numArgs> to account for any arguments that have been passed on the
8891   // stack instead.
8892   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8893   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8894   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8895   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8896 
8897   // Add the calling convention
8898   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8899 
8900   // Add the arguments we omitted previously. The register allocator should
8901   // place these in any free register.
8902   if (IsAnyRegCC)
8903     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8904       Ops.push_back(getValue(CB.getArgOperand(i)));
8905 
8906   // Push the arguments from the call instruction up to the register mask.
8907   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8908   Ops.append(Call->op_begin() + 2, e);
8909 
8910   // Push live variables for the stack map.
8911   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
8912 
8913   // Push the register mask info.
8914   if (HasGlue)
8915     Ops.push_back(*(Call->op_end()-2));
8916   else
8917     Ops.push_back(*(Call->op_end()-1));
8918 
8919   // Push the chain (this is originally the first operand of the call, but
8920   // becomes now the last or second to last operand).
8921   Ops.push_back(*(Call->op_begin()));
8922 
8923   // Push the glue flag (last operand).
8924   if (HasGlue)
8925     Ops.push_back(*(Call->op_end()-1));
8926 
8927   SDVTList NodeTys;
8928   if (IsAnyRegCC && HasDef) {
8929     // Create the return types based on the intrinsic definition
8930     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8931     SmallVector<EVT, 3> ValueVTs;
8932     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
8933     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8934 
8935     // There is always a chain and a glue type at the end
8936     ValueVTs.push_back(MVT::Other);
8937     ValueVTs.push_back(MVT::Glue);
8938     NodeTys = DAG.getVTList(ValueVTs);
8939   } else
8940     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8941 
8942   // Replace the target specific call node with a PATCHPOINT node.
8943   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8944                                          dl, NodeTys, Ops);
8945 
8946   // Update the NodeMap.
8947   if (HasDef) {
8948     if (IsAnyRegCC)
8949       setValue(&CB, SDValue(MN, 0));
8950     else
8951       setValue(&CB, Result.first);
8952   }
8953 
8954   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8955   // call sequence. Furthermore the location of the chain and glue can change
8956   // when the AnyReg calling convention is used and the intrinsic returns a
8957   // value.
8958   if (IsAnyRegCC && HasDef) {
8959     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8960     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8961     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8962   } else
8963     DAG.ReplaceAllUsesWith(Call, MN);
8964   DAG.DeleteNode(Call);
8965 
8966   // Inform the Frame Information that we have a patchpoint in this function.
8967   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8968 }
8969 
8970 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8971                                             unsigned Intrinsic) {
8972   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8973   SDValue Op1 = getValue(I.getArgOperand(0));
8974   SDValue Op2;
8975   if (I.getNumArgOperands() > 1)
8976     Op2 = getValue(I.getArgOperand(1));
8977   SDLoc dl = getCurSDLoc();
8978   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8979   SDValue Res;
8980   FastMathFlags FMF;
8981   if (isa<FPMathOperator>(I))
8982     FMF = I.getFastMathFlags();
8983 
8984   switch (Intrinsic) {
8985   case Intrinsic::experimental_vector_reduce_v2_fadd:
8986     if (FMF.allowReassoc())
8987       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8988                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8989     else
8990       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8991     break;
8992   case Intrinsic::experimental_vector_reduce_v2_fmul:
8993     if (FMF.allowReassoc())
8994       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8995                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8996     else
8997       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8998     break;
8999   case Intrinsic::experimental_vector_reduce_add:
9000     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9001     break;
9002   case Intrinsic::experimental_vector_reduce_mul:
9003     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9004     break;
9005   case Intrinsic::experimental_vector_reduce_and:
9006     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9007     break;
9008   case Intrinsic::experimental_vector_reduce_or:
9009     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9010     break;
9011   case Intrinsic::experimental_vector_reduce_xor:
9012     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9013     break;
9014   case Intrinsic::experimental_vector_reduce_smax:
9015     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9016     break;
9017   case Intrinsic::experimental_vector_reduce_smin:
9018     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9019     break;
9020   case Intrinsic::experimental_vector_reduce_umax:
9021     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9022     break;
9023   case Intrinsic::experimental_vector_reduce_umin:
9024     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9025     break;
9026   case Intrinsic::experimental_vector_reduce_fmax:
9027     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
9028     break;
9029   case Intrinsic::experimental_vector_reduce_fmin:
9030     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
9031     break;
9032   default:
9033     llvm_unreachable("Unhandled vector reduce intrinsic");
9034   }
9035   setValue(&I, Res);
9036 }
9037 
9038 /// Returns an AttributeList representing the attributes applied to the return
9039 /// value of the given call.
9040 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9041   SmallVector<Attribute::AttrKind, 2> Attrs;
9042   if (CLI.RetSExt)
9043     Attrs.push_back(Attribute::SExt);
9044   if (CLI.RetZExt)
9045     Attrs.push_back(Attribute::ZExt);
9046   if (CLI.IsInReg)
9047     Attrs.push_back(Attribute::InReg);
9048 
9049   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9050                             Attrs);
9051 }
9052 
9053 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9054 /// implementation, which just calls LowerCall.
9055 /// FIXME: When all targets are
9056 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9057 std::pair<SDValue, SDValue>
9058 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9059   // Handle the incoming return values from the call.
9060   CLI.Ins.clear();
9061   Type *OrigRetTy = CLI.RetTy;
9062   SmallVector<EVT, 4> RetTys;
9063   SmallVector<uint64_t, 4> Offsets;
9064   auto &DL = CLI.DAG.getDataLayout();
9065   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9066 
9067   if (CLI.IsPostTypeLegalization) {
9068     // If we are lowering a libcall after legalization, split the return type.
9069     SmallVector<EVT, 4> OldRetTys;
9070     SmallVector<uint64_t, 4> OldOffsets;
9071     RetTys.swap(OldRetTys);
9072     Offsets.swap(OldOffsets);
9073 
9074     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9075       EVT RetVT = OldRetTys[i];
9076       uint64_t Offset = OldOffsets[i];
9077       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9078       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9079       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9080       RetTys.append(NumRegs, RegisterVT);
9081       for (unsigned j = 0; j != NumRegs; ++j)
9082         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9083     }
9084   }
9085 
9086   SmallVector<ISD::OutputArg, 4> Outs;
9087   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9088 
9089   bool CanLowerReturn =
9090       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9091                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9092 
9093   SDValue DemoteStackSlot;
9094   int DemoteStackIdx = -100;
9095   if (!CanLowerReturn) {
9096     // FIXME: equivalent assert?
9097     // assert(!CS.hasInAllocaArgument() &&
9098     //        "sret demotion is incompatible with inalloca");
9099     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9100     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9101     MachineFunction &MF = CLI.DAG.getMachineFunction();
9102     DemoteStackIdx =
9103         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9104     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9105                                               DL.getAllocaAddrSpace());
9106 
9107     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9108     ArgListEntry Entry;
9109     Entry.Node = DemoteStackSlot;
9110     Entry.Ty = StackSlotPtrType;
9111     Entry.IsSExt = false;
9112     Entry.IsZExt = false;
9113     Entry.IsInReg = false;
9114     Entry.IsSRet = true;
9115     Entry.IsNest = false;
9116     Entry.IsByVal = false;
9117     Entry.IsReturned = false;
9118     Entry.IsSwiftSelf = false;
9119     Entry.IsSwiftError = false;
9120     Entry.IsCFGuardTarget = false;
9121     Entry.Alignment = Alignment;
9122     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9123     CLI.NumFixedArgs += 1;
9124     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9125 
9126     // sret demotion isn't compatible with tail-calls, since the sret argument
9127     // points into the callers stack frame.
9128     CLI.IsTailCall = false;
9129   } else {
9130     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9131         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9132     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9133       ISD::ArgFlagsTy Flags;
9134       if (NeedsRegBlock) {
9135         Flags.setInConsecutiveRegs();
9136         if (I == RetTys.size() - 1)
9137           Flags.setInConsecutiveRegsLast();
9138       }
9139       EVT VT = RetTys[I];
9140       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9141                                                      CLI.CallConv, VT);
9142       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9143                                                        CLI.CallConv, VT);
9144       for (unsigned i = 0; i != NumRegs; ++i) {
9145         ISD::InputArg MyFlags;
9146         MyFlags.Flags = Flags;
9147         MyFlags.VT = RegisterVT;
9148         MyFlags.ArgVT = VT;
9149         MyFlags.Used = CLI.IsReturnValueUsed;
9150         if (CLI.RetTy->isPointerTy()) {
9151           MyFlags.Flags.setPointer();
9152           MyFlags.Flags.setPointerAddrSpace(
9153               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9154         }
9155         if (CLI.RetSExt)
9156           MyFlags.Flags.setSExt();
9157         if (CLI.RetZExt)
9158           MyFlags.Flags.setZExt();
9159         if (CLI.IsInReg)
9160           MyFlags.Flags.setInReg();
9161         CLI.Ins.push_back(MyFlags);
9162       }
9163     }
9164   }
9165 
9166   // We push in swifterror return as the last element of CLI.Ins.
9167   ArgListTy &Args = CLI.getArgs();
9168   if (supportSwiftError()) {
9169     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9170       if (Args[i].IsSwiftError) {
9171         ISD::InputArg MyFlags;
9172         MyFlags.VT = getPointerTy(DL);
9173         MyFlags.ArgVT = EVT(getPointerTy(DL));
9174         MyFlags.Flags.setSwiftError();
9175         CLI.Ins.push_back(MyFlags);
9176       }
9177     }
9178   }
9179 
9180   // Handle all of the outgoing arguments.
9181   CLI.Outs.clear();
9182   CLI.OutVals.clear();
9183   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9184     SmallVector<EVT, 4> ValueVTs;
9185     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9186     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9187     Type *FinalType = Args[i].Ty;
9188     if (Args[i].IsByVal)
9189       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9190     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9191         FinalType, CLI.CallConv, CLI.IsVarArg);
9192     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9193          ++Value) {
9194       EVT VT = ValueVTs[Value];
9195       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9196       SDValue Op = SDValue(Args[i].Node.getNode(),
9197                            Args[i].Node.getResNo() + Value);
9198       ISD::ArgFlagsTy Flags;
9199 
9200       // Certain targets (such as MIPS), may have a different ABI alignment
9201       // for a type depending on the context. Give the target a chance to
9202       // specify the alignment it wants.
9203       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9204 
9205       if (Args[i].Ty->isPointerTy()) {
9206         Flags.setPointer();
9207         Flags.setPointerAddrSpace(
9208             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9209       }
9210       if (Args[i].IsZExt)
9211         Flags.setZExt();
9212       if (Args[i].IsSExt)
9213         Flags.setSExt();
9214       if (Args[i].IsInReg) {
9215         // If we are using vectorcall calling convention, a structure that is
9216         // passed InReg - is surely an HVA
9217         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9218             isa<StructType>(FinalType)) {
9219           // The first value of a structure is marked
9220           if (0 == Value)
9221             Flags.setHvaStart();
9222           Flags.setHva();
9223         }
9224         // Set InReg Flag
9225         Flags.setInReg();
9226       }
9227       if (Args[i].IsSRet)
9228         Flags.setSRet();
9229       if (Args[i].IsSwiftSelf)
9230         Flags.setSwiftSelf();
9231       if (Args[i].IsSwiftError)
9232         Flags.setSwiftError();
9233       if (Args[i].IsCFGuardTarget)
9234         Flags.setCFGuardTarget();
9235       if (Args[i].IsByVal)
9236         Flags.setByVal();
9237       if (Args[i].IsPreallocated) {
9238         Flags.setPreallocated();
9239         // Set the byval flag for CCAssignFn callbacks that don't know about
9240         // preallocated.  This way we can know how many bytes we should've
9241         // allocated and how many bytes a callee cleanup function will pop.  If
9242         // we port preallocated to more targets, we'll have to add custom
9243         // preallocated handling in the various CC lowering callbacks.
9244         Flags.setByVal();
9245       }
9246       if (Args[i].IsInAlloca) {
9247         Flags.setInAlloca();
9248         // Set the byval flag for CCAssignFn callbacks that don't know about
9249         // inalloca.  This way we can know how many bytes we should've allocated
9250         // and how many bytes a callee cleanup function will pop.  If we port
9251         // inalloca to more targets, we'll have to add custom inalloca handling
9252         // in the various CC lowering callbacks.
9253         Flags.setByVal();
9254       }
9255       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9256         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9257         Type *ElementTy = Ty->getElementType();
9258 
9259         unsigned FrameSize = DL.getTypeAllocSize(
9260             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9261         Flags.setByValSize(FrameSize);
9262 
9263         // info is not there but there are cases it cannot get right.
9264         Align FrameAlign;
9265         if (auto MA = Args[i].Alignment)
9266           FrameAlign = *MA;
9267         else
9268           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9269         Flags.setByValAlign(FrameAlign);
9270       }
9271       if (Args[i].IsNest)
9272         Flags.setNest();
9273       if (NeedsRegBlock)
9274         Flags.setInConsecutiveRegs();
9275       Flags.setOrigAlign(OriginalAlignment);
9276 
9277       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9278                                                  CLI.CallConv, VT);
9279       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9280                                                         CLI.CallConv, VT);
9281       SmallVector<SDValue, 4> Parts(NumParts);
9282       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9283 
9284       if (Args[i].IsSExt)
9285         ExtendKind = ISD::SIGN_EXTEND;
9286       else if (Args[i].IsZExt)
9287         ExtendKind = ISD::ZERO_EXTEND;
9288 
9289       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9290       // for now.
9291       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9292           CanLowerReturn) {
9293         assert((CLI.RetTy == Args[i].Ty ||
9294                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9295                  CLI.RetTy->getPointerAddressSpace() ==
9296                      Args[i].Ty->getPointerAddressSpace())) &&
9297                RetTys.size() == NumValues && "unexpected use of 'returned'");
9298         // Before passing 'returned' to the target lowering code, ensure that
9299         // either the register MVT and the actual EVT are the same size or that
9300         // the return value and argument are extended in the same way; in these
9301         // cases it's safe to pass the argument register value unchanged as the
9302         // return register value (although it's at the target's option whether
9303         // to do so)
9304         // TODO: allow code generation to take advantage of partially preserved
9305         // registers rather than clobbering the entire register when the
9306         // parameter extension method is not compatible with the return
9307         // extension method
9308         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9309             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9310              CLI.RetZExt == Args[i].IsZExt))
9311           Flags.setReturned();
9312       }
9313 
9314       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9315                      CLI.CallConv, ExtendKind);
9316 
9317       for (unsigned j = 0; j != NumParts; ++j) {
9318         // if it isn't first piece, alignment must be 1
9319         // For scalable vectors the scalable part is currently handled
9320         // by individual targets, so we just use the known minimum size here.
9321         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9322                     i < CLI.NumFixedArgs, i,
9323                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9324         if (NumParts > 1 && j == 0)
9325           MyFlags.Flags.setSplit();
9326         else if (j != 0) {
9327           MyFlags.Flags.setOrigAlign(Align(1));
9328           if (j == NumParts - 1)
9329             MyFlags.Flags.setSplitEnd();
9330         }
9331 
9332         CLI.Outs.push_back(MyFlags);
9333         CLI.OutVals.push_back(Parts[j]);
9334       }
9335 
9336       if (NeedsRegBlock && Value == NumValues - 1)
9337         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9338     }
9339   }
9340 
9341   SmallVector<SDValue, 4> InVals;
9342   CLI.Chain = LowerCall(CLI, InVals);
9343 
9344   // Update CLI.InVals to use outside of this function.
9345   CLI.InVals = InVals;
9346 
9347   // Verify that the target's LowerCall behaved as expected.
9348   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9349          "LowerCall didn't return a valid chain!");
9350   assert((!CLI.IsTailCall || InVals.empty()) &&
9351          "LowerCall emitted a return value for a tail call!");
9352   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9353          "LowerCall didn't emit the correct number of values!");
9354 
9355   // For a tail call, the return value is merely live-out and there aren't
9356   // any nodes in the DAG representing it. Return a special value to
9357   // indicate that a tail call has been emitted and no more Instructions
9358   // should be processed in the current block.
9359   if (CLI.IsTailCall) {
9360     CLI.DAG.setRoot(CLI.Chain);
9361     return std::make_pair(SDValue(), SDValue());
9362   }
9363 
9364 #ifndef NDEBUG
9365   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9366     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9367     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9368            "LowerCall emitted a value with the wrong type!");
9369   }
9370 #endif
9371 
9372   SmallVector<SDValue, 4> ReturnValues;
9373   if (!CanLowerReturn) {
9374     // The instruction result is the result of loading from the
9375     // hidden sret parameter.
9376     SmallVector<EVT, 1> PVTs;
9377     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9378 
9379     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9380     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9381     EVT PtrVT = PVTs[0];
9382 
9383     unsigned NumValues = RetTys.size();
9384     ReturnValues.resize(NumValues);
9385     SmallVector<SDValue, 4> Chains(NumValues);
9386 
9387     // An aggregate return value cannot wrap around the address space, so
9388     // offsets to its parts don't wrap either.
9389     SDNodeFlags Flags;
9390     Flags.setNoUnsignedWrap(true);
9391 
9392     MachineFunction &MF = CLI.DAG.getMachineFunction();
9393     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9394     for (unsigned i = 0; i < NumValues; ++i) {
9395       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9396                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9397                                                         PtrVT), Flags);
9398       SDValue L = CLI.DAG.getLoad(
9399           RetTys[i], CLI.DL, CLI.Chain, Add,
9400           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9401                                             DemoteStackIdx, Offsets[i]),
9402           HiddenSRetAlign);
9403       ReturnValues[i] = L;
9404       Chains[i] = L.getValue(1);
9405     }
9406 
9407     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9408   } else {
9409     // Collect the legal value parts into potentially illegal values
9410     // that correspond to the original function's return values.
9411     Optional<ISD::NodeType> AssertOp;
9412     if (CLI.RetSExt)
9413       AssertOp = ISD::AssertSext;
9414     else if (CLI.RetZExt)
9415       AssertOp = ISD::AssertZext;
9416     unsigned CurReg = 0;
9417     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9418       EVT VT = RetTys[I];
9419       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9420                                                      CLI.CallConv, VT);
9421       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9422                                                        CLI.CallConv, VT);
9423 
9424       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9425                                               NumRegs, RegisterVT, VT, nullptr,
9426                                               CLI.CallConv, AssertOp));
9427       CurReg += NumRegs;
9428     }
9429 
9430     // For a function returning void, there is no return value. We can't create
9431     // such a node, so we just return a null return value in that case. In
9432     // that case, nothing will actually look at the value.
9433     if (ReturnValues.empty())
9434       return std::make_pair(SDValue(), CLI.Chain);
9435   }
9436 
9437   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9438                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9439   return std::make_pair(Res, CLI.Chain);
9440 }
9441 
9442 void TargetLowering::LowerOperationWrapper(SDNode *N,
9443                                            SmallVectorImpl<SDValue> &Results,
9444                                            SelectionDAG &DAG) const {
9445   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9446     Results.push_back(Res);
9447 }
9448 
9449 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9450   llvm_unreachable("LowerOperation not implemented for this target!");
9451 }
9452 
9453 void
9454 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9455   SDValue Op = getNonRegisterValue(V);
9456   assert((Op.getOpcode() != ISD::CopyFromReg ||
9457           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9458          "Copy from a reg to the same reg!");
9459   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9460 
9461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9462   // If this is an InlineAsm we have to match the registers required, not the
9463   // notional registers required by the type.
9464 
9465   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9466                    None); // This is not an ABI copy.
9467   SDValue Chain = DAG.getEntryNode();
9468 
9469   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9470                               FuncInfo.PreferredExtendType.end())
9471                                  ? ISD::ANY_EXTEND
9472                                  : FuncInfo.PreferredExtendType[V];
9473   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9474   PendingExports.push_back(Chain);
9475 }
9476 
9477 #include "llvm/CodeGen/SelectionDAGISel.h"
9478 
9479 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9480 /// entry block, return true.  This includes arguments used by switches, since
9481 /// the switch may expand into multiple basic blocks.
9482 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9483   // With FastISel active, we may be splitting blocks, so force creation
9484   // of virtual registers for all non-dead arguments.
9485   if (FastISel)
9486     return A->use_empty();
9487 
9488   const BasicBlock &Entry = A->getParent()->front();
9489   for (const User *U : A->users())
9490     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9491       return false;  // Use not in entry block.
9492 
9493   return true;
9494 }
9495 
9496 using ArgCopyElisionMapTy =
9497     DenseMap<const Argument *,
9498              std::pair<const AllocaInst *, const StoreInst *>>;
9499 
9500 /// Scan the entry block of the function in FuncInfo for arguments that look
9501 /// like copies into a local alloca. Record any copied arguments in
9502 /// ArgCopyElisionCandidates.
9503 static void
9504 findArgumentCopyElisionCandidates(const DataLayout &DL,
9505                                   FunctionLoweringInfo *FuncInfo,
9506                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9507   // Record the state of every static alloca used in the entry block. Argument
9508   // allocas are all used in the entry block, so we need approximately as many
9509   // entries as we have arguments.
9510   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9511   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9512   unsigned NumArgs = FuncInfo->Fn->arg_size();
9513   StaticAllocas.reserve(NumArgs * 2);
9514 
9515   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9516     if (!V)
9517       return nullptr;
9518     V = V->stripPointerCasts();
9519     const auto *AI = dyn_cast<AllocaInst>(V);
9520     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9521       return nullptr;
9522     auto Iter = StaticAllocas.insert({AI, Unknown});
9523     return &Iter.first->second;
9524   };
9525 
9526   // Look for stores of arguments to static allocas. Look through bitcasts and
9527   // GEPs to handle type coercions, as long as the alloca is fully initialized
9528   // by the store. Any non-store use of an alloca escapes it and any subsequent
9529   // unanalyzed store might write it.
9530   // FIXME: Handle structs initialized with multiple stores.
9531   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9532     // Look for stores, and handle non-store uses conservatively.
9533     const auto *SI = dyn_cast<StoreInst>(&I);
9534     if (!SI) {
9535       // We will look through cast uses, so ignore them completely.
9536       if (I.isCast())
9537         continue;
9538       // Ignore debug info intrinsics, they don't escape or store to allocas.
9539       if (isa<DbgInfoIntrinsic>(I))
9540         continue;
9541       // This is an unknown instruction. Assume it escapes or writes to all
9542       // static alloca operands.
9543       for (const Use &U : I.operands()) {
9544         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9545           *Info = StaticAllocaInfo::Clobbered;
9546       }
9547       continue;
9548     }
9549 
9550     // If the stored value is a static alloca, mark it as escaped.
9551     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9552       *Info = StaticAllocaInfo::Clobbered;
9553 
9554     // Check if the destination is a static alloca.
9555     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9556     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9557     if (!Info)
9558       continue;
9559     const AllocaInst *AI = cast<AllocaInst>(Dst);
9560 
9561     // Skip allocas that have been initialized or clobbered.
9562     if (*Info != StaticAllocaInfo::Unknown)
9563       continue;
9564 
9565     // Check if the stored value is an argument, and that this store fully
9566     // initializes the alloca. Don't elide copies from the same argument twice.
9567     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9568     const auto *Arg = dyn_cast<Argument>(Val);
9569     if (!Arg || Arg->hasPassPointeeByValueAttr() ||
9570         Arg->getType()->isEmptyTy() ||
9571         DL.getTypeStoreSize(Arg->getType()) !=
9572             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9573         ArgCopyElisionCandidates.count(Arg)) {
9574       *Info = StaticAllocaInfo::Clobbered;
9575       continue;
9576     }
9577 
9578     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9579                       << '\n');
9580 
9581     // Mark this alloca and store for argument copy elision.
9582     *Info = StaticAllocaInfo::Elidable;
9583     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9584 
9585     // Stop scanning if we've seen all arguments. This will happen early in -O0
9586     // builds, which is useful, because -O0 builds have large entry blocks and
9587     // many allocas.
9588     if (ArgCopyElisionCandidates.size() == NumArgs)
9589       break;
9590   }
9591 }
9592 
9593 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9594 /// ArgVal is a load from a suitable fixed stack object.
9595 static void tryToElideArgumentCopy(
9596     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9597     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9598     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9599     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9600     SDValue ArgVal, bool &ArgHasUses) {
9601   // Check if this is a load from a fixed stack object.
9602   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9603   if (!LNode)
9604     return;
9605   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9606   if (!FINode)
9607     return;
9608 
9609   // Check that the fixed stack object is the right size and alignment.
9610   // Look at the alignment that the user wrote on the alloca instead of looking
9611   // at the stack object.
9612   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9613   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9614   const AllocaInst *AI = ArgCopyIter->second.first;
9615   int FixedIndex = FINode->getIndex();
9616   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9617   int OldIndex = AllocaIndex;
9618   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9619   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9620     LLVM_DEBUG(
9621         dbgs() << "  argument copy elision failed due to bad fixed stack "
9622                   "object size\n");
9623     return;
9624   }
9625   Align RequiredAlignment = AI->getAlign();
9626   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9627     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9628                          "greater than stack argument alignment ("
9629                       << DebugStr(RequiredAlignment) << " vs "
9630                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9631     return;
9632   }
9633 
9634   // Perform the elision. Delete the old stack object and replace its only use
9635   // in the variable info map. Mark the stack object as mutable.
9636   LLVM_DEBUG({
9637     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9638            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9639            << '\n';
9640   });
9641   MFI.RemoveStackObject(OldIndex);
9642   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9643   AllocaIndex = FixedIndex;
9644   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9645   Chains.push_back(ArgVal.getValue(1));
9646 
9647   // Avoid emitting code for the store implementing the copy.
9648   const StoreInst *SI = ArgCopyIter->second.second;
9649   ElidedArgCopyInstrs.insert(SI);
9650 
9651   // Check for uses of the argument again so that we can avoid exporting ArgVal
9652   // if it is't used by anything other than the store.
9653   for (const Value *U : Arg.users()) {
9654     if (U != SI) {
9655       ArgHasUses = true;
9656       break;
9657     }
9658   }
9659 }
9660 
9661 void SelectionDAGISel::LowerArguments(const Function &F) {
9662   SelectionDAG &DAG = SDB->DAG;
9663   SDLoc dl = SDB->getCurSDLoc();
9664   const DataLayout &DL = DAG.getDataLayout();
9665   SmallVector<ISD::InputArg, 16> Ins;
9666 
9667   // In Naked functions we aren't going to save any registers.
9668   if (F.hasFnAttribute(Attribute::Naked))
9669     return;
9670 
9671   if (!FuncInfo->CanLowerReturn) {
9672     // Put in an sret pointer parameter before all the other parameters.
9673     SmallVector<EVT, 1> ValueVTs;
9674     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9675                     F.getReturnType()->getPointerTo(
9676                         DAG.getDataLayout().getAllocaAddrSpace()),
9677                     ValueVTs);
9678 
9679     // NOTE: Assuming that a pointer will never break down to more than one VT
9680     // or one register.
9681     ISD::ArgFlagsTy Flags;
9682     Flags.setSRet();
9683     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9684     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9685                          ISD::InputArg::NoArgIndex, 0);
9686     Ins.push_back(RetArg);
9687   }
9688 
9689   // Look for stores of arguments to static allocas. Mark such arguments with a
9690   // flag to ask the target to give us the memory location of that argument if
9691   // available.
9692   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9693   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9694                                     ArgCopyElisionCandidates);
9695 
9696   // Set up the incoming argument description vector.
9697   for (const Argument &Arg : F.args()) {
9698     unsigned ArgNo = Arg.getArgNo();
9699     SmallVector<EVT, 4> ValueVTs;
9700     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9701     bool isArgValueUsed = !Arg.use_empty();
9702     unsigned PartBase = 0;
9703     Type *FinalType = Arg.getType();
9704     if (Arg.hasAttribute(Attribute::ByVal))
9705       FinalType = Arg.getParamByValType();
9706     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9707         FinalType, F.getCallingConv(), F.isVarArg());
9708     for (unsigned Value = 0, NumValues = ValueVTs.size();
9709          Value != NumValues; ++Value) {
9710       EVT VT = ValueVTs[Value];
9711       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9712       ISD::ArgFlagsTy Flags;
9713 
9714       // Certain targets (such as MIPS), may have a different ABI alignment
9715       // for a type depending on the context. Give the target a chance to
9716       // specify the alignment it wants.
9717       const Align OriginalAlignment(
9718           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9719 
9720       if (Arg.getType()->isPointerTy()) {
9721         Flags.setPointer();
9722         Flags.setPointerAddrSpace(
9723             cast<PointerType>(Arg.getType())->getAddressSpace());
9724       }
9725       if (Arg.hasAttribute(Attribute::ZExt))
9726         Flags.setZExt();
9727       if (Arg.hasAttribute(Attribute::SExt))
9728         Flags.setSExt();
9729       if (Arg.hasAttribute(Attribute::InReg)) {
9730         // If we are using vectorcall calling convention, a structure that is
9731         // passed InReg - is surely an HVA
9732         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9733             isa<StructType>(Arg.getType())) {
9734           // The first value of a structure is marked
9735           if (0 == Value)
9736             Flags.setHvaStart();
9737           Flags.setHva();
9738         }
9739         // Set InReg Flag
9740         Flags.setInReg();
9741       }
9742       if (Arg.hasAttribute(Attribute::StructRet))
9743         Flags.setSRet();
9744       if (Arg.hasAttribute(Attribute::SwiftSelf))
9745         Flags.setSwiftSelf();
9746       if (Arg.hasAttribute(Attribute::SwiftError))
9747         Flags.setSwiftError();
9748       if (Arg.hasAttribute(Attribute::ByVal))
9749         Flags.setByVal();
9750       if (Arg.hasAttribute(Attribute::InAlloca)) {
9751         Flags.setInAlloca();
9752         // Set the byval flag for CCAssignFn callbacks that don't know about
9753         // inalloca.  This way we can know how many bytes we should've allocated
9754         // and how many bytes a callee cleanup function will pop.  If we port
9755         // inalloca to more targets, we'll have to add custom inalloca handling
9756         // in the various CC lowering callbacks.
9757         Flags.setByVal();
9758       }
9759       if (Arg.hasAttribute(Attribute::Preallocated)) {
9760         Flags.setPreallocated();
9761         // Set the byval flag for CCAssignFn callbacks that don't know about
9762         // preallocated.  This way we can know how many bytes we should've
9763         // allocated and how many bytes a callee cleanup function will pop.  If
9764         // we port preallocated to more targets, we'll have to add custom
9765         // preallocated handling in the various CC lowering callbacks.
9766         Flags.setByVal();
9767       }
9768       if (F.getCallingConv() == CallingConv::X86_INTR) {
9769         // IA Interrupt passes frame (1st parameter) by value in the stack.
9770         if (ArgNo == 0)
9771           Flags.setByVal();
9772       }
9773       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) {
9774         Type *ElementTy = Arg.getParamByValType();
9775 
9776         // For ByVal, size and alignment should be passed from FE.  BE will
9777         // guess if this info is not there but there are cases it cannot get
9778         // right.
9779         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9780         Flags.setByValSize(FrameSize);
9781 
9782         unsigned FrameAlign;
9783         if (Arg.getParamAlignment())
9784           FrameAlign = Arg.getParamAlignment();
9785         else
9786           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9787         Flags.setByValAlign(Align(FrameAlign));
9788       }
9789       if (Arg.hasAttribute(Attribute::Nest))
9790         Flags.setNest();
9791       if (NeedsRegBlock)
9792         Flags.setInConsecutiveRegs();
9793       Flags.setOrigAlign(OriginalAlignment);
9794       if (ArgCopyElisionCandidates.count(&Arg))
9795         Flags.setCopyElisionCandidate();
9796       if (Arg.hasAttribute(Attribute::Returned))
9797         Flags.setReturned();
9798 
9799       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9800           *CurDAG->getContext(), F.getCallingConv(), VT);
9801       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9802           *CurDAG->getContext(), F.getCallingConv(), VT);
9803       for (unsigned i = 0; i != NumRegs; ++i) {
9804         // For scalable vectors, use the minimum size; individual targets
9805         // are responsible for handling scalable vector arguments and
9806         // return values.
9807         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9808                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9809         if (NumRegs > 1 && i == 0)
9810           MyFlags.Flags.setSplit();
9811         // if it isn't first piece, alignment must be 1
9812         else if (i > 0) {
9813           MyFlags.Flags.setOrigAlign(Align(1));
9814           if (i == NumRegs - 1)
9815             MyFlags.Flags.setSplitEnd();
9816         }
9817         Ins.push_back(MyFlags);
9818       }
9819       if (NeedsRegBlock && Value == NumValues - 1)
9820         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9821       PartBase += VT.getStoreSize().getKnownMinSize();
9822     }
9823   }
9824 
9825   // Call the target to set up the argument values.
9826   SmallVector<SDValue, 8> InVals;
9827   SDValue NewRoot = TLI->LowerFormalArguments(
9828       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9829 
9830   // Verify that the target's LowerFormalArguments behaved as expected.
9831   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9832          "LowerFormalArguments didn't return a valid chain!");
9833   assert(InVals.size() == Ins.size() &&
9834          "LowerFormalArguments didn't emit the correct number of values!");
9835   LLVM_DEBUG({
9836     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9837       assert(InVals[i].getNode() &&
9838              "LowerFormalArguments emitted a null value!");
9839       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9840              "LowerFormalArguments emitted a value with the wrong type!");
9841     }
9842   });
9843 
9844   // Update the DAG with the new chain value resulting from argument lowering.
9845   DAG.setRoot(NewRoot);
9846 
9847   // Set up the argument values.
9848   unsigned i = 0;
9849   if (!FuncInfo->CanLowerReturn) {
9850     // Create a virtual register for the sret pointer, and put in a copy
9851     // from the sret argument into it.
9852     SmallVector<EVT, 1> ValueVTs;
9853     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9854                     F.getReturnType()->getPointerTo(
9855                         DAG.getDataLayout().getAllocaAddrSpace()),
9856                     ValueVTs);
9857     MVT VT = ValueVTs[0].getSimpleVT();
9858     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9859     Optional<ISD::NodeType> AssertOp = None;
9860     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9861                                         nullptr, F.getCallingConv(), AssertOp);
9862 
9863     MachineFunction& MF = SDB->DAG.getMachineFunction();
9864     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9865     Register SRetReg =
9866         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9867     FuncInfo->DemoteRegister = SRetReg;
9868     NewRoot =
9869         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9870     DAG.setRoot(NewRoot);
9871 
9872     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9873     ++i;
9874   }
9875 
9876   SmallVector<SDValue, 4> Chains;
9877   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9878   for (const Argument &Arg : F.args()) {
9879     SmallVector<SDValue, 4> ArgValues;
9880     SmallVector<EVT, 4> ValueVTs;
9881     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9882     unsigned NumValues = ValueVTs.size();
9883     if (NumValues == 0)
9884       continue;
9885 
9886     bool ArgHasUses = !Arg.use_empty();
9887 
9888     // Elide the copying store if the target loaded this argument from a
9889     // suitable fixed stack object.
9890     if (Ins[i].Flags.isCopyElisionCandidate()) {
9891       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9892                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9893                              InVals[i], ArgHasUses);
9894     }
9895 
9896     // If this argument is unused then remember its value. It is used to generate
9897     // debugging information.
9898     bool isSwiftErrorArg =
9899         TLI->supportSwiftError() &&
9900         Arg.hasAttribute(Attribute::SwiftError);
9901     if (!ArgHasUses && !isSwiftErrorArg) {
9902       SDB->setUnusedArgValue(&Arg, InVals[i]);
9903 
9904       // Also remember any frame index for use in FastISel.
9905       if (FrameIndexSDNode *FI =
9906           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9907         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9908     }
9909 
9910     for (unsigned Val = 0; Val != NumValues; ++Val) {
9911       EVT VT = ValueVTs[Val];
9912       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9913                                                       F.getCallingConv(), VT);
9914       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9915           *CurDAG->getContext(), F.getCallingConv(), VT);
9916 
9917       // Even an apparent 'unused' swifterror argument needs to be returned. So
9918       // we do generate a copy for it that can be used on return from the
9919       // function.
9920       if (ArgHasUses || isSwiftErrorArg) {
9921         Optional<ISD::NodeType> AssertOp;
9922         if (Arg.hasAttribute(Attribute::SExt))
9923           AssertOp = ISD::AssertSext;
9924         else if (Arg.hasAttribute(Attribute::ZExt))
9925           AssertOp = ISD::AssertZext;
9926 
9927         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9928                                              PartVT, VT, nullptr,
9929                                              F.getCallingConv(), AssertOp));
9930       }
9931 
9932       i += NumParts;
9933     }
9934 
9935     // We don't need to do anything else for unused arguments.
9936     if (ArgValues.empty())
9937       continue;
9938 
9939     // Note down frame index.
9940     if (FrameIndexSDNode *FI =
9941         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9942       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9943 
9944     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9945                                      SDB->getCurSDLoc());
9946 
9947     SDB->setValue(&Arg, Res);
9948     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9949       // We want to associate the argument with the frame index, among
9950       // involved operands, that correspond to the lowest address. The
9951       // getCopyFromParts function, called earlier, is swapping the order of
9952       // the operands to BUILD_PAIR depending on endianness. The result of
9953       // that swapping is that the least significant bits of the argument will
9954       // be in the first operand of the BUILD_PAIR node, and the most
9955       // significant bits will be in the second operand.
9956       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9957       if (LoadSDNode *LNode =
9958           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9959         if (FrameIndexSDNode *FI =
9960             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9961           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9962     }
9963 
9964     // Analyses past this point are naive and don't expect an assertion.
9965     if (Res.getOpcode() == ISD::AssertZext)
9966       Res = Res.getOperand(0);
9967 
9968     // Update the SwiftErrorVRegDefMap.
9969     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9970       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9971       if (Register::isVirtualRegister(Reg))
9972         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9973                                    Reg);
9974     }
9975 
9976     // If this argument is live outside of the entry block, insert a copy from
9977     // wherever we got it to the vreg that other BB's will reference it as.
9978     if (Res.getOpcode() == ISD::CopyFromReg) {
9979       // If we can, though, try to skip creating an unnecessary vreg.
9980       // FIXME: This isn't very clean... it would be nice to make this more
9981       // general.
9982       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9983       if (Register::isVirtualRegister(Reg)) {
9984         FuncInfo->ValueMap[&Arg] = Reg;
9985         continue;
9986       }
9987     }
9988     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9989       FuncInfo->InitializeRegForValue(&Arg);
9990       SDB->CopyToExportRegsIfNeeded(&Arg);
9991     }
9992   }
9993 
9994   if (!Chains.empty()) {
9995     Chains.push_back(NewRoot);
9996     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9997   }
9998 
9999   DAG.setRoot(NewRoot);
10000 
10001   assert(i == InVals.size() && "Argument register count mismatch!");
10002 
10003   // If any argument copy elisions occurred and we have debug info, update the
10004   // stale frame indices used in the dbg.declare variable info table.
10005   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10006   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10007     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10008       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10009       if (I != ArgCopyElisionFrameIndexMap.end())
10010         VI.Slot = I->second;
10011     }
10012   }
10013 
10014   // Finally, if the target has anything special to do, allow it to do so.
10015   emitFunctionEntryCode();
10016 }
10017 
10018 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10019 /// ensure constants are generated when needed.  Remember the virtual registers
10020 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10021 /// directly add them, because expansion might result in multiple MBB's for one
10022 /// BB.  As such, the start of the BB might correspond to a different MBB than
10023 /// the end.
10024 void
10025 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10026   const Instruction *TI = LLVMBB->getTerminator();
10027 
10028   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10029 
10030   // Check PHI nodes in successors that expect a value to be available from this
10031   // block.
10032   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10033     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10034     if (!isa<PHINode>(SuccBB->begin())) continue;
10035     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10036 
10037     // If this terminator has multiple identical successors (common for
10038     // switches), only handle each succ once.
10039     if (!SuccsHandled.insert(SuccMBB).second)
10040       continue;
10041 
10042     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10043 
10044     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10045     // nodes and Machine PHI nodes, but the incoming operands have not been
10046     // emitted yet.
10047     for (const PHINode &PN : SuccBB->phis()) {
10048       // Ignore dead phi's.
10049       if (PN.use_empty())
10050         continue;
10051 
10052       // Skip empty types
10053       if (PN.getType()->isEmptyTy())
10054         continue;
10055 
10056       unsigned Reg;
10057       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10058 
10059       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10060         unsigned &RegOut = ConstantsOut[C];
10061         if (RegOut == 0) {
10062           RegOut = FuncInfo.CreateRegs(C);
10063           CopyValueToVirtualRegister(C, RegOut);
10064         }
10065         Reg = RegOut;
10066       } else {
10067         DenseMap<const Value *, Register>::iterator I =
10068           FuncInfo.ValueMap.find(PHIOp);
10069         if (I != FuncInfo.ValueMap.end())
10070           Reg = I->second;
10071         else {
10072           assert(isa<AllocaInst>(PHIOp) &&
10073                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10074                  "Didn't codegen value into a register!??");
10075           Reg = FuncInfo.CreateRegs(PHIOp);
10076           CopyValueToVirtualRegister(PHIOp, Reg);
10077         }
10078       }
10079 
10080       // Remember that this register needs to added to the machine PHI node as
10081       // the input for this MBB.
10082       SmallVector<EVT, 4> ValueVTs;
10083       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10084       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10085       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10086         EVT VT = ValueVTs[vti];
10087         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10088         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10089           FuncInfo.PHINodesToUpdate.push_back(
10090               std::make_pair(&*MBBI++, Reg + i));
10091         Reg += NumRegisters;
10092       }
10093     }
10094   }
10095 
10096   ConstantsOut.clear();
10097 }
10098 
10099 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10100 /// is 0.
10101 MachineBasicBlock *
10102 SelectionDAGBuilder::StackProtectorDescriptor::
10103 AddSuccessorMBB(const BasicBlock *BB,
10104                 MachineBasicBlock *ParentMBB,
10105                 bool IsLikely,
10106                 MachineBasicBlock *SuccMBB) {
10107   // If SuccBB has not been created yet, create it.
10108   if (!SuccMBB) {
10109     MachineFunction *MF = ParentMBB->getParent();
10110     MachineFunction::iterator BBI(ParentMBB);
10111     SuccMBB = MF->CreateMachineBasicBlock(BB);
10112     MF->insert(++BBI, SuccMBB);
10113   }
10114   // Add it as a successor of ParentMBB.
10115   ParentMBB->addSuccessor(
10116       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10117   return SuccMBB;
10118 }
10119 
10120 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10121   MachineFunction::iterator I(MBB);
10122   if (++I == FuncInfo.MF->end())
10123     return nullptr;
10124   return &*I;
10125 }
10126 
10127 /// During lowering new call nodes can be created (such as memset, etc.).
10128 /// Those will become new roots of the current DAG, but complications arise
10129 /// when they are tail calls. In such cases, the call lowering will update
10130 /// the root, but the builder still needs to know that a tail call has been
10131 /// lowered in order to avoid generating an additional return.
10132 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10133   // If the node is null, we do have a tail call.
10134   if (MaybeTC.getNode() != nullptr)
10135     DAG.setRoot(MaybeTC);
10136   else
10137     HasTailCall = true;
10138 }
10139 
10140 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10141                                         MachineBasicBlock *SwitchMBB,
10142                                         MachineBasicBlock *DefaultMBB) {
10143   MachineFunction *CurMF = FuncInfo.MF;
10144   MachineBasicBlock *NextMBB = nullptr;
10145   MachineFunction::iterator BBI(W.MBB);
10146   if (++BBI != FuncInfo.MF->end())
10147     NextMBB = &*BBI;
10148 
10149   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10150 
10151   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10152 
10153   if (Size == 2 && W.MBB == SwitchMBB) {
10154     // If any two of the cases has the same destination, and if one value
10155     // is the same as the other, but has one bit unset that the other has set,
10156     // use bit manipulation to do two compares at once.  For example:
10157     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10158     // TODO: This could be extended to merge any 2 cases in switches with 3
10159     // cases.
10160     // TODO: Handle cases where W.CaseBB != SwitchBB.
10161     CaseCluster &Small = *W.FirstCluster;
10162     CaseCluster &Big = *W.LastCluster;
10163 
10164     if (Small.Low == Small.High && Big.Low == Big.High &&
10165         Small.MBB == Big.MBB) {
10166       const APInt &SmallValue = Small.Low->getValue();
10167       const APInt &BigValue = Big.Low->getValue();
10168 
10169       // Check that there is only one bit different.
10170       APInt CommonBit = BigValue ^ SmallValue;
10171       if (CommonBit.isPowerOf2()) {
10172         SDValue CondLHS = getValue(Cond);
10173         EVT VT = CondLHS.getValueType();
10174         SDLoc DL = getCurSDLoc();
10175 
10176         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10177                                  DAG.getConstant(CommonBit, DL, VT));
10178         SDValue Cond = DAG.getSetCC(
10179             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10180             ISD::SETEQ);
10181 
10182         // Update successor info.
10183         // Both Small and Big will jump to Small.BB, so we sum up the
10184         // probabilities.
10185         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10186         if (BPI)
10187           addSuccessorWithProb(
10188               SwitchMBB, DefaultMBB,
10189               // The default destination is the first successor in IR.
10190               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10191         else
10192           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10193 
10194         // Insert the true branch.
10195         SDValue BrCond =
10196             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10197                         DAG.getBasicBlock(Small.MBB));
10198         // Insert the false branch.
10199         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10200                              DAG.getBasicBlock(DefaultMBB));
10201 
10202         DAG.setRoot(BrCond);
10203         return;
10204       }
10205     }
10206   }
10207 
10208   if (TM.getOptLevel() != CodeGenOpt::None) {
10209     // Here, we order cases by probability so the most likely case will be
10210     // checked first. However, two clusters can have the same probability in
10211     // which case their relative ordering is non-deterministic. So we use Low
10212     // as a tie-breaker as clusters are guaranteed to never overlap.
10213     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10214                [](const CaseCluster &a, const CaseCluster &b) {
10215       return a.Prob != b.Prob ?
10216              a.Prob > b.Prob :
10217              a.Low->getValue().slt(b.Low->getValue());
10218     });
10219 
10220     // Rearrange the case blocks so that the last one falls through if possible
10221     // without changing the order of probabilities.
10222     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10223       --I;
10224       if (I->Prob > W.LastCluster->Prob)
10225         break;
10226       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10227         std::swap(*I, *W.LastCluster);
10228         break;
10229       }
10230     }
10231   }
10232 
10233   // Compute total probability.
10234   BranchProbability DefaultProb = W.DefaultProb;
10235   BranchProbability UnhandledProbs = DefaultProb;
10236   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10237     UnhandledProbs += I->Prob;
10238 
10239   MachineBasicBlock *CurMBB = W.MBB;
10240   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10241     bool FallthroughUnreachable = false;
10242     MachineBasicBlock *Fallthrough;
10243     if (I == W.LastCluster) {
10244       // For the last cluster, fall through to the default destination.
10245       Fallthrough = DefaultMBB;
10246       FallthroughUnreachable = isa<UnreachableInst>(
10247           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10248     } else {
10249       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10250       CurMF->insert(BBI, Fallthrough);
10251       // Put Cond in a virtual register to make it available from the new blocks.
10252       ExportFromCurrentBlock(Cond);
10253     }
10254     UnhandledProbs -= I->Prob;
10255 
10256     switch (I->Kind) {
10257       case CC_JumpTable: {
10258         // FIXME: Optimize away range check based on pivot comparisons.
10259         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10260         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10261 
10262         // The jump block hasn't been inserted yet; insert it here.
10263         MachineBasicBlock *JumpMBB = JT->MBB;
10264         CurMF->insert(BBI, JumpMBB);
10265 
10266         auto JumpProb = I->Prob;
10267         auto FallthroughProb = UnhandledProbs;
10268 
10269         // If the default statement is a target of the jump table, we evenly
10270         // distribute the default probability to successors of CurMBB. Also
10271         // update the probability on the edge from JumpMBB to Fallthrough.
10272         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10273                                               SE = JumpMBB->succ_end();
10274              SI != SE; ++SI) {
10275           if (*SI == DefaultMBB) {
10276             JumpProb += DefaultProb / 2;
10277             FallthroughProb -= DefaultProb / 2;
10278             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10279             JumpMBB->normalizeSuccProbs();
10280             break;
10281           }
10282         }
10283 
10284         if (FallthroughUnreachable) {
10285           // Skip the range check if the fallthrough block is unreachable.
10286           JTH->OmitRangeCheck = true;
10287         }
10288 
10289         if (!JTH->OmitRangeCheck)
10290           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10291         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10292         CurMBB->normalizeSuccProbs();
10293 
10294         // The jump table header will be inserted in our current block, do the
10295         // range check, and fall through to our fallthrough block.
10296         JTH->HeaderBB = CurMBB;
10297         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10298 
10299         // If we're in the right place, emit the jump table header right now.
10300         if (CurMBB == SwitchMBB) {
10301           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10302           JTH->Emitted = true;
10303         }
10304         break;
10305       }
10306       case CC_BitTests: {
10307         // FIXME: Optimize away range check based on pivot comparisons.
10308         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10309 
10310         // The bit test blocks haven't been inserted yet; insert them here.
10311         for (BitTestCase &BTC : BTB->Cases)
10312           CurMF->insert(BBI, BTC.ThisBB);
10313 
10314         // Fill in fields of the BitTestBlock.
10315         BTB->Parent = CurMBB;
10316         BTB->Default = Fallthrough;
10317 
10318         BTB->DefaultProb = UnhandledProbs;
10319         // If the cases in bit test don't form a contiguous range, we evenly
10320         // distribute the probability on the edge to Fallthrough to two
10321         // successors of CurMBB.
10322         if (!BTB->ContiguousRange) {
10323           BTB->Prob += DefaultProb / 2;
10324           BTB->DefaultProb -= DefaultProb / 2;
10325         }
10326 
10327         if (FallthroughUnreachable) {
10328           // Skip the range check if the fallthrough block is unreachable.
10329           BTB->OmitRangeCheck = true;
10330         }
10331 
10332         // If we're in the right place, emit the bit test header right now.
10333         if (CurMBB == SwitchMBB) {
10334           visitBitTestHeader(*BTB, SwitchMBB);
10335           BTB->Emitted = true;
10336         }
10337         break;
10338       }
10339       case CC_Range: {
10340         const Value *RHS, *LHS, *MHS;
10341         ISD::CondCode CC;
10342         if (I->Low == I->High) {
10343           // Check Cond == I->Low.
10344           CC = ISD::SETEQ;
10345           LHS = Cond;
10346           RHS=I->Low;
10347           MHS = nullptr;
10348         } else {
10349           // Check I->Low <= Cond <= I->High.
10350           CC = ISD::SETLE;
10351           LHS = I->Low;
10352           MHS = Cond;
10353           RHS = I->High;
10354         }
10355 
10356         // If Fallthrough is unreachable, fold away the comparison.
10357         if (FallthroughUnreachable)
10358           CC = ISD::SETTRUE;
10359 
10360         // The false probability is the sum of all unhandled cases.
10361         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10362                      getCurSDLoc(), I->Prob, UnhandledProbs);
10363 
10364         if (CurMBB == SwitchMBB)
10365           visitSwitchCase(CB, SwitchMBB);
10366         else
10367           SL->SwitchCases.push_back(CB);
10368 
10369         break;
10370       }
10371     }
10372     CurMBB = Fallthrough;
10373   }
10374 }
10375 
10376 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10377                                               CaseClusterIt First,
10378                                               CaseClusterIt Last) {
10379   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10380     if (X.Prob != CC.Prob)
10381       return X.Prob > CC.Prob;
10382 
10383     // Ties are broken by comparing the case value.
10384     return X.Low->getValue().slt(CC.Low->getValue());
10385   });
10386 }
10387 
10388 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10389                                         const SwitchWorkListItem &W,
10390                                         Value *Cond,
10391                                         MachineBasicBlock *SwitchMBB) {
10392   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10393          "Clusters not sorted?");
10394 
10395   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10396 
10397   // Balance the tree based on branch probabilities to create a near-optimal (in
10398   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10399   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10400   CaseClusterIt LastLeft = W.FirstCluster;
10401   CaseClusterIt FirstRight = W.LastCluster;
10402   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10403   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10404 
10405   // Move LastLeft and FirstRight towards each other from opposite directions to
10406   // find a partitioning of the clusters which balances the probability on both
10407   // sides. If LeftProb and RightProb are equal, alternate which side is
10408   // taken to ensure 0-probability nodes are distributed evenly.
10409   unsigned I = 0;
10410   while (LastLeft + 1 < FirstRight) {
10411     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10412       LeftProb += (++LastLeft)->Prob;
10413     else
10414       RightProb += (--FirstRight)->Prob;
10415     I++;
10416   }
10417 
10418   while (true) {
10419     // Our binary search tree differs from a typical BST in that ours can have up
10420     // to three values in each leaf. The pivot selection above doesn't take that
10421     // into account, which means the tree might require more nodes and be less
10422     // efficient. We compensate for this here.
10423 
10424     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10425     unsigned NumRight = W.LastCluster - FirstRight + 1;
10426 
10427     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10428       // If one side has less than 3 clusters, and the other has more than 3,
10429       // consider taking a cluster from the other side.
10430 
10431       if (NumLeft < NumRight) {
10432         // Consider moving the first cluster on the right to the left side.
10433         CaseCluster &CC = *FirstRight;
10434         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10435         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10436         if (LeftSideRank <= RightSideRank) {
10437           // Moving the cluster to the left does not demote it.
10438           ++LastLeft;
10439           ++FirstRight;
10440           continue;
10441         }
10442       } else {
10443         assert(NumRight < NumLeft);
10444         // Consider moving the last element on the left to the right side.
10445         CaseCluster &CC = *LastLeft;
10446         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10447         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10448         if (RightSideRank <= LeftSideRank) {
10449           // Moving the cluster to the right does not demot it.
10450           --LastLeft;
10451           --FirstRight;
10452           continue;
10453         }
10454       }
10455     }
10456     break;
10457   }
10458 
10459   assert(LastLeft + 1 == FirstRight);
10460   assert(LastLeft >= W.FirstCluster);
10461   assert(FirstRight <= W.LastCluster);
10462 
10463   // Use the first element on the right as pivot since we will make less-than
10464   // comparisons against it.
10465   CaseClusterIt PivotCluster = FirstRight;
10466   assert(PivotCluster > W.FirstCluster);
10467   assert(PivotCluster <= W.LastCluster);
10468 
10469   CaseClusterIt FirstLeft = W.FirstCluster;
10470   CaseClusterIt LastRight = W.LastCluster;
10471 
10472   const ConstantInt *Pivot = PivotCluster->Low;
10473 
10474   // New blocks will be inserted immediately after the current one.
10475   MachineFunction::iterator BBI(W.MBB);
10476   ++BBI;
10477 
10478   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10479   // we can branch to its destination directly if it's squeezed exactly in
10480   // between the known lower bound and Pivot - 1.
10481   MachineBasicBlock *LeftMBB;
10482   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10483       FirstLeft->Low == W.GE &&
10484       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10485     LeftMBB = FirstLeft->MBB;
10486   } else {
10487     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10488     FuncInfo.MF->insert(BBI, LeftMBB);
10489     WorkList.push_back(
10490         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10491     // Put Cond in a virtual register to make it available from the new blocks.
10492     ExportFromCurrentBlock(Cond);
10493   }
10494 
10495   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10496   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10497   // directly if RHS.High equals the current upper bound.
10498   MachineBasicBlock *RightMBB;
10499   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10500       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10501     RightMBB = FirstRight->MBB;
10502   } else {
10503     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10504     FuncInfo.MF->insert(BBI, RightMBB);
10505     WorkList.push_back(
10506         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10507     // Put Cond in a virtual register to make it available from the new blocks.
10508     ExportFromCurrentBlock(Cond);
10509   }
10510 
10511   // Create the CaseBlock record that will be used to lower the branch.
10512   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10513                getCurSDLoc(), LeftProb, RightProb);
10514 
10515   if (W.MBB == SwitchMBB)
10516     visitSwitchCase(CB, SwitchMBB);
10517   else
10518     SL->SwitchCases.push_back(CB);
10519 }
10520 
10521 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10522 // from the swith statement.
10523 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10524                                             BranchProbability PeeledCaseProb) {
10525   if (PeeledCaseProb == BranchProbability::getOne())
10526     return BranchProbability::getZero();
10527   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10528 
10529   uint32_t Numerator = CaseProb.getNumerator();
10530   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10531   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10532 }
10533 
10534 // Try to peel the top probability case if it exceeds the threshold.
10535 // Return current MachineBasicBlock for the switch statement if the peeling
10536 // does not occur.
10537 // If the peeling is performed, return the newly created MachineBasicBlock
10538 // for the peeled switch statement. Also update Clusters to remove the peeled
10539 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10540 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10541     const SwitchInst &SI, CaseClusterVector &Clusters,
10542     BranchProbability &PeeledCaseProb) {
10543   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10544   // Don't perform if there is only one cluster or optimizing for size.
10545   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10546       TM.getOptLevel() == CodeGenOpt::None ||
10547       SwitchMBB->getParent()->getFunction().hasMinSize())
10548     return SwitchMBB;
10549 
10550   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10551   unsigned PeeledCaseIndex = 0;
10552   bool SwitchPeeled = false;
10553   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10554     CaseCluster &CC = Clusters[Index];
10555     if (CC.Prob < TopCaseProb)
10556       continue;
10557     TopCaseProb = CC.Prob;
10558     PeeledCaseIndex = Index;
10559     SwitchPeeled = true;
10560   }
10561   if (!SwitchPeeled)
10562     return SwitchMBB;
10563 
10564   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10565                     << TopCaseProb << "\n");
10566 
10567   // Record the MBB for the peeled switch statement.
10568   MachineFunction::iterator BBI(SwitchMBB);
10569   ++BBI;
10570   MachineBasicBlock *PeeledSwitchMBB =
10571       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10572   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10573 
10574   ExportFromCurrentBlock(SI.getCondition());
10575   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10576   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10577                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10578   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10579 
10580   Clusters.erase(PeeledCaseIt);
10581   for (CaseCluster &CC : Clusters) {
10582     LLVM_DEBUG(
10583         dbgs() << "Scale the probablity for one cluster, before scaling: "
10584                << CC.Prob << "\n");
10585     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10586     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10587   }
10588   PeeledCaseProb = TopCaseProb;
10589   return PeeledSwitchMBB;
10590 }
10591 
10592 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10593   // Extract cases from the switch.
10594   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10595   CaseClusterVector Clusters;
10596   Clusters.reserve(SI.getNumCases());
10597   for (auto I : SI.cases()) {
10598     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10599     const ConstantInt *CaseVal = I.getCaseValue();
10600     BranchProbability Prob =
10601         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10602             : BranchProbability(1, SI.getNumCases() + 1);
10603     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10604   }
10605 
10606   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10607 
10608   // Cluster adjacent cases with the same destination. We do this at all
10609   // optimization levels because it's cheap to do and will make codegen faster
10610   // if there are many clusters.
10611   sortAndRangeify(Clusters);
10612 
10613   // The branch probablity of the peeled case.
10614   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10615   MachineBasicBlock *PeeledSwitchMBB =
10616       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10617 
10618   // If there is only the default destination, jump there directly.
10619   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10620   if (Clusters.empty()) {
10621     assert(PeeledSwitchMBB == SwitchMBB);
10622     SwitchMBB->addSuccessor(DefaultMBB);
10623     if (DefaultMBB != NextBlock(SwitchMBB)) {
10624       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10625                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10626     }
10627     return;
10628   }
10629 
10630   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10631   SL->findBitTestClusters(Clusters, &SI);
10632 
10633   LLVM_DEBUG({
10634     dbgs() << "Case clusters: ";
10635     for (const CaseCluster &C : Clusters) {
10636       if (C.Kind == CC_JumpTable)
10637         dbgs() << "JT:";
10638       if (C.Kind == CC_BitTests)
10639         dbgs() << "BT:";
10640 
10641       C.Low->getValue().print(dbgs(), true);
10642       if (C.Low != C.High) {
10643         dbgs() << '-';
10644         C.High->getValue().print(dbgs(), true);
10645       }
10646       dbgs() << ' ';
10647     }
10648     dbgs() << '\n';
10649   });
10650 
10651   assert(!Clusters.empty());
10652   SwitchWorkList WorkList;
10653   CaseClusterIt First = Clusters.begin();
10654   CaseClusterIt Last = Clusters.end() - 1;
10655   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10656   // Scale the branchprobability for DefaultMBB if the peel occurs and
10657   // DefaultMBB is not replaced.
10658   if (PeeledCaseProb != BranchProbability::getZero() &&
10659       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10660     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10661   WorkList.push_back(
10662       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10663 
10664   while (!WorkList.empty()) {
10665     SwitchWorkListItem W = WorkList.back();
10666     WorkList.pop_back();
10667     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10668 
10669     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10670         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10671       // For optimized builds, lower large range as a balanced binary tree.
10672       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10673       continue;
10674     }
10675 
10676     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10677   }
10678 }
10679 
10680 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10681   SmallVector<EVT, 4> ValueVTs;
10682   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10683                   ValueVTs);
10684   unsigned NumValues = ValueVTs.size();
10685   if (NumValues == 0) return;
10686 
10687   SmallVector<SDValue, 4> Values(NumValues);
10688   SDValue Op = getValue(I.getOperand(0));
10689 
10690   for (unsigned i = 0; i != NumValues; ++i)
10691     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10692                             SDValue(Op.getNode(), Op.getResNo() + i));
10693 
10694   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10695                            DAG.getVTList(ValueVTs), Values));
10696 }
10697