xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision cfd2c5ce580fce744f6fd6ba34e869cab05e94c3)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/Analysis/MemoryLocation.h"
31 #include "llvm/Analysis/TargetLibraryInfo.h"
32 #include "llvm/Analysis/ValueTracking.h"
33 #include "llvm/CodeGen/Analysis.h"
34 #include "llvm/CodeGen/CodeGenCommonISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCMetadata.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
42 #include "llvm/CodeGen/MachineMemOperand.h"
43 #include "llvm/CodeGen/MachineModuleInfo.h"
44 #include "llvm/CodeGen/MachineOperand.h"
45 #include "llvm/CodeGen/MachineRegisterInfo.h"
46 #include "llvm/CodeGen/RuntimeLibcalls.h"
47 #include "llvm/CodeGen/SelectionDAG.h"
48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
49 #include "llvm/CodeGen/StackMaps.h"
50 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
51 #include "llvm/CodeGen/TargetFrameLowering.h"
52 #include "llvm/CodeGen/TargetInstrInfo.h"
53 #include "llvm/CodeGen/TargetOpcodes.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/TargetSubtargetInfo.h"
56 #include "llvm/CodeGen/WinEHFuncInfo.h"
57 #include "llvm/IR/Argument.h"
58 #include "llvm/IR/Attributes.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/CFG.h"
61 #include "llvm/IR/CallingConv.h"
62 #include "llvm/IR/Constant.h"
63 #include "llvm/IR/ConstantRange.h"
64 #include "llvm/IR/Constants.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugInfoMetadata.h"
67 #include "llvm/IR/DerivedTypes.h"
68 #include "llvm/IR/DiagnosticInfo.h"
69 #include "llvm/IR/Function.h"
70 #include "llvm/IR/GetElementPtrTypeIterator.h"
71 #include "llvm/IR/InlineAsm.h"
72 #include "llvm/IR/InstrTypes.h"
73 #include "llvm/IR/Instructions.h"
74 #include "llvm/IR/IntrinsicInst.h"
75 #include "llvm/IR/Intrinsics.h"
76 #include "llvm/IR/IntrinsicsAArch64.h"
77 #include "llvm/IR/IntrinsicsWebAssembly.h"
78 #include "llvm/IR/LLVMContext.h"
79 #include "llvm/IR/Metadata.h"
80 #include "llvm/IR/Module.h"
81 #include "llvm/IR/Operator.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Statepoint.h"
84 #include "llvm/IR/Type.h"
85 #include "llvm/IR/User.h"
86 #include "llvm/IR/Value.h"
87 #include "llvm/MC/MCContext.h"
88 #include "llvm/Support/AtomicOrdering.h"
89 #include "llvm/Support/Casting.h"
90 #include "llvm/Support/CommandLine.h"
91 #include "llvm/Support/Compiler.h"
92 #include "llvm/Support/Debug.h"
93 #include "llvm/Support/MathExtras.h"
94 #include "llvm/Support/raw_ostream.h"
95 #include "llvm/Target/TargetIntrinsicInfo.h"
96 #include "llvm/Target/TargetMachine.h"
97 #include "llvm/Target/TargetOptions.h"
98 #include "llvm/Transforms/Utils/Local.h"
99 #include <cstddef>
100 #include <iterator>
101 #include <limits>
102 #include <tuple>
103 
104 using namespace llvm;
105 using namespace PatternMatch;
106 using namespace SwitchCG;
107 
108 #define DEBUG_TYPE "isel"
109 
110 /// LimitFloatPrecision - Generate low-precision inline sequences for
111 /// some float libcalls (6, 8 or 12 bits).
112 static unsigned LimitFloatPrecision;
113 
114 static cl::opt<bool>
115     InsertAssertAlign("insert-assert-align", cl::init(true),
116                       cl::desc("Insert the experimental `assertalign` node."),
117                       cl::ReallyHidden);
118 
119 static cl::opt<unsigned, true>
120     LimitFPPrecision("limit-float-precision",
121                      cl::desc("Generate low-precision inline sequences "
122                               "for some float libcalls"),
123                      cl::location(LimitFloatPrecision), cl::Hidden,
124                      cl::init(0));
125 
126 static cl::opt<unsigned> SwitchPeelThreshold(
127     "switch-peel-threshold", cl::Hidden, cl::init(66),
128     cl::desc("Set the case probability threshold for peeling the case from a "
129              "switch statement. A value greater than 100 will void this "
130              "optimization"));
131 
132 // Limit the width of DAG chains. This is important in general to prevent
133 // DAG-based analysis from blowing up. For example, alias analysis and
134 // load clustering may not complete in reasonable time. It is difficult to
135 // recognize and avoid this situation within each individual analysis, and
136 // future analyses are likely to have the same behavior. Limiting DAG width is
137 // the safe approach and will be especially important with global DAGs.
138 //
139 // MaxParallelChains default is arbitrarily high to avoid affecting
140 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
141 // sequence over this should have been converted to llvm.memcpy by the
142 // frontend. It is easy to induce this behavior with .ll code such as:
143 // %buffer = alloca [4096 x i8]
144 // %data = load [4096 x i8]* %argPtr
145 // store [4096 x i8] %data, [4096 x i8]* %buffer
146 static const unsigned MaxParallelChains = 64;
147 
148 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
149                                       const SDValue *Parts, unsigned NumParts,
150                                       MVT PartVT, EVT ValueVT, const Value *V,
151                                       Optional<CallingConv::ID> CC);
152 
153 /// getCopyFromParts - Create a value that contains the specified legal parts
154 /// combined into the value they represent.  If the parts combine to a type
155 /// larger than ValueVT then AssertOp can be used to specify whether the extra
156 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
157 /// (ISD::AssertSext).
158 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
159                                 const SDValue *Parts, unsigned NumParts,
160                                 MVT PartVT, EVT ValueVT, const Value *V,
161                                 Optional<CallingConv::ID> CC = None,
162                                 Optional<ISD::NodeType> AssertOp = None) {
163   // Let the target assemble the parts if it wants to
164   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
165   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
166                                                    PartVT, ValueVT, CC))
167     return Val;
168 
169   if (ValueVT.isVector())
170     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
171                                   CC);
172 
173   assert(NumParts > 0 && "No parts to assemble!");
174   SDValue Val = Parts[0];
175 
176   if (NumParts > 1) {
177     // Assemble the value from multiple parts.
178     if (ValueVT.isInteger()) {
179       unsigned PartBits = PartVT.getSizeInBits();
180       unsigned ValueBits = ValueVT.getSizeInBits();
181 
182       // Assemble the power of 2 part.
183       unsigned RoundParts =
184           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
185       unsigned RoundBits = PartBits * RoundParts;
186       EVT RoundVT = RoundBits == ValueBits ?
187         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
188       SDValue Lo, Hi;
189 
190       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
191 
192       if (RoundParts > 2) {
193         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
194                               PartVT, HalfVT, V);
195         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
196                               RoundParts / 2, PartVT, HalfVT, V);
197       } else {
198         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
199         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
200       }
201 
202       if (DAG.getDataLayout().isBigEndian())
203         std::swap(Lo, Hi);
204 
205       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
206 
207       if (RoundParts < NumParts) {
208         // Assemble the trailing non-power-of-2 part.
209         unsigned OddParts = NumParts - RoundParts;
210         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
211         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
212                               OddVT, V, CC);
213 
214         // Combine the round and odd parts.
215         Lo = Val;
216         if (DAG.getDataLayout().isBigEndian())
217           std::swap(Lo, Hi);
218         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
219         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
220         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
221                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
222                                          TLI.getShiftAmountTy(
223                                              TotalVT, DAG.getDataLayout())));
224         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
225         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
226       }
227     } else if (PartVT.isFloatingPoint()) {
228       // FP split into multiple FP parts (for ppcf128)
229       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
230              "Unexpected split");
231       SDValue Lo, Hi;
232       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
233       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
234       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
235         std::swap(Lo, Hi);
236       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
237     } else {
238       // FP split into integer parts (soft fp)
239       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
240              !PartVT.isVector() && "Unexpected split");
241       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
242       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
243     }
244   }
245 
246   // There is now one part, held in Val.  Correct it to match ValueVT.
247   // PartEVT is the type of the register class that holds the value.
248   // ValueVT is the type of the inline asm operation.
249   EVT PartEVT = Val.getValueType();
250 
251   if (PartEVT == ValueVT)
252     return Val;
253 
254   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
255       ValueVT.bitsLT(PartEVT)) {
256     // For an FP value in an integer part, we need to truncate to the right
257     // width first.
258     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
259     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
260   }
261 
262   // Handle types that have the same size.
263   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
264     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
265 
266   // Handle types with different sizes.
267   if (PartEVT.isInteger() && ValueVT.isInteger()) {
268     if (ValueVT.bitsLT(PartEVT)) {
269       // For a truncate, see if we have any information to
270       // indicate whether the truncated bits will always be
271       // zero or sign-extension.
272       if (AssertOp)
273         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
274                           DAG.getValueType(ValueVT));
275       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
276     }
277     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
278   }
279 
280   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
281     // FP_ROUND's are always exact here.
282     if (ValueVT.bitsLT(Val.getValueType()))
283       return DAG.getNode(
284           ISD::FP_ROUND, DL, ValueVT, Val,
285           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
286 
287     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
288   }
289 
290   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
291   // then truncating.
292   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
293       ValueVT.bitsLT(PartEVT)) {
294     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
295     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
296   }
297 
298   report_fatal_error("Unknown mismatch in getCopyFromParts!");
299 }
300 
301 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
302                                               const Twine &ErrMsg) {
303   const Instruction *I = dyn_cast_or_null<Instruction>(V);
304   if (!V)
305     return Ctx.emitError(ErrMsg);
306 
307   const char *AsmError = ", possible invalid constraint for vector type";
308   if (const CallInst *CI = dyn_cast<CallInst>(I))
309     if (CI->isInlineAsm())
310       return Ctx.emitError(I, ErrMsg + AsmError);
311 
312   return Ctx.emitError(I, ErrMsg);
313 }
314 
315 /// getCopyFromPartsVector - Create a value that contains the specified legal
316 /// parts combined into the value they represent.  If the parts combine to a
317 /// type larger than ValueVT then AssertOp can be used to specify whether the
318 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
319 /// ValueVT (ISD::AssertSext).
320 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
321                                       const SDValue *Parts, unsigned NumParts,
322                                       MVT PartVT, EVT ValueVT, const Value *V,
323                                       Optional<CallingConv::ID> CallConv) {
324   assert(ValueVT.isVector() && "Not a vector value");
325   assert(NumParts > 0 && "No parts to assemble!");
326   const bool IsABIRegCopy = CallConv.has_value();
327 
328   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
329   SDValue Val = Parts[0];
330 
331   // Handle a multi-element vector.
332   if (NumParts > 1) {
333     EVT IntermediateVT;
334     MVT RegisterVT;
335     unsigned NumIntermediates;
336     unsigned NumRegs;
337 
338     if (IsABIRegCopy) {
339       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
340           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
341           NumIntermediates, RegisterVT);
342     } else {
343       NumRegs =
344           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
345                                      NumIntermediates, RegisterVT);
346     }
347 
348     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
349     NumParts = NumRegs; // Silence a compiler warning.
350     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
351     assert(RegisterVT.getSizeInBits() ==
352            Parts[0].getSimpleValueType().getSizeInBits() &&
353            "Part type sizes don't match!");
354 
355     // Assemble the parts into intermediate operands.
356     SmallVector<SDValue, 8> Ops(NumIntermediates);
357     if (NumIntermediates == NumParts) {
358       // If the register was not expanded, truncate or copy the value,
359       // as appropriate.
360       for (unsigned i = 0; i != NumParts; ++i)
361         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
362                                   PartVT, IntermediateVT, V, CallConv);
363     } else if (NumParts > 0) {
364       // If the intermediate type was expanded, build the intermediate
365       // operands from the parts.
366       assert(NumParts % NumIntermediates == 0 &&
367              "Must expand into a divisible number of parts!");
368       unsigned Factor = NumParts / NumIntermediates;
369       for (unsigned i = 0; i != NumIntermediates; ++i)
370         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
371                                   PartVT, IntermediateVT, V, CallConv);
372     }
373 
374     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
375     // intermediate operands.
376     EVT BuiltVectorTy =
377         IntermediateVT.isVector()
378             ? EVT::getVectorVT(
379                   *DAG.getContext(), IntermediateVT.getScalarType(),
380                   IntermediateVT.getVectorElementCount() * NumParts)
381             : EVT::getVectorVT(*DAG.getContext(),
382                                IntermediateVT.getScalarType(),
383                                NumIntermediates);
384     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
385                                                 : ISD::BUILD_VECTOR,
386                       DL, BuiltVectorTy, Ops);
387   }
388 
389   // There is now one part, held in Val.  Correct it to match ValueVT.
390   EVT PartEVT = Val.getValueType();
391 
392   if (PartEVT == ValueVT)
393     return Val;
394 
395   if (PartEVT.isVector()) {
396     // Vector/Vector bitcast.
397     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
398       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
399 
400     // If the element type of the source/dest vectors are the same, but the
401     // parts vector has more elements than the value vector, then we have a
402     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
403     // elements we want.
404     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
405       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
406               ValueVT.getVectorElementCount().getKnownMinValue()) &&
407              (PartEVT.getVectorElementCount().isScalable() ==
408               ValueVT.getVectorElementCount().isScalable()) &&
409              "Cannot narrow, it would be a lossy transformation");
410       PartEVT =
411           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
412                            ValueVT.getVectorElementCount());
413       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
414                         DAG.getVectorIdxConstant(0, DL));
415       if (PartEVT == ValueVT)
416         return Val;
417     }
418 
419     // Promoted vector extract
420     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
421   }
422 
423   // Trivial bitcast if the types are the same size and the destination
424   // vector type is legal.
425   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
426       TLI.isTypeLegal(ValueVT))
427     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
428 
429   if (ValueVT.getVectorNumElements() != 1) {
430      // Certain ABIs require that vectors are passed as integers. For vectors
431      // are the same size, this is an obvious bitcast.
432      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
433        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
434      } else if (ValueVT.bitsLT(PartEVT)) {
435        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
436        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
437        // Drop the extra bits.
438        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
439        return DAG.getBitcast(ValueVT, Val);
440      }
441 
442      diagnosePossiblyInvalidConstraint(
443          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
444      return DAG.getUNDEF(ValueVT);
445   }
446 
447   // Handle cases such as i8 -> <1 x i1>
448   EVT ValueSVT = ValueVT.getVectorElementType();
449   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
450     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
451       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
452     else
453       Val = ValueVT.isFloatingPoint()
454                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
455                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
456   }
457 
458   return DAG.getBuildVector(ValueVT, DL, Val);
459 }
460 
461 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
462                                  SDValue Val, SDValue *Parts, unsigned NumParts,
463                                  MVT PartVT, const Value *V,
464                                  Optional<CallingConv::ID> CallConv);
465 
466 /// getCopyToParts - Create a series of nodes that contain the specified value
467 /// split into legal parts.  If the parts contain more bits than Val, then, for
468 /// integers, ExtendKind can be used to specify how to generate the extra bits.
469 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
470                            SDValue *Parts, unsigned NumParts, MVT PartVT,
471                            const Value *V,
472                            Optional<CallingConv::ID> CallConv = None,
473                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
474   // Let the target split the parts if it wants to
475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
476   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
477                                       CallConv))
478     return;
479   EVT ValueVT = Val.getValueType();
480 
481   // Handle the vector case separately.
482   if (ValueVT.isVector())
483     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
484                                 CallConv);
485 
486   unsigned PartBits = PartVT.getSizeInBits();
487   unsigned OrigNumParts = NumParts;
488   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
489          "Copying to an illegal type!");
490 
491   if (NumParts == 0)
492     return;
493 
494   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
495   EVT PartEVT = PartVT;
496   if (PartEVT == ValueVT) {
497     assert(NumParts == 1 && "No-op copy with multiple parts!");
498     Parts[0] = Val;
499     return;
500   }
501 
502   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
503     // If the parts cover more bits than the value has, promote the value.
504     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
505       assert(NumParts == 1 && "Do not know what to promote to!");
506       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
507     } else {
508       if (ValueVT.isFloatingPoint()) {
509         // FP values need to be bitcast, then extended if they are being put
510         // into a larger container.
511         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
512         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
513       }
514       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
515              ValueVT.isInteger() &&
516              "Unknown mismatch!");
517       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
518       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
519       if (PartVT == MVT::x86mmx)
520         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
521     }
522   } else if (PartBits == ValueVT.getSizeInBits()) {
523     // Different types of the same size.
524     assert(NumParts == 1 && PartEVT != ValueVT);
525     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
526   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
527     // If the parts cover less bits than value has, truncate the value.
528     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
529            ValueVT.isInteger() &&
530            "Unknown mismatch!");
531     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
532     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
533     if (PartVT == MVT::x86mmx)
534       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
535   }
536 
537   // The value may have changed - recompute ValueVT.
538   ValueVT = Val.getValueType();
539   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
540          "Failed to tile the value with PartVT!");
541 
542   if (NumParts == 1) {
543     if (PartEVT != ValueVT) {
544       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
545                                         "scalar-to-vector conversion failed");
546       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
547     }
548 
549     Parts[0] = Val;
550     return;
551   }
552 
553   // Expand the value into multiple parts.
554   if (NumParts & (NumParts - 1)) {
555     // The number of parts is not a power of 2.  Split off and copy the tail.
556     assert(PartVT.isInteger() && ValueVT.isInteger() &&
557            "Do not know what to expand to!");
558     unsigned RoundParts = 1 << Log2_32(NumParts);
559     unsigned RoundBits = RoundParts * PartBits;
560     unsigned OddParts = NumParts - RoundParts;
561     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
562       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
563 
564     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
565                    CallConv);
566 
567     if (DAG.getDataLayout().isBigEndian())
568       // The odd parts were reversed by getCopyToParts - unreverse them.
569       std::reverse(Parts + RoundParts, Parts + NumParts);
570 
571     NumParts = RoundParts;
572     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
573     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
574   }
575 
576   // The number of parts is a power of 2.  Repeatedly bisect the value using
577   // EXTRACT_ELEMENT.
578   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
579                          EVT::getIntegerVT(*DAG.getContext(),
580                                            ValueVT.getSizeInBits()),
581                          Val);
582 
583   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
584     for (unsigned i = 0; i < NumParts; i += StepSize) {
585       unsigned ThisBits = StepSize * PartBits / 2;
586       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
587       SDValue &Part0 = Parts[i];
588       SDValue &Part1 = Parts[i+StepSize/2];
589 
590       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
591                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
592       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
593                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
594 
595       if (ThisBits == PartBits && ThisVT != PartVT) {
596         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
597         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
598       }
599     }
600   }
601 
602   if (DAG.getDataLayout().isBigEndian())
603     std::reverse(Parts, Parts + OrigNumParts);
604 }
605 
606 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
607                                      const SDLoc &DL, EVT PartVT) {
608   if (!PartVT.isVector())
609     return SDValue();
610 
611   EVT ValueVT = Val.getValueType();
612   ElementCount PartNumElts = PartVT.getVectorElementCount();
613   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
614 
615   // We only support widening vectors with equivalent element types and
616   // fixed/scalable properties. If a target needs to widen a fixed-length type
617   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
618   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
619       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
620       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
621     return SDValue();
622 
623   // Widening a scalable vector to another scalable vector is done by inserting
624   // the vector into a larger undef one.
625   if (PartNumElts.isScalable())
626     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
627                        Val, DAG.getVectorIdxConstant(0, DL));
628 
629   EVT ElementVT = PartVT.getVectorElementType();
630   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
631   // undef elements.
632   SmallVector<SDValue, 16> Ops;
633   DAG.ExtractVectorElements(Val, Ops);
634   SDValue EltUndef = DAG.getUNDEF(ElementVT);
635   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
636 
637   // FIXME: Use CONCAT for 2x -> 4x.
638   return DAG.getBuildVector(PartVT, DL, Ops);
639 }
640 
641 /// getCopyToPartsVector - Create a series of nodes that contain the specified
642 /// value split into legal parts.
643 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
644                                  SDValue Val, SDValue *Parts, unsigned NumParts,
645                                  MVT PartVT, const Value *V,
646                                  Optional<CallingConv::ID> CallConv) {
647   EVT ValueVT = Val.getValueType();
648   assert(ValueVT.isVector() && "Not a vector");
649   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
650   const bool IsABIRegCopy = CallConv.has_value();
651 
652   if (NumParts == 1) {
653     EVT PartEVT = PartVT;
654     if (PartEVT == ValueVT) {
655       // Nothing to do.
656     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
657       // Bitconvert vector->vector case.
658       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
659     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
660       Val = Widened;
661     } else if (PartVT.isVector() &&
662                PartEVT.getVectorElementType().bitsGE(
663                    ValueVT.getVectorElementType()) &&
664                PartEVT.getVectorElementCount() ==
665                    ValueVT.getVectorElementCount()) {
666 
667       // Promoted vector extract
668       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
669     } else if (PartEVT.isVector() &&
670                PartEVT.getVectorElementType() !=
671                    ValueVT.getVectorElementType() &&
672                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
673                    TargetLowering::TypeWidenVector) {
674       // Combination of widening and promotion.
675       EVT WidenVT =
676           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
677                            PartVT.getVectorElementCount());
678       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
679       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
680     } else {
681       if (ValueVT.getVectorElementCount().isScalar()) {
682         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
683                           DAG.getVectorIdxConstant(0, DL));
684       } else {
685         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
686         assert(PartVT.getFixedSizeInBits() > ValueSize &&
687                "lossy conversion of vector to scalar type");
688         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
689         Val = DAG.getBitcast(IntermediateType, Val);
690         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
691       }
692     }
693 
694     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
695     Parts[0] = Val;
696     return;
697   }
698 
699   // Handle a multi-element vector.
700   EVT IntermediateVT;
701   MVT RegisterVT;
702   unsigned NumIntermediates;
703   unsigned NumRegs;
704   if (IsABIRegCopy) {
705     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
706         *DAG.getContext(), CallConv.value(), ValueVT, IntermediateVT,
707         NumIntermediates, RegisterVT);
708   } else {
709     NumRegs =
710         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
711                                    NumIntermediates, RegisterVT);
712   }
713 
714   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
715   NumParts = NumRegs; // Silence a compiler warning.
716   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
717 
718   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
719          "Mixing scalable and fixed vectors when copying in parts");
720 
721   Optional<ElementCount> DestEltCnt;
722 
723   if (IntermediateVT.isVector())
724     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
725   else
726     DestEltCnt = ElementCount::getFixed(NumIntermediates);
727 
728   EVT BuiltVectorTy = EVT::getVectorVT(
729       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
730 
731   if (ValueVT == BuiltVectorTy) {
732     // Nothing to do.
733   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
734     // Bitconvert vector->vector case.
735     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
736   } else {
737     if (BuiltVectorTy.getVectorElementType().bitsGT(
738             ValueVT.getVectorElementType())) {
739       // Integer promotion.
740       ValueVT = EVT::getVectorVT(*DAG.getContext(),
741                                  BuiltVectorTy.getVectorElementType(),
742                                  ValueVT.getVectorElementCount());
743       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
744     }
745 
746     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
747       Val = Widened;
748     }
749   }
750 
751   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
752 
753   // Split the vector into intermediate operands.
754   SmallVector<SDValue, 8> Ops(NumIntermediates);
755   for (unsigned i = 0; i != NumIntermediates; ++i) {
756     if (IntermediateVT.isVector()) {
757       // This does something sensible for scalable vectors - see the
758       // definition of EXTRACT_SUBVECTOR for further details.
759       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
760       Ops[i] =
761           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
762                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
763     } else {
764       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
765                            DAG.getVectorIdxConstant(i, DL));
766     }
767   }
768 
769   // Split the intermediate operands into legal parts.
770   if (NumParts == NumIntermediates) {
771     // If the register was not expanded, promote or copy the value,
772     // as appropriate.
773     for (unsigned i = 0; i != NumParts; ++i)
774       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
775   } else if (NumParts > 0) {
776     // If the intermediate type was expanded, split each the value into
777     // legal parts.
778     assert(NumIntermediates != 0 && "division by zero");
779     assert(NumParts % NumIntermediates == 0 &&
780            "Must expand into a divisible number of parts!");
781     unsigned Factor = NumParts / NumIntermediates;
782     for (unsigned i = 0; i != NumIntermediates; ++i)
783       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
784                      CallConv);
785   }
786 }
787 
788 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
789                            EVT valuevt, Optional<CallingConv::ID> CC)
790     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
791       RegCount(1, regs.size()), CallConv(CC) {}
792 
793 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
794                            const DataLayout &DL, unsigned Reg, Type *Ty,
795                            Optional<CallingConv::ID> CC) {
796   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
797 
798   CallConv = CC;
799 
800   for (EVT ValueVT : ValueVTs) {
801     unsigned NumRegs =
802         isABIMangled()
803             ? TLI.getNumRegistersForCallingConv(Context, CC.value(), ValueVT)
804             : TLI.getNumRegisters(Context, ValueVT);
805     MVT RegisterVT =
806         isABIMangled()
807             ? TLI.getRegisterTypeForCallingConv(Context, CC.value(), ValueVT)
808             : TLI.getRegisterType(Context, ValueVT);
809     for (unsigned i = 0; i != NumRegs; ++i)
810       Regs.push_back(Reg + i);
811     RegVTs.push_back(RegisterVT);
812     RegCount.push_back(NumRegs);
813     Reg += NumRegs;
814   }
815 }
816 
817 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
818                                       FunctionLoweringInfo &FuncInfo,
819                                       const SDLoc &dl, SDValue &Chain,
820                                       SDValue *Flag, const Value *V) const {
821   // A Value with type {} or [0 x %t] needs no registers.
822   if (ValueVTs.empty())
823     return SDValue();
824 
825   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
826 
827   // Assemble the legal parts into the final values.
828   SmallVector<SDValue, 4> Values(ValueVTs.size());
829   SmallVector<SDValue, 8> Parts;
830   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
831     // Copy the legal parts from the registers.
832     EVT ValueVT = ValueVTs[Value];
833     unsigned NumRegs = RegCount[Value];
834     MVT RegisterVT =
835         isABIMangled() ? TLI.getRegisterTypeForCallingConv(
836                              *DAG.getContext(), CallConv.value(), RegVTs[Value])
837                        : RegVTs[Value];
838 
839     Parts.resize(NumRegs);
840     for (unsigned i = 0; i != NumRegs; ++i) {
841       SDValue P;
842       if (!Flag) {
843         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
844       } else {
845         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
846         *Flag = P.getValue(2);
847       }
848 
849       Chain = P.getValue(1);
850       Parts[i] = P;
851 
852       // If the source register was virtual and if we know something about it,
853       // add an assert node.
854       if (!Register::isVirtualRegister(Regs[Part + i]) ||
855           !RegisterVT.isInteger())
856         continue;
857 
858       const FunctionLoweringInfo::LiveOutInfo *LOI =
859         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
860       if (!LOI)
861         continue;
862 
863       unsigned RegSize = RegisterVT.getScalarSizeInBits();
864       unsigned NumSignBits = LOI->NumSignBits;
865       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
866 
867       if (NumZeroBits == RegSize) {
868         // The current value is a zero.
869         // Explicitly express that as it would be easier for
870         // optimizations to kick in.
871         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
872         continue;
873       }
874 
875       // FIXME: We capture more information than the dag can represent.  For
876       // now, just use the tightest assertzext/assertsext possible.
877       bool isSExt;
878       EVT FromVT(MVT::Other);
879       if (NumZeroBits) {
880         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
881         isSExt = false;
882       } else if (NumSignBits > 1) {
883         FromVT =
884             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
885         isSExt = true;
886       } else {
887         continue;
888       }
889       // Add an assertion node.
890       assert(FromVT != MVT::Other);
891       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
892                              RegisterVT, P, DAG.getValueType(FromVT));
893     }
894 
895     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
896                                      RegisterVT, ValueVT, V, CallConv);
897     Part += NumRegs;
898     Parts.clear();
899   }
900 
901   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
902 }
903 
904 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
905                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
906                                  const Value *V,
907                                  ISD::NodeType PreferredExtendType) const {
908   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
909   ISD::NodeType ExtendKind = PreferredExtendType;
910 
911   // Get the list of the values's legal parts.
912   unsigned NumRegs = Regs.size();
913   SmallVector<SDValue, 8> Parts(NumRegs);
914   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
915     unsigned NumParts = RegCount[Value];
916 
917     MVT RegisterVT =
918         isABIMangled() ? TLI.getRegisterTypeForCallingConv(
919                              *DAG.getContext(), CallConv.value(), RegVTs[Value])
920                        : RegVTs[Value];
921 
922     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
923       ExtendKind = ISD::ZERO_EXTEND;
924 
925     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
926                    NumParts, RegisterVT, V, CallConv, ExtendKind);
927     Part += NumParts;
928   }
929 
930   // Copy the parts into the registers.
931   SmallVector<SDValue, 8> Chains(NumRegs);
932   for (unsigned i = 0; i != NumRegs; ++i) {
933     SDValue Part;
934     if (!Flag) {
935       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
936     } else {
937       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
938       *Flag = Part.getValue(1);
939     }
940 
941     Chains[i] = Part.getValue(0);
942   }
943 
944   if (NumRegs == 1 || Flag)
945     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
946     // flagged to it. That is the CopyToReg nodes and the user are considered
947     // a single scheduling unit. If we create a TokenFactor and return it as
948     // chain, then the TokenFactor is both a predecessor (operand) of the
949     // user as well as a successor (the TF operands are flagged to the user).
950     // c1, f1 = CopyToReg
951     // c2, f2 = CopyToReg
952     // c3     = TokenFactor c1, c2
953     // ...
954     //        = op c3, ..., f2
955     Chain = Chains[NumRegs-1];
956   else
957     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
958 }
959 
960 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
961                                         unsigned MatchingIdx, const SDLoc &dl,
962                                         SelectionDAG &DAG,
963                                         std::vector<SDValue> &Ops) const {
964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
965 
966   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
967   if (HasMatching)
968     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
969   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
970     // Put the register class of the virtual registers in the flag word.  That
971     // way, later passes can recompute register class constraints for inline
972     // assembly as well as normal instructions.
973     // Don't do this for tied operands that can use the regclass information
974     // from the def.
975     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
976     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
977     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
978   }
979 
980   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
981   Ops.push_back(Res);
982 
983   if (Code == InlineAsm::Kind_Clobber) {
984     // Clobbers should always have a 1:1 mapping with registers, and may
985     // reference registers that have illegal (e.g. vector) types. Hence, we
986     // shouldn't try to apply any sort of splitting logic to them.
987     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
988            "No 1:1 mapping from clobbers to regs?");
989     Register SP = TLI.getStackPointerRegisterToSaveRestore();
990     (void)SP;
991     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
992       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
993       assert(
994           (Regs[I] != SP ||
995            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
996           "If we clobbered the stack pointer, MFI should know about it.");
997     }
998     return;
999   }
1000 
1001   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1002     MVT RegisterVT = RegVTs[Value];
1003     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1004                                            RegisterVT);
1005     for (unsigned i = 0; i != NumRegs; ++i) {
1006       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1007       unsigned TheReg = Regs[Reg++];
1008       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1009     }
1010   }
1011 }
1012 
1013 SmallVector<std::pair<unsigned, TypeSize>, 4>
1014 RegsForValue::getRegsAndSizes() const {
1015   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1016   unsigned I = 0;
1017   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1018     unsigned RegCount = std::get<0>(CountAndVT);
1019     MVT RegisterVT = std::get<1>(CountAndVT);
1020     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1021     for (unsigned E = I + RegCount; I != E; ++I)
1022       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1023   }
1024   return OutVec;
1025 }
1026 
1027 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1028                                const TargetLibraryInfo *li) {
1029   AA = aa;
1030   GFI = gfi;
1031   LibInfo = li;
1032   Context = DAG.getContext();
1033   LPadToCallSiteMap.clear();
1034   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1035 }
1036 
1037 void SelectionDAGBuilder::clear() {
1038   NodeMap.clear();
1039   UnusedArgNodeMap.clear();
1040   PendingLoads.clear();
1041   PendingExports.clear();
1042   PendingConstrainedFP.clear();
1043   PendingConstrainedFPStrict.clear();
1044   CurInst = nullptr;
1045   HasTailCall = false;
1046   SDNodeOrder = LowestSDNodeOrder;
1047   StatepointLowering.clear();
1048 }
1049 
1050 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1051   DanglingDebugInfoMap.clear();
1052 }
1053 
1054 // Update DAG root to include dependencies on Pending chains.
1055 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1056   SDValue Root = DAG.getRoot();
1057 
1058   if (Pending.empty())
1059     return Root;
1060 
1061   // Add current root to PendingChains, unless we already indirectly
1062   // depend on it.
1063   if (Root.getOpcode() != ISD::EntryToken) {
1064     unsigned i = 0, e = Pending.size();
1065     for (; i != e; ++i) {
1066       assert(Pending[i].getNode()->getNumOperands() > 1);
1067       if (Pending[i].getNode()->getOperand(0) == Root)
1068         break;  // Don't add the root if we already indirectly depend on it.
1069     }
1070 
1071     if (i == e)
1072       Pending.push_back(Root);
1073   }
1074 
1075   if (Pending.size() == 1)
1076     Root = Pending[0];
1077   else
1078     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1079 
1080   DAG.setRoot(Root);
1081   Pending.clear();
1082   return Root;
1083 }
1084 
1085 SDValue SelectionDAGBuilder::getMemoryRoot() {
1086   return updateRoot(PendingLoads);
1087 }
1088 
1089 SDValue SelectionDAGBuilder::getRoot() {
1090   // Chain up all pending constrained intrinsics together with all
1091   // pending loads, by simply appending them to PendingLoads and
1092   // then calling getMemoryRoot().
1093   PendingLoads.reserve(PendingLoads.size() +
1094                        PendingConstrainedFP.size() +
1095                        PendingConstrainedFPStrict.size());
1096   PendingLoads.append(PendingConstrainedFP.begin(),
1097                       PendingConstrainedFP.end());
1098   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1099                       PendingConstrainedFPStrict.end());
1100   PendingConstrainedFP.clear();
1101   PendingConstrainedFPStrict.clear();
1102   return getMemoryRoot();
1103 }
1104 
1105 SDValue SelectionDAGBuilder::getControlRoot() {
1106   // We need to emit pending fpexcept.strict constrained intrinsics,
1107   // so append them to the PendingExports list.
1108   PendingExports.append(PendingConstrainedFPStrict.begin(),
1109                         PendingConstrainedFPStrict.end());
1110   PendingConstrainedFPStrict.clear();
1111   return updateRoot(PendingExports);
1112 }
1113 
1114 void SelectionDAGBuilder::visit(const Instruction &I) {
1115   // Set up outgoing PHI node register values before emitting the terminator.
1116   if (I.isTerminator()) {
1117     HandlePHINodesInSuccessorBlocks(I.getParent());
1118   }
1119 
1120   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1121   if (!isa<DbgInfoIntrinsic>(I))
1122     ++SDNodeOrder;
1123 
1124   CurInst = &I;
1125 
1126   visit(I.getOpcode(), I);
1127 
1128   if (!I.isTerminator() && !HasTailCall &&
1129       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1130     CopyToExportRegsIfNeeded(&I);
1131 
1132   CurInst = nullptr;
1133 }
1134 
1135 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1136   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1137 }
1138 
1139 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1140   // Note: this doesn't use InstVisitor, because it has to work with
1141   // ConstantExpr's in addition to instructions.
1142   switch (Opcode) {
1143   default: llvm_unreachable("Unknown instruction type encountered!");
1144     // Build the switch statement using the Instruction.def file.
1145 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1146     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1147 #include "llvm/IR/Instruction.def"
1148   }
1149 }
1150 
1151 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1152                                                DebugLoc DL, unsigned Order) {
1153   // We treat variadic dbg_values differently at this stage.
1154   if (DI->hasArgList()) {
1155     // For variadic dbg_values we will now insert an undef.
1156     // FIXME: We can potentially recover these!
1157     SmallVector<SDDbgOperand, 2> Locs;
1158     for (const Value *V : DI->getValues()) {
1159       auto Undef = UndefValue::get(V->getType());
1160       Locs.push_back(SDDbgOperand::fromConst(Undef));
1161     }
1162     SDDbgValue *SDV = DAG.getDbgValueList(
1163         DI->getVariable(), DI->getExpression(), Locs, {},
1164         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1165     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1166   } else {
1167     // TODO: Dangling debug info will eventually either be resolved or produce
1168     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1169     // between the original dbg.value location and its resolved DBG_VALUE,
1170     // which we should ideally fill with an extra Undef DBG_VALUE.
1171     assert(DI->getNumVariableLocationOps() == 1 &&
1172            "DbgValueInst without an ArgList should have a single location "
1173            "operand.");
1174     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1175   }
1176 }
1177 
1178 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1179                                                 const DIExpression *Expr) {
1180   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1181     const DbgValueInst *DI = DDI.getDI();
1182     DIVariable *DanglingVariable = DI->getVariable();
1183     DIExpression *DanglingExpr = DI->getExpression();
1184     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1185       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1186       return true;
1187     }
1188     return false;
1189   };
1190 
1191   for (auto &DDIMI : DanglingDebugInfoMap) {
1192     DanglingDebugInfoVector &DDIV = DDIMI.second;
1193 
1194     // If debug info is to be dropped, run it through final checks to see
1195     // whether it can be salvaged.
1196     for (auto &DDI : DDIV)
1197       if (isMatchingDbgValue(DDI))
1198         salvageUnresolvedDbgValue(DDI);
1199 
1200     erase_if(DDIV, isMatchingDbgValue);
1201   }
1202 }
1203 
1204 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1205 // generate the debug data structures now that we've seen its definition.
1206 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1207                                                    SDValue Val) {
1208   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1209   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1210     return;
1211 
1212   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1213   for (auto &DDI : DDIV) {
1214     const DbgValueInst *DI = DDI.getDI();
1215     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1216     assert(DI && "Ill-formed DanglingDebugInfo");
1217     DebugLoc dl = DDI.getdl();
1218     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1219     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1220     DILocalVariable *Variable = DI->getVariable();
1221     DIExpression *Expr = DI->getExpression();
1222     assert(Variable->isValidLocationForIntrinsic(dl) &&
1223            "Expected inlined-at fields to agree");
1224     SDDbgValue *SDV;
1225     if (Val.getNode()) {
1226       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1227       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1228       // we couldn't resolve it directly when examining the DbgValue intrinsic
1229       // in the first place we should not be more successful here). Unless we
1230       // have some test case that prove this to be correct we should avoid
1231       // calling EmitFuncArgumentDbgValue here.
1232       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl,
1233                                     FuncArgumentDbgValueKind::Value, Val)) {
1234         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1235                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1236         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1237         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1238         // inserted after the definition of Val when emitting the instructions
1239         // after ISel. An alternative could be to teach
1240         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1241         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1242                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1243                    << ValSDNodeOrder << "\n");
1244         SDV = getDbgValue(Val, Variable, Expr, dl,
1245                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1246         DAG.AddDbgValue(SDV, false);
1247       } else
1248         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1249                           << "in EmitFuncArgumentDbgValue\n");
1250     } else {
1251       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1252       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1253       auto SDV =
1254           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1255       DAG.AddDbgValue(SDV, false);
1256     }
1257   }
1258   DDIV.clear();
1259 }
1260 
1261 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1262   // TODO: For the variadic implementation, instead of only checking the fail
1263   // state of `handleDebugValue`, we need know specifically which values were
1264   // invalid, so that we attempt to salvage only those values when processing
1265   // a DIArgList.
1266   assert(!DDI.getDI()->hasArgList() &&
1267          "Not implemented for variadic dbg_values");
1268   Value *V = DDI.getDI()->getValue(0);
1269   DILocalVariable *Var = DDI.getDI()->getVariable();
1270   DIExpression *Expr = DDI.getDI()->getExpression();
1271   DebugLoc DL = DDI.getdl();
1272   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1273   unsigned SDOrder = DDI.getSDNodeOrder();
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, /*IsVariadic=*/false))
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     // Temporary "0", awaiting real implementation.
1289     SmallVector<uint64_t, 16> Ops;
1290     SmallVector<Value *, 4> AdditionalValues;
1291     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1292                              AdditionalValues);
1293     // If we cannot salvage any further, and haven't yet found a suitable debug
1294     // expression, bail out.
1295     if (!V)
1296       break;
1297 
1298     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1299     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1300     // here for variadic dbg_values, remove that condition.
1301     if (!AdditionalValues.empty())
1302       break;
1303 
1304     // New value and expr now represent this debuginfo.
1305     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1306 
1307     // Some kind of simplification occurred: check whether the operand of the
1308     // salvaged debug expression can be encoded in this DAG.
1309     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1310                          /*IsVariadic=*/false)) {
1311       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1312                         << *DDI.getDI() << "\nBy stripping back to:\n  " << *V);
1313       return;
1314     }
1315   }
1316 
1317   // This was the final opportunity to salvage this debug information, and it
1318   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1319   // any earlier variable location.
1320   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1321   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1322   DAG.AddDbgValue(SDV, false);
1323 
1324   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << *DDI.getDI()
1325                     << "\n");
1326   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1327                     << "\n");
1328 }
1329 
1330 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1331                                            DILocalVariable *Var,
1332                                            DIExpression *Expr, DebugLoc dl,
1333                                            DebugLoc InstDL, unsigned Order,
1334                                            bool IsVariadic) {
1335   if (Values.empty())
1336     return true;
1337   SmallVector<SDDbgOperand> LocationOps;
1338   SmallVector<SDNode *> Dependencies;
1339   for (const Value *V : Values) {
1340     // Constant value.
1341     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1342         isa<ConstantPointerNull>(V)) {
1343       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1344       continue;
1345     }
1346 
1347     // Look through IntToPtr constants.
1348     if (auto *CE = dyn_cast<ConstantExpr>(V))
1349       if (CE->getOpcode() == Instruction::IntToPtr) {
1350         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1351         continue;
1352       }
1353 
1354     // If the Value is a frame index, we can create a FrameIndex debug value
1355     // without relying on the DAG at all.
1356     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1357       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1358       if (SI != FuncInfo.StaticAllocaMap.end()) {
1359         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1360         continue;
1361       }
1362     }
1363 
1364     // Do not use getValue() in here; we don't want to generate code at
1365     // this point if it hasn't been done yet.
1366     SDValue N = NodeMap[V];
1367     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1368       N = UnusedArgNodeMap[V];
1369     if (N.getNode()) {
1370       // Only emit func arg dbg value for non-variadic dbg.values for now.
1371       if (!IsVariadic &&
1372           EmitFuncArgumentDbgValue(V, Var, Expr, dl,
1373                                    FuncArgumentDbgValueKind::Value, N))
1374         return true;
1375       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1376         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1377         // describe stack slot locations.
1378         //
1379         // Consider "int x = 0; int *px = &x;". There are two kinds of
1380         // interesting debug values here after optimization:
1381         //
1382         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1383         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1384         //
1385         // Both describe the direct values of their associated variables.
1386         Dependencies.push_back(N.getNode());
1387         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1388         continue;
1389       }
1390       LocationOps.emplace_back(
1391           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1392       continue;
1393     }
1394 
1395     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1396     // Special rules apply for the first dbg.values of parameter variables in a
1397     // function. Identify them by the fact they reference Argument Values, that
1398     // they're parameters, and they are parameters of the current function. We
1399     // need to let them dangle until they get an SDNode.
1400     bool IsParamOfFunc =
1401         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1402     if (IsParamOfFunc)
1403       return false;
1404 
1405     // The value is not used in this block yet (or it would have an SDNode).
1406     // We still want the value to appear for the user if possible -- if it has
1407     // an associated VReg, we can refer to that instead.
1408     auto VMI = FuncInfo.ValueMap.find(V);
1409     if (VMI != FuncInfo.ValueMap.end()) {
1410       unsigned Reg = VMI->second;
1411       // If this is a PHI node, it may be split up into several MI PHI nodes
1412       // (in FunctionLoweringInfo::set).
1413       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1414                        V->getType(), None);
1415       if (RFV.occupiesMultipleRegs()) {
1416         // FIXME: We could potentially support variadic dbg_values here.
1417         if (IsVariadic)
1418           return false;
1419         unsigned Offset = 0;
1420         unsigned BitsToDescribe = 0;
1421         if (auto VarSize = Var->getSizeInBits())
1422           BitsToDescribe = *VarSize;
1423         if (auto Fragment = Expr->getFragmentInfo())
1424           BitsToDescribe = Fragment->SizeInBits;
1425         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1426           // Bail out if all bits are described already.
1427           if (Offset >= BitsToDescribe)
1428             break;
1429           // TODO: handle scalable vectors.
1430           unsigned RegisterSize = RegAndSize.second;
1431           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1432                                       ? BitsToDescribe - Offset
1433                                       : RegisterSize;
1434           auto FragmentExpr = DIExpression::createFragmentExpression(
1435               Expr, Offset, FragmentSize);
1436           if (!FragmentExpr)
1437             continue;
1438           SDDbgValue *SDV = DAG.getVRegDbgValue(
1439               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1440           DAG.AddDbgValue(SDV, false);
1441           Offset += RegisterSize;
1442         }
1443         return true;
1444       }
1445       // We can use simple vreg locations for variadic dbg_values as well.
1446       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1447       continue;
1448     }
1449     // We failed to create a SDDbgOperand for V.
1450     return false;
1451   }
1452 
1453   // We have created a SDDbgOperand for each Value in Values.
1454   // Should use Order instead of SDNodeOrder?
1455   assert(!LocationOps.empty());
1456   SDDbgValue *SDV =
1457       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1458                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1459   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1460   return true;
1461 }
1462 
1463 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1464   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1465   for (auto &Pair : DanglingDebugInfoMap)
1466     for (auto &DDI : Pair.second)
1467       salvageUnresolvedDbgValue(DDI);
1468   clearDanglingDebugInfo();
1469 }
1470 
1471 /// getCopyFromRegs - If there was virtual register allocated for the value V
1472 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1473 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1474   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1475   SDValue Result;
1476 
1477   if (It != FuncInfo.ValueMap.end()) {
1478     Register InReg = It->second;
1479 
1480     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1481                      DAG.getDataLayout(), InReg, Ty,
1482                      None); // This is not an ABI copy.
1483     SDValue Chain = DAG.getEntryNode();
1484     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1485                                  V);
1486     resolveDanglingDebugInfo(V, Result);
1487   }
1488 
1489   return Result;
1490 }
1491 
1492 /// getValue - Return an SDValue for the given Value.
1493 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1494   // If we already have an SDValue for this value, use it. It's important
1495   // to do this first, so that we don't create a CopyFromReg if we already
1496   // have a regular SDValue.
1497   SDValue &N = NodeMap[V];
1498   if (N.getNode()) return N;
1499 
1500   // If there's a virtual register allocated and initialized for this
1501   // value, use it.
1502   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1503     return copyFromReg;
1504 
1505   // Otherwise create a new SDValue and remember it.
1506   SDValue Val = getValueImpl(V);
1507   NodeMap[V] = Val;
1508   resolveDanglingDebugInfo(V, Val);
1509   return Val;
1510 }
1511 
1512 /// getNonRegisterValue - Return an SDValue for the given Value, but
1513 /// don't look in FuncInfo.ValueMap for a virtual register.
1514 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1515   // If we already have an SDValue for this value, use it.
1516   SDValue &N = NodeMap[V];
1517   if (N.getNode()) {
1518     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1519       // Remove the debug location from the node as the node is about to be used
1520       // in a location which may differ from the original debug location.  This
1521       // is relevant to Constant and ConstantFP nodes because they can appear
1522       // as constant expressions inside PHI nodes.
1523       N->setDebugLoc(DebugLoc());
1524     }
1525     return N;
1526   }
1527 
1528   // Otherwise create a new SDValue and remember it.
1529   SDValue Val = getValueImpl(V);
1530   NodeMap[V] = Val;
1531   resolveDanglingDebugInfo(V, Val);
1532   return Val;
1533 }
1534 
1535 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1536 /// Create an SDValue for the given value.
1537 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1539 
1540   if (const Constant *C = dyn_cast<Constant>(V)) {
1541     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1542 
1543     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1544       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1545 
1546     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1547       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1548 
1549     if (isa<ConstantPointerNull>(C)) {
1550       unsigned AS = V->getType()->getPointerAddressSpace();
1551       return DAG.getConstant(0, getCurSDLoc(),
1552                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1553     }
1554 
1555     if (match(C, m_VScale(DAG.getDataLayout())))
1556       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1557 
1558     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1559       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1560 
1561     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1562       return DAG.getUNDEF(VT);
1563 
1564     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1565       visit(CE->getOpcode(), *CE);
1566       SDValue N1 = NodeMap[V];
1567       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1568       return N1;
1569     }
1570 
1571     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1572       SmallVector<SDValue, 4> Constants;
1573       for (const Use &U : C->operands()) {
1574         SDNode *Val = getValue(U).getNode();
1575         // If the operand is an empty aggregate, there are no values.
1576         if (!Val) continue;
1577         // Add each leaf value from the operand to the Constants list
1578         // to form a flattened list of all the values.
1579         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1580           Constants.push_back(SDValue(Val, i));
1581       }
1582 
1583       return DAG.getMergeValues(Constants, getCurSDLoc());
1584     }
1585 
1586     if (const ConstantDataSequential *CDS =
1587           dyn_cast<ConstantDataSequential>(C)) {
1588       SmallVector<SDValue, 4> Ops;
1589       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1590         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1591         // Add each leaf value from the operand to the Constants list
1592         // to form a flattened list of all the values.
1593         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1594           Ops.push_back(SDValue(Val, i));
1595       }
1596 
1597       if (isa<ArrayType>(CDS->getType()))
1598         return DAG.getMergeValues(Ops, getCurSDLoc());
1599       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1600     }
1601 
1602     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1603       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1604              "Unknown struct or array constant!");
1605 
1606       SmallVector<EVT, 4> ValueVTs;
1607       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1608       unsigned NumElts = ValueVTs.size();
1609       if (NumElts == 0)
1610         return SDValue(); // empty struct
1611       SmallVector<SDValue, 4> Constants(NumElts);
1612       for (unsigned i = 0; i != NumElts; ++i) {
1613         EVT EltVT = ValueVTs[i];
1614         if (isa<UndefValue>(C))
1615           Constants[i] = DAG.getUNDEF(EltVT);
1616         else if (EltVT.isFloatingPoint())
1617           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1618         else
1619           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1620       }
1621 
1622       return DAG.getMergeValues(Constants, getCurSDLoc());
1623     }
1624 
1625     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1626       return DAG.getBlockAddress(BA, VT);
1627 
1628     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1629       return getValue(Equiv->getGlobalValue());
1630 
1631     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1632       return getValue(NC->getGlobalValue());
1633 
1634     VectorType *VecTy = cast<VectorType>(V->getType());
1635 
1636     // Now that we know the number and type of the elements, get that number of
1637     // elements into the Ops array based on what kind of constant it is.
1638     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1639       SmallVector<SDValue, 16> Ops;
1640       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1641       for (unsigned i = 0; i != NumElements; ++i)
1642         Ops.push_back(getValue(CV->getOperand(i)));
1643 
1644       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1645     }
1646 
1647     if (isa<ConstantAggregateZero>(C)) {
1648       EVT EltVT =
1649           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1650 
1651       SDValue Op;
1652       if (EltVT.isFloatingPoint())
1653         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1654       else
1655         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1656 
1657       if (isa<ScalableVectorType>(VecTy))
1658         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1659 
1660       SmallVector<SDValue, 16> Ops;
1661       Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1662       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1663     }
1664 
1665     llvm_unreachable("Unknown vector constant");
1666   }
1667 
1668   // If this is a static alloca, generate it as the frameindex instead of
1669   // computation.
1670   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1671     DenseMap<const AllocaInst*, int>::iterator SI =
1672       FuncInfo.StaticAllocaMap.find(AI);
1673     if (SI != FuncInfo.StaticAllocaMap.end())
1674       return DAG.getFrameIndex(SI->second,
1675                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1676   }
1677 
1678   // If this is an instruction which fast-isel has deferred, select it now.
1679   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1680     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1681 
1682     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1683                      Inst->getType(), None);
1684     SDValue Chain = DAG.getEntryNode();
1685     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1686   }
1687 
1688   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1689     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1690 
1691   if (const auto *BB = dyn_cast<BasicBlock>(V))
1692     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1693 
1694   llvm_unreachable("Can't get register for value!");
1695 }
1696 
1697 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1698   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1699   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1700   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1701   bool IsSEH = isAsynchronousEHPersonality(Pers);
1702   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1703   if (!IsSEH)
1704     CatchPadMBB->setIsEHScopeEntry();
1705   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1706   if (IsMSVCCXX || IsCoreCLR)
1707     CatchPadMBB->setIsEHFuncletEntry();
1708 }
1709 
1710 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1711   // Update machine-CFG edge.
1712   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1713   FuncInfo.MBB->addSuccessor(TargetMBB);
1714   TargetMBB->setIsEHCatchretTarget(true);
1715   DAG.getMachineFunction().setHasEHCatchret(true);
1716 
1717   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1718   bool IsSEH = isAsynchronousEHPersonality(Pers);
1719   if (IsSEH) {
1720     // If this is not a fall-through branch or optimizations are switched off,
1721     // emit the branch.
1722     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1723         TM.getOptLevel() == CodeGenOpt::None)
1724       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1725                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1726     return;
1727   }
1728 
1729   // Figure out the funclet membership for the catchret's successor.
1730   // This will be used by the FuncletLayout pass to determine how to order the
1731   // BB's.
1732   // A 'catchret' returns to the outer scope's color.
1733   Value *ParentPad = I.getCatchSwitchParentPad();
1734   const BasicBlock *SuccessorColor;
1735   if (isa<ConstantTokenNone>(ParentPad))
1736     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1737   else
1738     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1739   assert(SuccessorColor && "No parent funclet for catchret!");
1740   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1741   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1742 
1743   // Create the terminator node.
1744   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1745                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1746                             DAG.getBasicBlock(SuccessorColorMBB));
1747   DAG.setRoot(Ret);
1748 }
1749 
1750 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1751   // Don't emit any special code for the cleanuppad instruction. It just marks
1752   // the start of an EH scope/funclet.
1753   FuncInfo.MBB->setIsEHScopeEntry();
1754   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1755   if (Pers != EHPersonality::Wasm_CXX) {
1756     FuncInfo.MBB->setIsEHFuncletEntry();
1757     FuncInfo.MBB->setIsCleanupFuncletEntry();
1758   }
1759 }
1760 
1761 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1762 // not match, it is OK to add only the first unwind destination catchpad to the
1763 // successors, because there will be at least one invoke instruction within the
1764 // catch scope that points to the next unwind destination, if one exists, so
1765 // CFGSort cannot mess up with BB sorting order.
1766 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1767 // call within them, and catchpads only consisting of 'catch (...)' have a
1768 // '__cxa_end_catch' call within them, both of which generate invokes in case
1769 // the next unwind destination exists, i.e., the next unwind destination is not
1770 // the caller.)
1771 //
1772 // Having at most one EH pad successor is also simpler and helps later
1773 // transformations.
1774 //
1775 // For example,
1776 // current:
1777 //   invoke void @foo to ... unwind label %catch.dispatch
1778 // catch.dispatch:
1779 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1780 // catch.start:
1781 //   ...
1782 //   ... in this BB or some other child BB dominated by this BB there will be an
1783 //   invoke that points to 'next' BB as an unwind destination
1784 //
1785 // next: ; We don't need to add this to 'current' BB's successor
1786 //   ...
1787 static void findWasmUnwindDestinations(
1788     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1789     BranchProbability Prob,
1790     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1791         &UnwindDests) {
1792   while (EHPadBB) {
1793     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1794     if (isa<CleanupPadInst>(Pad)) {
1795       // Stop on cleanup pads.
1796       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1797       UnwindDests.back().first->setIsEHScopeEntry();
1798       break;
1799     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1800       // Add the catchpad handlers to the possible destinations. We don't
1801       // continue to the unwind destination of the catchswitch for wasm.
1802       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1803         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1804         UnwindDests.back().first->setIsEHScopeEntry();
1805       }
1806       break;
1807     } else {
1808       continue;
1809     }
1810   }
1811 }
1812 
1813 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1814 /// many places it could ultimately go. In the IR, we have a single unwind
1815 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1816 /// This function skips over imaginary basic blocks that hold catchswitch
1817 /// instructions, and finds all the "real" machine
1818 /// basic block destinations. As those destinations may not be successors of
1819 /// EHPadBB, here we also calculate the edge probability to those destinations.
1820 /// The passed-in Prob is the edge probability to EHPadBB.
1821 static void findUnwindDestinations(
1822     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1823     BranchProbability Prob,
1824     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1825         &UnwindDests) {
1826   EHPersonality Personality =
1827     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1828   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1829   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1830   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1831   bool IsSEH = isAsynchronousEHPersonality(Personality);
1832 
1833   if (IsWasmCXX) {
1834     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1835     assert(UnwindDests.size() <= 1 &&
1836            "There should be at most one unwind destination for wasm");
1837     return;
1838   }
1839 
1840   while (EHPadBB) {
1841     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1842     BasicBlock *NewEHPadBB = nullptr;
1843     if (isa<LandingPadInst>(Pad)) {
1844       // Stop on landingpads. They are not funclets.
1845       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1846       break;
1847     } else if (isa<CleanupPadInst>(Pad)) {
1848       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1849       // personalities.
1850       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1851       UnwindDests.back().first->setIsEHScopeEntry();
1852       UnwindDests.back().first->setIsEHFuncletEntry();
1853       break;
1854     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1855       // Add the catchpad handlers to the possible destinations.
1856       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1857         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1858         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1859         if (IsMSVCCXX || IsCoreCLR)
1860           UnwindDests.back().first->setIsEHFuncletEntry();
1861         if (!IsSEH)
1862           UnwindDests.back().first->setIsEHScopeEntry();
1863       }
1864       NewEHPadBB = CatchSwitch->getUnwindDest();
1865     } else {
1866       continue;
1867     }
1868 
1869     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1870     if (BPI && NewEHPadBB)
1871       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1872     EHPadBB = NewEHPadBB;
1873   }
1874 }
1875 
1876 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1877   // Update successor info.
1878   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1879   auto UnwindDest = I.getUnwindDest();
1880   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1881   BranchProbability UnwindDestProb =
1882       (BPI && UnwindDest)
1883           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1884           : BranchProbability::getZero();
1885   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1886   for (auto &UnwindDest : UnwindDests) {
1887     UnwindDest.first->setIsEHPad();
1888     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1889   }
1890   FuncInfo.MBB->normalizeSuccProbs();
1891 
1892   // Create the terminator node.
1893   SDValue Ret =
1894       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1895   DAG.setRoot(Ret);
1896 }
1897 
1898 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1899   report_fatal_error("visitCatchSwitch not yet implemented!");
1900 }
1901 
1902 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1903   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1904   auto &DL = DAG.getDataLayout();
1905   SDValue Chain = getControlRoot();
1906   SmallVector<ISD::OutputArg, 8> Outs;
1907   SmallVector<SDValue, 8> OutVals;
1908 
1909   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1910   // lower
1911   //
1912   //   %val = call <ty> @llvm.experimental.deoptimize()
1913   //   ret <ty> %val
1914   //
1915   // differently.
1916   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1917     LowerDeoptimizingReturn();
1918     return;
1919   }
1920 
1921   if (!FuncInfo.CanLowerReturn) {
1922     unsigned DemoteReg = FuncInfo.DemoteRegister;
1923     const Function *F = I.getParent()->getParent();
1924 
1925     // Emit a store of the return value through the virtual register.
1926     // Leave Outs empty so that LowerReturn won't try to load return
1927     // registers the usual way.
1928     SmallVector<EVT, 1> PtrValueVTs;
1929     ComputeValueVTs(TLI, DL,
1930                     F->getReturnType()->getPointerTo(
1931                         DAG.getDataLayout().getAllocaAddrSpace()),
1932                     PtrValueVTs);
1933 
1934     SDValue RetPtr =
1935         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1936     SDValue RetOp = getValue(I.getOperand(0));
1937 
1938     SmallVector<EVT, 4> ValueVTs, MemVTs;
1939     SmallVector<uint64_t, 4> Offsets;
1940     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1941                     &Offsets);
1942     unsigned NumValues = ValueVTs.size();
1943 
1944     SmallVector<SDValue, 4> Chains(NumValues);
1945     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1946     for (unsigned i = 0; i != NumValues; ++i) {
1947       // An aggregate return value cannot wrap around the address space, so
1948       // offsets to its parts don't wrap either.
1949       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1950                                            TypeSize::Fixed(Offsets[i]));
1951 
1952       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1953       if (MemVTs[i] != ValueVTs[i])
1954         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1955       Chains[i] = DAG.getStore(
1956           Chain, getCurSDLoc(), Val,
1957           // FIXME: better loc info would be nice.
1958           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1959           commonAlignment(BaseAlign, Offsets[i]));
1960     }
1961 
1962     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1963                         MVT::Other, Chains);
1964   } else if (I.getNumOperands() != 0) {
1965     SmallVector<EVT, 4> ValueVTs;
1966     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1967     unsigned NumValues = ValueVTs.size();
1968     if (NumValues) {
1969       SDValue RetOp = getValue(I.getOperand(0));
1970 
1971       const Function *F = I.getParent()->getParent();
1972 
1973       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1974           I.getOperand(0)->getType(), F->getCallingConv(),
1975           /*IsVarArg*/ false, DL);
1976 
1977       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1978       if (F->getAttributes().hasRetAttr(Attribute::SExt))
1979         ExtendKind = ISD::SIGN_EXTEND;
1980       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
1981         ExtendKind = ISD::ZERO_EXTEND;
1982 
1983       LLVMContext &Context = F->getContext();
1984       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
1985 
1986       for (unsigned j = 0; j != NumValues; ++j) {
1987         EVT VT = ValueVTs[j];
1988 
1989         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1990           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1991 
1992         CallingConv::ID CC = F->getCallingConv();
1993 
1994         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1995         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1996         SmallVector<SDValue, 4> Parts(NumParts);
1997         getCopyToParts(DAG, getCurSDLoc(),
1998                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1999                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2000 
2001         // 'inreg' on function refers to return value
2002         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2003         if (RetInReg)
2004           Flags.setInReg();
2005 
2006         if (I.getOperand(0)->getType()->isPointerTy()) {
2007           Flags.setPointer();
2008           Flags.setPointerAddrSpace(
2009               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2010         }
2011 
2012         if (NeedsRegBlock) {
2013           Flags.setInConsecutiveRegs();
2014           if (j == NumValues - 1)
2015             Flags.setInConsecutiveRegsLast();
2016         }
2017 
2018         // Propagate extension type if any
2019         if (ExtendKind == ISD::SIGN_EXTEND)
2020           Flags.setSExt();
2021         else if (ExtendKind == ISD::ZERO_EXTEND)
2022           Flags.setZExt();
2023 
2024         for (unsigned i = 0; i < NumParts; ++i) {
2025           Outs.push_back(ISD::OutputArg(Flags,
2026                                         Parts[i].getValueType().getSimpleVT(),
2027                                         VT, /*isfixed=*/true, 0, 0));
2028           OutVals.push_back(Parts[i]);
2029         }
2030       }
2031     }
2032   }
2033 
2034   // Push in swifterror virtual register as the last element of Outs. This makes
2035   // sure swifterror virtual register will be returned in the swifterror
2036   // physical register.
2037   const Function *F = I.getParent()->getParent();
2038   if (TLI.supportSwiftError() &&
2039       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2040     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2041     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2042     Flags.setSwiftError();
2043     Outs.push_back(ISD::OutputArg(
2044         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2045         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2046     // Create SDNode for the swifterror virtual register.
2047     OutVals.push_back(
2048         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2049                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2050                         EVT(TLI.getPointerTy(DL))));
2051   }
2052 
2053   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2054   CallingConv::ID CallConv =
2055     DAG.getMachineFunction().getFunction().getCallingConv();
2056   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2057       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2058 
2059   // Verify that the target's LowerReturn behaved as expected.
2060   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2061          "LowerReturn didn't return a valid chain!");
2062 
2063   // Update the DAG with the new chain value resulting from return lowering.
2064   DAG.setRoot(Chain);
2065 }
2066 
2067 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2068 /// created for it, emit nodes to copy the value into the virtual
2069 /// registers.
2070 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2071   // Skip empty types
2072   if (V->getType()->isEmptyTy())
2073     return;
2074 
2075   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2076   if (VMI != FuncInfo.ValueMap.end()) {
2077     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2078     CopyValueToVirtualRegister(V, VMI->second);
2079   }
2080 }
2081 
2082 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2083 /// the current basic block, add it to ValueMap now so that we'll get a
2084 /// CopyTo/FromReg.
2085 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2086   // No need to export constants.
2087   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2088 
2089   // Already exported?
2090   if (FuncInfo.isExportedInst(V)) return;
2091 
2092   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2093   CopyValueToVirtualRegister(V, Reg);
2094 }
2095 
2096 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2097                                                      const BasicBlock *FromBB) {
2098   // The operands of the setcc have to be in this block.  We don't know
2099   // how to export them from some other block.
2100   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2101     // Can export from current BB.
2102     if (VI->getParent() == FromBB)
2103       return true;
2104 
2105     // Is already exported, noop.
2106     return FuncInfo.isExportedInst(V);
2107   }
2108 
2109   // If this is an argument, we can export it if the BB is the entry block or
2110   // if it is already exported.
2111   if (isa<Argument>(V)) {
2112     if (FromBB->isEntryBlock())
2113       return true;
2114 
2115     // Otherwise, can only export this if it is already exported.
2116     return FuncInfo.isExportedInst(V);
2117   }
2118 
2119   // Otherwise, constants can always be exported.
2120   return true;
2121 }
2122 
2123 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2124 BranchProbability
2125 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2126                                         const MachineBasicBlock *Dst) const {
2127   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2128   const BasicBlock *SrcBB = Src->getBasicBlock();
2129   const BasicBlock *DstBB = Dst->getBasicBlock();
2130   if (!BPI) {
2131     // If BPI is not available, set the default probability as 1 / N, where N is
2132     // the number of successors.
2133     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2134     return BranchProbability(1, SuccSize);
2135   }
2136   return BPI->getEdgeProbability(SrcBB, DstBB);
2137 }
2138 
2139 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2140                                                MachineBasicBlock *Dst,
2141                                                BranchProbability Prob) {
2142   if (!FuncInfo.BPI)
2143     Src->addSuccessorWithoutProb(Dst);
2144   else {
2145     if (Prob.isUnknown())
2146       Prob = getEdgeProbability(Src, Dst);
2147     Src->addSuccessor(Dst, Prob);
2148   }
2149 }
2150 
2151 static bool InBlock(const Value *V, const BasicBlock *BB) {
2152   if (const Instruction *I = dyn_cast<Instruction>(V))
2153     return I->getParent() == BB;
2154   return true;
2155 }
2156 
2157 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2158 /// This function emits a branch and is used at the leaves of an OR or an
2159 /// AND operator tree.
2160 void
2161 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2162                                                   MachineBasicBlock *TBB,
2163                                                   MachineBasicBlock *FBB,
2164                                                   MachineBasicBlock *CurBB,
2165                                                   MachineBasicBlock *SwitchBB,
2166                                                   BranchProbability TProb,
2167                                                   BranchProbability FProb,
2168                                                   bool InvertCond) {
2169   const BasicBlock *BB = CurBB->getBasicBlock();
2170 
2171   // If the leaf of the tree is a comparison, merge the condition into
2172   // the caseblock.
2173   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2174     // The operands of the cmp have to be in this block.  We don't know
2175     // how to export them from some other block.  If this is the first block
2176     // of the sequence, no exporting is needed.
2177     if (CurBB == SwitchBB ||
2178         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2179          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2180       ISD::CondCode Condition;
2181       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2182         ICmpInst::Predicate Pred =
2183             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2184         Condition = getICmpCondCode(Pred);
2185       } else {
2186         const FCmpInst *FC = cast<FCmpInst>(Cond);
2187         FCmpInst::Predicate Pred =
2188             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2189         Condition = getFCmpCondCode(Pred);
2190         if (TM.Options.NoNaNsFPMath)
2191           Condition = getFCmpCodeWithoutNaN(Condition);
2192       }
2193 
2194       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2195                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2196       SL->SwitchCases.push_back(CB);
2197       return;
2198     }
2199   }
2200 
2201   // Create a CaseBlock record representing this branch.
2202   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2203   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2204                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2205   SL->SwitchCases.push_back(CB);
2206 }
2207 
2208 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2209                                                MachineBasicBlock *TBB,
2210                                                MachineBasicBlock *FBB,
2211                                                MachineBasicBlock *CurBB,
2212                                                MachineBasicBlock *SwitchBB,
2213                                                Instruction::BinaryOps Opc,
2214                                                BranchProbability TProb,
2215                                                BranchProbability FProb,
2216                                                bool InvertCond) {
2217   // Skip over not part of the tree and remember to invert op and operands at
2218   // next level.
2219   Value *NotCond;
2220   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2221       InBlock(NotCond, CurBB->getBasicBlock())) {
2222     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2223                          !InvertCond);
2224     return;
2225   }
2226 
2227   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2228   const Value *BOpOp0, *BOpOp1;
2229   // Compute the effective opcode for Cond, taking into account whether it needs
2230   // to be inverted, e.g.
2231   //   and (not (or A, B)), C
2232   // gets lowered as
2233   //   and (and (not A, not B), C)
2234   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2235   if (BOp) {
2236     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2237                ? Instruction::And
2238                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2239                       ? Instruction::Or
2240                       : (Instruction::BinaryOps)0);
2241     if (InvertCond) {
2242       if (BOpc == Instruction::And)
2243         BOpc = Instruction::Or;
2244       else if (BOpc == Instruction::Or)
2245         BOpc = Instruction::And;
2246     }
2247   }
2248 
2249   // If this node is not part of the or/and tree, emit it as a branch.
2250   // Note that all nodes in the tree should have same opcode.
2251   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2252   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2253       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2254       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2255     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2256                                  TProb, FProb, InvertCond);
2257     return;
2258   }
2259 
2260   //  Create TmpBB after CurBB.
2261   MachineFunction::iterator BBI(CurBB);
2262   MachineFunction &MF = DAG.getMachineFunction();
2263   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2264   CurBB->getParent()->insert(++BBI, TmpBB);
2265 
2266   if (Opc == Instruction::Or) {
2267     // Codegen X | Y as:
2268     // BB1:
2269     //   jmp_if_X TBB
2270     //   jmp TmpBB
2271     // TmpBB:
2272     //   jmp_if_Y TBB
2273     //   jmp FBB
2274     //
2275 
2276     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2277     // The requirement is that
2278     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2279     //     = TrueProb for original BB.
2280     // Assuming the original probabilities are A and B, one choice is to set
2281     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2282     // A/(1+B) and 2B/(1+B). This choice assumes that
2283     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2284     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2285     // TmpBB, but the math is more complicated.
2286 
2287     auto NewTrueProb = TProb / 2;
2288     auto NewFalseProb = TProb / 2 + FProb;
2289     // Emit the LHS condition.
2290     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2291                          NewFalseProb, InvertCond);
2292 
2293     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2294     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2295     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2296     // Emit the RHS condition into TmpBB.
2297     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2298                          Probs[1], InvertCond);
2299   } else {
2300     assert(Opc == Instruction::And && "Unknown merge op!");
2301     // Codegen X & Y as:
2302     // BB1:
2303     //   jmp_if_X TmpBB
2304     //   jmp FBB
2305     // TmpBB:
2306     //   jmp_if_Y TBB
2307     //   jmp FBB
2308     //
2309     //  This requires creation of TmpBB after CurBB.
2310 
2311     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2312     // The requirement is that
2313     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2314     //     = FalseProb for original BB.
2315     // Assuming the original probabilities are A and B, one choice is to set
2316     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2317     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2318     // TrueProb for BB1 * FalseProb for TmpBB.
2319 
2320     auto NewTrueProb = TProb + FProb / 2;
2321     auto NewFalseProb = FProb / 2;
2322     // Emit the LHS condition.
2323     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2324                          NewFalseProb, InvertCond);
2325 
2326     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2327     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2328     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2329     // Emit the RHS condition into TmpBB.
2330     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2331                          Probs[1], InvertCond);
2332   }
2333 }
2334 
2335 /// If the set of cases should be emitted as a series of branches, return true.
2336 /// If we should emit this as a bunch of and/or'd together conditions, return
2337 /// false.
2338 bool
2339 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2340   if (Cases.size() != 2) return true;
2341 
2342   // If this is two comparisons of the same values or'd or and'd together, they
2343   // will get folded into a single comparison, so don't emit two blocks.
2344   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2345        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2346       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2347        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2348     return false;
2349   }
2350 
2351   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2352   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2353   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2354       Cases[0].CC == Cases[1].CC &&
2355       isa<Constant>(Cases[0].CmpRHS) &&
2356       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2357     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2358       return false;
2359     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2360       return false;
2361   }
2362 
2363   return true;
2364 }
2365 
2366 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2367   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2368 
2369   // Update machine-CFG edges.
2370   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2371 
2372   if (I.isUnconditional()) {
2373     // Update machine-CFG edges.
2374     BrMBB->addSuccessor(Succ0MBB);
2375 
2376     // If this is not a fall-through branch or optimizations are switched off,
2377     // emit the branch.
2378     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2379       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2380                               MVT::Other, getControlRoot(),
2381                               DAG.getBasicBlock(Succ0MBB)));
2382 
2383     return;
2384   }
2385 
2386   // If this condition is one of the special cases we handle, do special stuff
2387   // now.
2388   const Value *CondVal = I.getCondition();
2389   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2390 
2391   // If this is a series of conditions that are or'd or and'd together, emit
2392   // this as a sequence of branches instead of setcc's with and/or operations.
2393   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2394   // unpredictable branches, and vector extracts because those jumps are likely
2395   // expensive for any target), this should improve performance.
2396   // For example, instead of something like:
2397   //     cmp A, B
2398   //     C = seteq
2399   //     cmp D, E
2400   //     F = setle
2401   //     or C, F
2402   //     jnz foo
2403   // Emit:
2404   //     cmp A, B
2405   //     je foo
2406   //     cmp D, E
2407   //     jle foo
2408   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2409   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2410       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2411     Value *Vec;
2412     const Value *BOp0, *BOp1;
2413     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2414     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2415       Opcode = Instruction::And;
2416     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2417       Opcode = Instruction::Or;
2418 
2419     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2420                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2421       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2422                            getEdgeProbability(BrMBB, Succ0MBB),
2423                            getEdgeProbability(BrMBB, Succ1MBB),
2424                            /*InvertCond=*/false);
2425       // If the compares in later blocks need to use values not currently
2426       // exported from this block, export them now.  This block should always
2427       // be the first entry.
2428       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2429 
2430       // Allow some cases to be rejected.
2431       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2432         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2433           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2434           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2435         }
2436 
2437         // Emit the branch for this block.
2438         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2439         SL->SwitchCases.erase(SL->SwitchCases.begin());
2440         return;
2441       }
2442 
2443       // Okay, we decided not to do this, remove any inserted MBB's and clear
2444       // SwitchCases.
2445       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2446         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2447 
2448       SL->SwitchCases.clear();
2449     }
2450   }
2451 
2452   // Create a CaseBlock record representing this branch.
2453   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2454                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2455 
2456   // Use visitSwitchCase to actually insert the fast branch sequence for this
2457   // cond branch.
2458   visitSwitchCase(CB, BrMBB);
2459 }
2460 
2461 /// visitSwitchCase - Emits the necessary code to represent a single node in
2462 /// the binary search tree resulting from lowering a switch instruction.
2463 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2464                                           MachineBasicBlock *SwitchBB) {
2465   SDValue Cond;
2466   SDValue CondLHS = getValue(CB.CmpLHS);
2467   SDLoc dl = CB.DL;
2468 
2469   if (CB.CC == ISD::SETTRUE) {
2470     // Branch or fall through to TrueBB.
2471     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2472     SwitchBB->normalizeSuccProbs();
2473     if (CB.TrueBB != NextBlock(SwitchBB)) {
2474       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2475                               DAG.getBasicBlock(CB.TrueBB)));
2476     }
2477     return;
2478   }
2479 
2480   auto &TLI = DAG.getTargetLoweringInfo();
2481   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2482 
2483   // Build the setcc now.
2484   if (!CB.CmpMHS) {
2485     // Fold "(X == true)" to X and "(X == false)" to !X to
2486     // handle common cases produced by branch lowering.
2487     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2488         CB.CC == ISD::SETEQ)
2489       Cond = CondLHS;
2490     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2491              CB.CC == ISD::SETEQ) {
2492       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2493       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2494     } else {
2495       SDValue CondRHS = getValue(CB.CmpRHS);
2496 
2497       // If a pointer's DAG type is larger than its memory type then the DAG
2498       // values are zero-extended. This breaks signed comparisons so truncate
2499       // back to the underlying type before doing the compare.
2500       if (CondLHS.getValueType() != MemVT) {
2501         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2502         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2503       }
2504       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2505     }
2506   } else {
2507     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2508 
2509     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2510     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2511 
2512     SDValue CmpOp = getValue(CB.CmpMHS);
2513     EVT VT = CmpOp.getValueType();
2514 
2515     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2516       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2517                           ISD::SETLE);
2518     } else {
2519       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2520                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2521       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2522                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2523     }
2524   }
2525 
2526   // Update successor info
2527   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2528   // TrueBB and FalseBB are always different unless the incoming IR is
2529   // degenerate. This only happens when running llc on weird IR.
2530   if (CB.TrueBB != CB.FalseBB)
2531     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2532   SwitchBB->normalizeSuccProbs();
2533 
2534   // If the lhs block is the next block, invert the condition so that we can
2535   // fall through to the lhs instead of the rhs block.
2536   if (CB.TrueBB == NextBlock(SwitchBB)) {
2537     std::swap(CB.TrueBB, CB.FalseBB);
2538     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2539     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2540   }
2541 
2542   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2543                                MVT::Other, getControlRoot(), Cond,
2544                                DAG.getBasicBlock(CB.TrueBB));
2545 
2546   // Insert the false branch. Do this even if it's a fall through branch,
2547   // this makes it easier to do DAG optimizations which require inverting
2548   // the branch condition.
2549   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2550                        DAG.getBasicBlock(CB.FalseBB));
2551 
2552   DAG.setRoot(BrCond);
2553 }
2554 
2555 /// visitJumpTable - Emit JumpTable node in the current MBB
2556 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2557   // Emit the code for the jump table
2558   assert(JT.Reg != -1U && "Should lower JT Header first!");
2559   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2560   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2561                                      JT.Reg, PTy);
2562   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2563   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2564                                     MVT::Other, Index.getValue(1),
2565                                     Table, Index);
2566   DAG.setRoot(BrJumpTable);
2567 }
2568 
2569 /// visitJumpTableHeader - This function emits necessary code to produce index
2570 /// in the JumpTable from switch case.
2571 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2572                                                JumpTableHeader &JTH,
2573                                                MachineBasicBlock *SwitchBB) {
2574   SDLoc dl = getCurSDLoc();
2575 
2576   // Subtract the lowest switch case value from the value being switched on.
2577   SDValue SwitchOp = getValue(JTH.SValue);
2578   EVT VT = SwitchOp.getValueType();
2579   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2580                             DAG.getConstant(JTH.First, dl, VT));
2581 
2582   // The SDNode we just created, which holds the value being switched on minus
2583   // the smallest case value, needs to be copied to a virtual register so it
2584   // can be used as an index into the jump table in a subsequent basic block.
2585   // This value may be smaller or larger than the target's pointer type, and
2586   // therefore require extension or truncating.
2587   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2588   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2589 
2590   unsigned JumpTableReg =
2591       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2592   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2593                                     JumpTableReg, SwitchOp);
2594   JT.Reg = JumpTableReg;
2595 
2596   if (!JTH.FallthroughUnreachable) {
2597     // Emit the range check for the jump table, and branch to the default block
2598     // for the switch statement if the value being switched on exceeds the
2599     // largest case in the switch.
2600     SDValue CMP = DAG.getSetCC(
2601         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2602                                    Sub.getValueType()),
2603         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2604 
2605     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2606                                  MVT::Other, CopyTo, CMP,
2607                                  DAG.getBasicBlock(JT.Default));
2608 
2609     // Avoid emitting unnecessary branches to the next block.
2610     if (JT.MBB != NextBlock(SwitchBB))
2611       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2612                            DAG.getBasicBlock(JT.MBB));
2613 
2614     DAG.setRoot(BrCond);
2615   } else {
2616     // Avoid emitting unnecessary branches to the next block.
2617     if (JT.MBB != NextBlock(SwitchBB))
2618       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2619                               DAG.getBasicBlock(JT.MBB)));
2620     else
2621       DAG.setRoot(CopyTo);
2622   }
2623 }
2624 
2625 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2626 /// variable if there exists one.
2627 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2628                                  SDValue &Chain) {
2629   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2630   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2631   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2632   MachineFunction &MF = DAG.getMachineFunction();
2633   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2634   MachineSDNode *Node =
2635       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2636   if (Global) {
2637     MachinePointerInfo MPInfo(Global);
2638     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2639                  MachineMemOperand::MODereferenceable;
2640     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2641         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2642     DAG.setNodeMemRefs(Node, {MemRef});
2643   }
2644   if (PtrTy != PtrMemTy)
2645     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2646   return SDValue(Node, 0);
2647 }
2648 
2649 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2650 /// tail spliced into a stack protector check success bb.
2651 ///
2652 /// For a high level explanation of how this fits into the stack protector
2653 /// generation see the comment on the declaration of class
2654 /// StackProtectorDescriptor.
2655 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2656                                                   MachineBasicBlock *ParentBB) {
2657 
2658   // First create the loads to the guard/stack slot for the comparison.
2659   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2660   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2661   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2662 
2663   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2664   int FI = MFI.getStackProtectorIndex();
2665 
2666   SDValue Guard;
2667   SDLoc dl = getCurSDLoc();
2668   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2669   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2670   Align Align =
2671       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2672 
2673   // Generate code to load the content of the guard slot.
2674   SDValue GuardVal = DAG.getLoad(
2675       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2676       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2677       MachineMemOperand::MOVolatile);
2678 
2679   if (TLI.useStackGuardXorFP())
2680     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2681 
2682   // Retrieve guard check function, nullptr if instrumentation is inlined.
2683   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2684     // The target provides a guard check function to validate the guard value.
2685     // Generate a call to that function with the content of the guard slot as
2686     // argument.
2687     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2688     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2689 
2690     TargetLowering::ArgListTy Args;
2691     TargetLowering::ArgListEntry Entry;
2692     Entry.Node = GuardVal;
2693     Entry.Ty = FnTy->getParamType(0);
2694     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2695       Entry.IsInReg = true;
2696     Args.push_back(Entry);
2697 
2698     TargetLowering::CallLoweringInfo CLI(DAG);
2699     CLI.setDebugLoc(getCurSDLoc())
2700         .setChain(DAG.getEntryNode())
2701         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2702                    getValue(GuardCheckFn), std::move(Args));
2703 
2704     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2705     DAG.setRoot(Result.second);
2706     return;
2707   }
2708 
2709   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2710   // Otherwise, emit a volatile load to retrieve the stack guard value.
2711   SDValue Chain = DAG.getEntryNode();
2712   if (TLI.useLoadStackGuardNode()) {
2713     Guard = getLoadStackGuard(DAG, dl, Chain);
2714   } else {
2715     const Value *IRGuard = TLI.getSDagStackGuard(M);
2716     SDValue GuardPtr = getValue(IRGuard);
2717 
2718     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2719                         MachinePointerInfo(IRGuard, 0), Align,
2720                         MachineMemOperand::MOVolatile);
2721   }
2722 
2723   // Perform the comparison via a getsetcc.
2724   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2725                                                         *DAG.getContext(),
2726                                                         Guard.getValueType()),
2727                              Guard, GuardVal, ISD::SETNE);
2728 
2729   // If the guard/stackslot do not equal, branch to failure MBB.
2730   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2731                                MVT::Other, GuardVal.getOperand(0),
2732                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2733   // Otherwise branch to success MBB.
2734   SDValue Br = DAG.getNode(ISD::BR, dl,
2735                            MVT::Other, BrCond,
2736                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2737 
2738   DAG.setRoot(Br);
2739 }
2740 
2741 /// Codegen the failure basic block for a stack protector check.
2742 ///
2743 /// A failure stack protector machine basic block consists simply of a call to
2744 /// __stack_chk_fail().
2745 ///
2746 /// For a high level explanation of how this fits into the stack protector
2747 /// generation see the comment on the declaration of class
2748 /// StackProtectorDescriptor.
2749 void
2750 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2751   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2752   TargetLowering::MakeLibCallOptions CallOptions;
2753   CallOptions.setDiscardResult(true);
2754   SDValue Chain =
2755       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2756                       None, CallOptions, getCurSDLoc()).second;
2757   // On PS4/PS5, the "return address" must still be within the calling
2758   // function, even if it's at the very end, so emit an explicit TRAP here.
2759   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2760   if (TM.getTargetTriple().isPS())
2761     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2762   // WebAssembly needs an unreachable instruction after a non-returning call,
2763   // because the function return type can be different from __stack_chk_fail's
2764   // return type (void).
2765   if (TM.getTargetTriple().isWasm())
2766     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2767 
2768   DAG.setRoot(Chain);
2769 }
2770 
2771 /// visitBitTestHeader - This function emits necessary code to produce value
2772 /// suitable for "bit tests"
2773 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2774                                              MachineBasicBlock *SwitchBB) {
2775   SDLoc dl = getCurSDLoc();
2776 
2777   // Subtract the minimum value.
2778   SDValue SwitchOp = getValue(B.SValue);
2779   EVT VT = SwitchOp.getValueType();
2780   SDValue RangeSub =
2781       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2782 
2783   // Determine the type of the test operands.
2784   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2785   bool UsePtrType = false;
2786   if (!TLI.isTypeLegal(VT)) {
2787     UsePtrType = true;
2788   } else {
2789     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2790       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2791         // Switch table case range are encoded into series of masks.
2792         // Just use pointer type, it's guaranteed to fit.
2793         UsePtrType = true;
2794         break;
2795       }
2796   }
2797   SDValue Sub = RangeSub;
2798   if (UsePtrType) {
2799     VT = TLI.getPointerTy(DAG.getDataLayout());
2800     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2801   }
2802 
2803   B.RegVT = VT.getSimpleVT();
2804   B.Reg = FuncInfo.CreateReg(B.RegVT);
2805   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2806 
2807   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2808 
2809   if (!B.FallthroughUnreachable)
2810     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2811   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2812   SwitchBB->normalizeSuccProbs();
2813 
2814   SDValue Root = CopyTo;
2815   if (!B.FallthroughUnreachable) {
2816     // Conditional branch to the default block.
2817     SDValue RangeCmp = DAG.getSetCC(dl,
2818         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2819                                RangeSub.getValueType()),
2820         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2821         ISD::SETUGT);
2822 
2823     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2824                        DAG.getBasicBlock(B.Default));
2825   }
2826 
2827   // Avoid emitting unnecessary branches to the next block.
2828   if (MBB != NextBlock(SwitchBB))
2829     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2830 
2831   DAG.setRoot(Root);
2832 }
2833 
2834 /// visitBitTestCase - this function produces one "bit test"
2835 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2836                                            MachineBasicBlock* NextMBB,
2837                                            BranchProbability BranchProbToNext,
2838                                            unsigned Reg,
2839                                            BitTestCase &B,
2840                                            MachineBasicBlock *SwitchBB) {
2841   SDLoc dl = getCurSDLoc();
2842   MVT VT = BB.RegVT;
2843   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2844   SDValue Cmp;
2845   unsigned PopCount = countPopulation(B.Mask);
2846   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2847   if (PopCount == 1) {
2848     // Testing for a single bit; just compare the shift count with what it
2849     // would need to be to shift a 1 bit in that position.
2850     Cmp = DAG.getSetCC(
2851         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2852         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2853         ISD::SETEQ);
2854   } else if (PopCount == BB.Range) {
2855     // There is only one zero bit in the range, test for it directly.
2856     Cmp = DAG.getSetCC(
2857         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2858         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2859         ISD::SETNE);
2860   } else {
2861     // Make desired shift
2862     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2863                                     DAG.getConstant(1, dl, VT), ShiftOp);
2864 
2865     // Emit bit tests and jumps
2866     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2867                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2868     Cmp = DAG.getSetCC(
2869         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2870         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2871   }
2872 
2873   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2874   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2875   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2876   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2877   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2878   // one as they are relative probabilities (and thus work more like weights),
2879   // and hence we need to normalize them to let the sum of them become one.
2880   SwitchBB->normalizeSuccProbs();
2881 
2882   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2883                               MVT::Other, getControlRoot(),
2884                               Cmp, DAG.getBasicBlock(B.TargetBB));
2885 
2886   // Avoid emitting unnecessary branches to the next block.
2887   if (NextMBB != NextBlock(SwitchBB))
2888     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2889                         DAG.getBasicBlock(NextMBB));
2890 
2891   DAG.setRoot(BrAnd);
2892 }
2893 
2894 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2895   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2896 
2897   // Retrieve successors. Look through artificial IR level blocks like
2898   // catchswitch for successors.
2899   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2900   const BasicBlock *EHPadBB = I.getSuccessor(1);
2901 
2902   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2903   // have to do anything here to lower funclet bundles.
2904   assert(!I.hasOperandBundlesOtherThan(
2905              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2906               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2907               LLVMContext::OB_cfguardtarget,
2908               LLVMContext::OB_clang_arc_attachedcall}) &&
2909          "Cannot lower invokes with arbitrary operand bundles yet!");
2910 
2911   const Value *Callee(I.getCalledOperand());
2912   const Function *Fn = dyn_cast<Function>(Callee);
2913   if (isa<InlineAsm>(Callee))
2914     visitInlineAsm(I, EHPadBB);
2915   else if (Fn && Fn->isIntrinsic()) {
2916     switch (Fn->getIntrinsicID()) {
2917     default:
2918       llvm_unreachable("Cannot invoke this intrinsic");
2919     case Intrinsic::donothing:
2920       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2921     case Intrinsic::seh_try_begin:
2922     case Intrinsic::seh_scope_begin:
2923     case Intrinsic::seh_try_end:
2924     case Intrinsic::seh_scope_end:
2925       break;
2926     case Intrinsic::experimental_patchpoint_void:
2927     case Intrinsic::experimental_patchpoint_i64:
2928       visitPatchpoint(I, EHPadBB);
2929       break;
2930     case Intrinsic::experimental_gc_statepoint:
2931       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2932       break;
2933     case Intrinsic::wasm_rethrow: {
2934       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2935       // special because it can be invoked, so we manually lower it to a DAG
2936       // node here.
2937       SmallVector<SDValue, 8> Ops;
2938       Ops.push_back(getRoot()); // inchain
2939       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2940       Ops.push_back(
2941           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2942                                 TLI.getPointerTy(DAG.getDataLayout())));
2943       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2944       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2945       break;
2946     }
2947     }
2948   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2949     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2950     // Eventually we will support lowering the @llvm.experimental.deoptimize
2951     // intrinsic, and right now there are no plans to support other intrinsics
2952     // with deopt state.
2953     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2954   } else {
2955     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2956   }
2957 
2958   // If the value of the invoke is used outside of its defining block, make it
2959   // available as a virtual register.
2960   // We already took care of the exported value for the statepoint instruction
2961   // during call to the LowerStatepoint.
2962   if (!isa<GCStatepointInst>(I)) {
2963     CopyToExportRegsIfNeeded(&I);
2964   }
2965 
2966   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2967   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2968   BranchProbability EHPadBBProb =
2969       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2970           : BranchProbability::getZero();
2971   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2972 
2973   // Update successor info.
2974   addSuccessorWithProb(InvokeMBB, Return);
2975   for (auto &UnwindDest : UnwindDests) {
2976     UnwindDest.first->setIsEHPad();
2977     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2978   }
2979   InvokeMBB->normalizeSuccProbs();
2980 
2981   // Drop into normal successor.
2982   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2983                           DAG.getBasicBlock(Return)));
2984 }
2985 
2986 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2987   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2988 
2989   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2990   // have to do anything here to lower funclet bundles.
2991   assert(!I.hasOperandBundlesOtherThan(
2992              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2993          "Cannot lower callbrs with arbitrary operand bundles yet!");
2994 
2995   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2996   visitInlineAsm(I);
2997   CopyToExportRegsIfNeeded(&I);
2998 
2999   // Retrieve successors.
3000   SmallPtrSet<BasicBlock *, 8> Dests;
3001   Dests.insert(I.getDefaultDest());
3002   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3003 
3004   // Update successor info.
3005   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3006   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3007     BasicBlock *Dest = I.getIndirectDest(i);
3008     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3009     Target->setIsInlineAsmBrIndirectTarget();
3010     Target->setMachineBlockAddressTaken();
3011     // Don't add duplicate machine successors.
3012     if (Dests.insert(Dest).second)
3013       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3014   }
3015   CallBrMBB->normalizeSuccProbs();
3016 
3017   // Drop into default successor.
3018   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3019                           MVT::Other, getControlRoot(),
3020                           DAG.getBasicBlock(Return)));
3021 }
3022 
3023 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3024   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3025 }
3026 
3027 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3028   assert(FuncInfo.MBB->isEHPad() &&
3029          "Call to landingpad not in landing pad!");
3030 
3031   // If there aren't registers to copy the values into (e.g., during SjLj
3032   // exceptions), then don't bother to create these DAG nodes.
3033   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3034   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3035   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3036       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3037     return;
3038 
3039   // If landingpad's return type is token type, we don't create DAG nodes
3040   // for its exception pointer and selector value. The extraction of exception
3041   // pointer or selector value from token type landingpads is not currently
3042   // supported.
3043   if (LP.getType()->isTokenTy())
3044     return;
3045 
3046   SmallVector<EVT, 2> ValueVTs;
3047   SDLoc dl = getCurSDLoc();
3048   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3049   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3050 
3051   // Get the two live-in registers as SDValues. The physregs have already been
3052   // copied into virtual registers.
3053   SDValue Ops[2];
3054   if (FuncInfo.ExceptionPointerVirtReg) {
3055     Ops[0] = DAG.getZExtOrTrunc(
3056         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3057                            FuncInfo.ExceptionPointerVirtReg,
3058                            TLI.getPointerTy(DAG.getDataLayout())),
3059         dl, ValueVTs[0]);
3060   } else {
3061     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3062   }
3063   Ops[1] = DAG.getZExtOrTrunc(
3064       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3065                          FuncInfo.ExceptionSelectorVirtReg,
3066                          TLI.getPointerTy(DAG.getDataLayout())),
3067       dl, ValueVTs[1]);
3068 
3069   // Merge into one.
3070   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3071                             DAG.getVTList(ValueVTs), Ops);
3072   setValue(&LP, Res);
3073 }
3074 
3075 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3076                                            MachineBasicBlock *Last) {
3077   // Update JTCases.
3078   for (JumpTableBlock &JTB : SL->JTCases)
3079     if (JTB.first.HeaderBB == First)
3080       JTB.first.HeaderBB = Last;
3081 
3082   // Update BitTestCases.
3083   for (BitTestBlock &BTB : SL->BitTestCases)
3084     if (BTB.Parent == First)
3085       BTB.Parent = Last;
3086 }
3087 
3088 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3089   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3090 
3091   // Update machine-CFG edges with unique successors.
3092   SmallSet<BasicBlock*, 32> Done;
3093   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3094     BasicBlock *BB = I.getSuccessor(i);
3095     bool Inserted = Done.insert(BB).second;
3096     if (!Inserted)
3097         continue;
3098 
3099     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3100     addSuccessorWithProb(IndirectBrMBB, Succ);
3101   }
3102   IndirectBrMBB->normalizeSuccProbs();
3103 
3104   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3105                           MVT::Other, getControlRoot(),
3106                           getValue(I.getAddress())));
3107 }
3108 
3109 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3110   if (!DAG.getTarget().Options.TrapUnreachable)
3111     return;
3112 
3113   // We may be able to ignore unreachable behind a noreturn call.
3114   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3115     const BasicBlock &BB = *I.getParent();
3116     if (&I != &BB.front()) {
3117       BasicBlock::const_iterator PredI =
3118         std::prev(BasicBlock::const_iterator(&I));
3119       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3120         if (Call->doesNotReturn())
3121           return;
3122       }
3123     }
3124   }
3125 
3126   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3127 }
3128 
3129 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3130   SDNodeFlags Flags;
3131   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3132     Flags.copyFMF(*FPOp);
3133 
3134   SDValue Op = getValue(I.getOperand(0));
3135   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3136                                     Op, Flags);
3137   setValue(&I, UnNodeValue);
3138 }
3139 
3140 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3141   SDNodeFlags Flags;
3142   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3143     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3144     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3145   }
3146   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3147     Flags.setExact(ExactOp->isExact());
3148   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3149     Flags.copyFMF(*FPOp);
3150 
3151   SDValue Op1 = getValue(I.getOperand(0));
3152   SDValue Op2 = getValue(I.getOperand(1));
3153   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3154                                      Op1, Op2, Flags);
3155   setValue(&I, BinNodeValue);
3156 }
3157 
3158 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3159   SDValue Op1 = getValue(I.getOperand(0));
3160   SDValue Op2 = getValue(I.getOperand(1));
3161 
3162   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3163       Op1.getValueType(), DAG.getDataLayout());
3164 
3165   // Coerce the shift amount to the right type if we can. This exposes the
3166   // truncate or zext to optimization early.
3167   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3168     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3169            "Unexpected shift type");
3170     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3171   }
3172 
3173   bool nuw = false;
3174   bool nsw = false;
3175   bool exact = false;
3176 
3177   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3178 
3179     if (const OverflowingBinaryOperator *OFBinOp =
3180             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3181       nuw = OFBinOp->hasNoUnsignedWrap();
3182       nsw = OFBinOp->hasNoSignedWrap();
3183     }
3184     if (const PossiblyExactOperator *ExactOp =
3185             dyn_cast<const PossiblyExactOperator>(&I))
3186       exact = ExactOp->isExact();
3187   }
3188   SDNodeFlags Flags;
3189   Flags.setExact(exact);
3190   Flags.setNoSignedWrap(nsw);
3191   Flags.setNoUnsignedWrap(nuw);
3192   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3193                             Flags);
3194   setValue(&I, Res);
3195 }
3196 
3197 void SelectionDAGBuilder::visitSDiv(const User &I) {
3198   SDValue Op1 = getValue(I.getOperand(0));
3199   SDValue Op2 = getValue(I.getOperand(1));
3200 
3201   SDNodeFlags Flags;
3202   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3203                  cast<PossiblyExactOperator>(&I)->isExact());
3204   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3205                            Op2, Flags));
3206 }
3207 
3208 void SelectionDAGBuilder::visitICmp(const User &I) {
3209   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3210   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3211     predicate = IC->getPredicate();
3212   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3213     predicate = ICmpInst::Predicate(IC->getPredicate());
3214   SDValue Op1 = getValue(I.getOperand(0));
3215   SDValue Op2 = getValue(I.getOperand(1));
3216   ISD::CondCode Opcode = getICmpCondCode(predicate);
3217 
3218   auto &TLI = DAG.getTargetLoweringInfo();
3219   EVT MemVT =
3220       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3221 
3222   // If a pointer's DAG type is larger than its memory type then the DAG values
3223   // are zero-extended. This breaks signed comparisons so truncate back to the
3224   // underlying type before doing the compare.
3225   if (Op1.getValueType() != MemVT) {
3226     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3227     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3228   }
3229 
3230   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3231                                                         I.getType());
3232   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3233 }
3234 
3235 void SelectionDAGBuilder::visitFCmp(const User &I) {
3236   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3237   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3238     predicate = FC->getPredicate();
3239   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3240     predicate = FCmpInst::Predicate(FC->getPredicate());
3241   SDValue Op1 = getValue(I.getOperand(0));
3242   SDValue Op2 = getValue(I.getOperand(1));
3243 
3244   ISD::CondCode Condition = getFCmpCondCode(predicate);
3245   auto *FPMO = cast<FPMathOperator>(&I);
3246   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3247     Condition = getFCmpCodeWithoutNaN(Condition);
3248 
3249   SDNodeFlags Flags;
3250   Flags.copyFMF(*FPMO);
3251   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3252 
3253   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3254                                                         I.getType());
3255   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3256 }
3257 
3258 // Check if the condition of the select has one use or two users that are both
3259 // selects with the same condition.
3260 static bool hasOnlySelectUsers(const Value *Cond) {
3261   return llvm::all_of(Cond->users(), [](const Value *V) {
3262     return isa<SelectInst>(V);
3263   });
3264 }
3265 
3266 void SelectionDAGBuilder::visitSelect(const User &I) {
3267   SmallVector<EVT, 4> ValueVTs;
3268   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3269                   ValueVTs);
3270   unsigned NumValues = ValueVTs.size();
3271   if (NumValues == 0) return;
3272 
3273   SmallVector<SDValue, 4> Values(NumValues);
3274   SDValue Cond     = getValue(I.getOperand(0));
3275   SDValue LHSVal   = getValue(I.getOperand(1));
3276   SDValue RHSVal   = getValue(I.getOperand(2));
3277   SmallVector<SDValue, 1> BaseOps(1, Cond);
3278   ISD::NodeType OpCode =
3279       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3280 
3281   bool IsUnaryAbs = false;
3282   bool Negate = false;
3283 
3284   SDNodeFlags Flags;
3285   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3286     Flags.copyFMF(*FPOp);
3287 
3288   // Min/max matching is only viable if all output VTs are the same.
3289   if (is_splat(ValueVTs)) {
3290     EVT VT = ValueVTs[0];
3291     LLVMContext &Ctx = *DAG.getContext();
3292     auto &TLI = DAG.getTargetLoweringInfo();
3293 
3294     // We care about the legality of the operation after it has been type
3295     // legalized.
3296     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3297       VT = TLI.getTypeToTransformTo(Ctx, VT);
3298 
3299     // If the vselect is legal, assume we want to leave this as a vector setcc +
3300     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3301     // min/max is legal on the scalar type.
3302     bool UseScalarMinMax = VT.isVector() &&
3303       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3304 
3305     Value *LHS, *RHS;
3306     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3307     ISD::NodeType Opc = ISD::DELETED_NODE;
3308     switch (SPR.Flavor) {
3309     case SPF_UMAX:    Opc = ISD::UMAX; break;
3310     case SPF_UMIN:    Opc = ISD::UMIN; break;
3311     case SPF_SMAX:    Opc = ISD::SMAX; break;
3312     case SPF_SMIN:    Opc = ISD::SMIN; break;
3313     case SPF_FMINNUM:
3314       switch (SPR.NaNBehavior) {
3315       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3316       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3317       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3318       case SPNB_RETURNS_ANY: {
3319         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3320           Opc = ISD::FMINNUM;
3321         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3322           Opc = ISD::FMINIMUM;
3323         else if (UseScalarMinMax)
3324           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3325             ISD::FMINNUM : ISD::FMINIMUM;
3326         break;
3327       }
3328       }
3329       break;
3330     case SPF_FMAXNUM:
3331       switch (SPR.NaNBehavior) {
3332       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3333       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3334       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3335       case SPNB_RETURNS_ANY:
3336 
3337         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3338           Opc = ISD::FMAXNUM;
3339         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3340           Opc = ISD::FMAXIMUM;
3341         else if (UseScalarMinMax)
3342           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3343             ISD::FMAXNUM : ISD::FMAXIMUM;
3344         break;
3345       }
3346       break;
3347     case SPF_NABS:
3348       Negate = true;
3349       [[fallthrough]];
3350     case SPF_ABS:
3351       IsUnaryAbs = true;
3352       Opc = ISD::ABS;
3353       break;
3354     default: break;
3355     }
3356 
3357     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3358         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3359          (UseScalarMinMax &&
3360           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3361         // If the underlying comparison instruction is used by any other
3362         // instruction, the consumed instructions won't be destroyed, so it is
3363         // not profitable to convert to a min/max.
3364         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3365       OpCode = Opc;
3366       LHSVal = getValue(LHS);
3367       RHSVal = getValue(RHS);
3368       BaseOps.clear();
3369     }
3370 
3371     if (IsUnaryAbs) {
3372       OpCode = Opc;
3373       LHSVal = getValue(LHS);
3374       BaseOps.clear();
3375     }
3376   }
3377 
3378   if (IsUnaryAbs) {
3379     for (unsigned i = 0; i != NumValues; ++i) {
3380       SDLoc dl = getCurSDLoc();
3381       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3382       Values[i] =
3383           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3384       if (Negate)
3385         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3386                                 Values[i]);
3387     }
3388   } else {
3389     for (unsigned i = 0; i != NumValues; ++i) {
3390       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3391       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3392       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3393       Values[i] = DAG.getNode(
3394           OpCode, getCurSDLoc(),
3395           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3396     }
3397   }
3398 
3399   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3400                            DAG.getVTList(ValueVTs), Values));
3401 }
3402 
3403 void SelectionDAGBuilder::visitTrunc(const User &I) {
3404   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3405   SDValue N = getValue(I.getOperand(0));
3406   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3407                                                         I.getType());
3408   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3409 }
3410 
3411 void SelectionDAGBuilder::visitZExt(const User &I) {
3412   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3413   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3414   SDValue N = getValue(I.getOperand(0));
3415   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3416                                                         I.getType());
3417   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3418 }
3419 
3420 void SelectionDAGBuilder::visitSExt(const User &I) {
3421   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3422   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3423   SDValue N = getValue(I.getOperand(0));
3424   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3425                                                         I.getType());
3426   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3427 }
3428 
3429 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3430   // FPTrunc is never a no-op cast, no need to check
3431   SDValue N = getValue(I.getOperand(0));
3432   SDLoc dl = getCurSDLoc();
3433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3434   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3435   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3436                            DAG.getTargetConstant(
3437                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3438 }
3439 
3440 void SelectionDAGBuilder::visitFPExt(const User &I) {
3441   // FPExt is never a no-op cast, no need to check
3442   SDValue N = getValue(I.getOperand(0));
3443   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3444                                                         I.getType());
3445   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3446 }
3447 
3448 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3449   // FPToUI is never a no-op cast, no need to check
3450   SDValue N = getValue(I.getOperand(0));
3451   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3452                                                         I.getType());
3453   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3454 }
3455 
3456 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3457   // FPToSI is never a no-op cast, no need to check
3458   SDValue N = getValue(I.getOperand(0));
3459   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3460                                                         I.getType());
3461   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3462 }
3463 
3464 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3465   // UIToFP is never a no-op cast, no need to check
3466   SDValue N = getValue(I.getOperand(0));
3467   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3468                                                         I.getType());
3469   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3470 }
3471 
3472 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3473   // SIToFP is never a no-op cast, no need to check
3474   SDValue N = getValue(I.getOperand(0));
3475   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3476                                                         I.getType());
3477   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3478 }
3479 
3480 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3481   // What to do depends on the size of the integer and the size of the pointer.
3482   // We can either truncate, zero extend, or no-op, accordingly.
3483   SDValue N = getValue(I.getOperand(0));
3484   auto &TLI = DAG.getTargetLoweringInfo();
3485   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3486                                                         I.getType());
3487   EVT PtrMemVT =
3488       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3489   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3490   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3491   setValue(&I, N);
3492 }
3493 
3494 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3495   // What to do depends on the size of the integer and the size of the pointer.
3496   // We can either truncate, zero extend, or no-op, accordingly.
3497   SDValue N = getValue(I.getOperand(0));
3498   auto &TLI = DAG.getTargetLoweringInfo();
3499   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3500   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3501   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3502   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3503   setValue(&I, N);
3504 }
3505 
3506 void SelectionDAGBuilder::visitBitCast(const User &I) {
3507   SDValue N = getValue(I.getOperand(0));
3508   SDLoc dl = getCurSDLoc();
3509   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3510                                                         I.getType());
3511 
3512   // BitCast assures us that source and destination are the same size so this is
3513   // either a BITCAST or a no-op.
3514   if (DestVT != N.getValueType())
3515     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3516                              DestVT, N)); // convert types.
3517   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3518   // might fold any kind of constant expression to an integer constant and that
3519   // is not what we are looking for. Only recognize a bitcast of a genuine
3520   // constant integer as an opaque constant.
3521   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3522     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3523                                  /*isOpaque*/true));
3524   else
3525     setValue(&I, N);            // noop cast.
3526 }
3527 
3528 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3530   const Value *SV = I.getOperand(0);
3531   SDValue N = getValue(SV);
3532   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3533 
3534   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3535   unsigned DestAS = I.getType()->getPointerAddressSpace();
3536 
3537   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3538     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3539 
3540   setValue(&I, N);
3541 }
3542 
3543 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3544   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3545   SDValue InVec = getValue(I.getOperand(0));
3546   SDValue InVal = getValue(I.getOperand(1));
3547   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3548                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3549   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3550                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3551                            InVec, InVal, InIdx));
3552 }
3553 
3554 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3556   SDValue InVec = getValue(I.getOperand(0));
3557   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3558                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3559   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3560                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3561                            InVec, InIdx));
3562 }
3563 
3564 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3565   SDValue Src1 = getValue(I.getOperand(0));
3566   SDValue Src2 = getValue(I.getOperand(1));
3567   ArrayRef<int> Mask;
3568   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3569     Mask = SVI->getShuffleMask();
3570   else
3571     Mask = cast<ConstantExpr>(I).getShuffleMask();
3572   SDLoc DL = getCurSDLoc();
3573   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3574   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3575   EVT SrcVT = Src1.getValueType();
3576 
3577   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3578       VT.isScalableVector()) {
3579     // Canonical splat form of first element of first input vector.
3580     SDValue FirstElt =
3581         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3582                     DAG.getVectorIdxConstant(0, DL));
3583     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3584     return;
3585   }
3586 
3587   // For now, we only handle splats for scalable vectors.
3588   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3589   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3590   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3591 
3592   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3593   unsigned MaskNumElts = Mask.size();
3594 
3595   if (SrcNumElts == MaskNumElts) {
3596     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3597     return;
3598   }
3599 
3600   // Normalize the shuffle vector since mask and vector length don't match.
3601   if (SrcNumElts < MaskNumElts) {
3602     // Mask is longer than the source vectors. We can use concatenate vector to
3603     // make the mask and vectors lengths match.
3604 
3605     if (MaskNumElts % SrcNumElts == 0) {
3606       // Mask length is a multiple of the source vector length.
3607       // Check if the shuffle is some kind of concatenation of the input
3608       // vectors.
3609       unsigned NumConcat = MaskNumElts / SrcNumElts;
3610       bool IsConcat = true;
3611       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3612       for (unsigned i = 0; i != MaskNumElts; ++i) {
3613         int Idx = Mask[i];
3614         if (Idx < 0)
3615           continue;
3616         // Ensure the indices in each SrcVT sized piece are sequential and that
3617         // the same source is used for the whole piece.
3618         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3619             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3620              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3621           IsConcat = false;
3622           break;
3623         }
3624         // Remember which source this index came from.
3625         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3626       }
3627 
3628       // The shuffle is concatenating multiple vectors together. Just emit
3629       // a CONCAT_VECTORS operation.
3630       if (IsConcat) {
3631         SmallVector<SDValue, 8> ConcatOps;
3632         for (auto Src : ConcatSrcs) {
3633           if (Src < 0)
3634             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3635           else if (Src == 0)
3636             ConcatOps.push_back(Src1);
3637           else
3638             ConcatOps.push_back(Src2);
3639         }
3640         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3641         return;
3642       }
3643     }
3644 
3645     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3646     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3647     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3648                                     PaddedMaskNumElts);
3649 
3650     // Pad both vectors with undefs to make them the same length as the mask.
3651     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3652 
3653     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3654     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3655     MOps1[0] = Src1;
3656     MOps2[0] = Src2;
3657 
3658     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3659     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3660 
3661     // Readjust mask for new input vector length.
3662     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3663     for (unsigned i = 0; i != MaskNumElts; ++i) {
3664       int Idx = Mask[i];
3665       if (Idx >= (int)SrcNumElts)
3666         Idx -= SrcNumElts - PaddedMaskNumElts;
3667       MappedOps[i] = Idx;
3668     }
3669 
3670     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3671 
3672     // If the concatenated vector was padded, extract a subvector with the
3673     // correct number of elements.
3674     if (MaskNumElts != PaddedMaskNumElts)
3675       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3676                            DAG.getVectorIdxConstant(0, DL));
3677 
3678     setValue(&I, Result);
3679     return;
3680   }
3681 
3682   if (SrcNumElts > MaskNumElts) {
3683     // Analyze the access pattern of the vector to see if we can extract
3684     // two subvectors and do the shuffle.
3685     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3686     bool CanExtract = true;
3687     for (int Idx : Mask) {
3688       unsigned Input = 0;
3689       if (Idx < 0)
3690         continue;
3691 
3692       if (Idx >= (int)SrcNumElts) {
3693         Input = 1;
3694         Idx -= SrcNumElts;
3695       }
3696 
3697       // If all the indices come from the same MaskNumElts sized portion of
3698       // the sources we can use extract. Also make sure the extract wouldn't
3699       // extract past the end of the source.
3700       int NewStartIdx = alignDown(Idx, MaskNumElts);
3701       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3702           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3703         CanExtract = false;
3704       // Make sure we always update StartIdx as we use it to track if all
3705       // elements are undef.
3706       StartIdx[Input] = NewStartIdx;
3707     }
3708 
3709     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3710       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3711       return;
3712     }
3713     if (CanExtract) {
3714       // Extract appropriate subvector and generate a vector shuffle
3715       for (unsigned Input = 0; Input < 2; ++Input) {
3716         SDValue &Src = Input == 0 ? Src1 : Src2;
3717         if (StartIdx[Input] < 0)
3718           Src = DAG.getUNDEF(VT);
3719         else {
3720           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3721                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3722         }
3723       }
3724 
3725       // Calculate new mask.
3726       SmallVector<int, 8> MappedOps(Mask);
3727       for (int &Idx : MappedOps) {
3728         if (Idx >= (int)SrcNumElts)
3729           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3730         else if (Idx >= 0)
3731           Idx -= StartIdx[0];
3732       }
3733 
3734       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3735       return;
3736     }
3737   }
3738 
3739   // We can't use either concat vectors or extract subvectors so fall back to
3740   // replacing the shuffle with extract and build vector.
3741   // to insert and build vector.
3742   EVT EltVT = VT.getVectorElementType();
3743   SmallVector<SDValue,8> Ops;
3744   for (int Idx : Mask) {
3745     SDValue Res;
3746 
3747     if (Idx < 0) {
3748       Res = DAG.getUNDEF(EltVT);
3749     } else {
3750       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3751       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3752 
3753       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3754                         DAG.getVectorIdxConstant(Idx, DL));
3755     }
3756 
3757     Ops.push_back(Res);
3758   }
3759 
3760   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3761 }
3762 
3763 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3764   ArrayRef<unsigned> Indices = I.getIndices();
3765   const Value *Op0 = I.getOperand(0);
3766   const Value *Op1 = I.getOperand(1);
3767   Type *AggTy = I.getType();
3768   Type *ValTy = Op1->getType();
3769   bool IntoUndef = isa<UndefValue>(Op0);
3770   bool FromUndef = isa<UndefValue>(Op1);
3771 
3772   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3773 
3774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3775   SmallVector<EVT, 4> AggValueVTs;
3776   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3777   SmallVector<EVT, 4> ValValueVTs;
3778   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3779 
3780   unsigned NumAggValues = AggValueVTs.size();
3781   unsigned NumValValues = ValValueVTs.size();
3782   SmallVector<SDValue, 4> Values(NumAggValues);
3783 
3784   // Ignore an insertvalue that produces an empty object
3785   if (!NumAggValues) {
3786     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3787     return;
3788   }
3789 
3790   SDValue Agg = getValue(Op0);
3791   unsigned i = 0;
3792   // Copy the beginning value(s) from the original aggregate.
3793   for (; i != LinearIndex; ++i)
3794     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3795                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3796   // Copy values from the inserted value(s).
3797   if (NumValValues) {
3798     SDValue Val = getValue(Op1);
3799     for (; i != LinearIndex + NumValValues; ++i)
3800       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3801                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3802   }
3803   // Copy remaining value(s) from the original aggregate.
3804   for (; i != NumAggValues; ++i)
3805     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3806                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3807 
3808   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3809                            DAG.getVTList(AggValueVTs), Values));
3810 }
3811 
3812 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3813   ArrayRef<unsigned> Indices = I.getIndices();
3814   const Value *Op0 = I.getOperand(0);
3815   Type *AggTy = Op0->getType();
3816   Type *ValTy = I.getType();
3817   bool OutOfUndef = isa<UndefValue>(Op0);
3818 
3819   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3820 
3821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3822   SmallVector<EVT, 4> ValValueVTs;
3823   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3824 
3825   unsigned NumValValues = ValValueVTs.size();
3826 
3827   // Ignore a extractvalue that produces an empty object
3828   if (!NumValValues) {
3829     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3830     return;
3831   }
3832 
3833   SmallVector<SDValue, 4> Values(NumValValues);
3834 
3835   SDValue Agg = getValue(Op0);
3836   // Copy out the selected value(s).
3837   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3838     Values[i - LinearIndex] =
3839       OutOfUndef ?
3840         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3841         SDValue(Agg.getNode(), Agg.getResNo() + i);
3842 
3843   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3844                            DAG.getVTList(ValValueVTs), Values));
3845 }
3846 
3847 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3848   Value *Op0 = I.getOperand(0);
3849   // Note that the pointer operand may be a vector of pointers. Take the scalar
3850   // element which holds a pointer.
3851   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3852   SDValue N = getValue(Op0);
3853   SDLoc dl = getCurSDLoc();
3854   auto &TLI = DAG.getTargetLoweringInfo();
3855 
3856   // Normalize Vector GEP - all scalar operands should be converted to the
3857   // splat vector.
3858   bool IsVectorGEP = I.getType()->isVectorTy();
3859   ElementCount VectorElementCount =
3860       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3861                   : ElementCount::getFixed(0);
3862 
3863   if (IsVectorGEP && !N.getValueType().isVector()) {
3864     LLVMContext &Context = *DAG.getContext();
3865     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3866     if (VectorElementCount.isScalable())
3867       N = DAG.getSplatVector(VT, dl, N);
3868     else
3869       N = DAG.getSplatBuildVector(VT, dl, N);
3870   }
3871 
3872   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3873        GTI != E; ++GTI) {
3874     const Value *Idx = GTI.getOperand();
3875     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3876       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3877       if (Field) {
3878         // N = N + Offset
3879         uint64_t Offset =
3880             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3881 
3882         // In an inbounds GEP with an offset that is nonnegative even when
3883         // interpreted as signed, assume there is no unsigned overflow.
3884         SDNodeFlags Flags;
3885         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3886           Flags.setNoUnsignedWrap(true);
3887 
3888         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3889                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3890       }
3891     } else {
3892       // IdxSize is the width of the arithmetic according to IR semantics.
3893       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3894       // (and fix up the result later).
3895       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3896       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3897       TypeSize ElementSize =
3898           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3899       // We intentionally mask away the high bits here; ElementSize may not
3900       // fit in IdxTy.
3901       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3902       bool ElementScalable = ElementSize.isScalable();
3903 
3904       // If this is a scalar constant or a splat vector of constants,
3905       // handle it quickly.
3906       const auto *C = dyn_cast<Constant>(Idx);
3907       if (C && isa<VectorType>(C->getType()))
3908         C = C->getSplatValue();
3909 
3910       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3911       if (CI && CI->isZero())
3912         continue;
3913       if (CI && !ElementScalable) {
3914         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3915         LLVMContext &Context = *DAG.getContext();
3916         SDValue OffsVal;
3917         if (IsVectorGEP)
3918           OffsVal = DAG.getConstant(
3919               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3920         else
3921           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3922 
3923         // In an inbounds GEP with an offset that is nonnegative even when
3924         // interpreted as signed, assume there is no unsigned overflow.
3925         SDNodeFlags Flags;
3926         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3927           Flags.setNoUnsignedWrap(true);
3928 
3929         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3930 
3931         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3932         continue;
3933       }
3934 
3935       // N = N + Idx * ElementMul;
3936       SDValue IdxN = getValue(Idx);
3937 
3938       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3939         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3940                                   VectorElementCount);
3941         if (VectorElementCount.isScalable())
3942           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3943         else
3944           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3945       }
3946 
3947       // If the index is smaller or larger than intptr_t, truncate or extend
3948       // it.
3949       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3950 
3951       if (ElementScalable) {
3952         EVT VScaleTy = N.getValueType().getScalarType();
3953         SDValue VScale = DAG.getNode(
3954             ISD::VSCALE, dl, VScaleTy,
3955             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3956         if (IsVectorGEP)
3957           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3958         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3959       } else {
3960         // If this is a multiply by a power of two, turn it into a shl
3961         // immediately.  This is a very common case.
3962         if (ElementMul != 1) {
3963           if (ElementMul.isPowerOf2()) {
3964             unsigned Amt = ElementMul.logBase2();
3965             IdxN = DAG.getNode(ISD::SHL, dl,
3966                                N.getValueType(), IdxN,
3967                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3968           } else {
3969             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3970                                             IdxN.getValueType());
3971             IdxN = DAG.getNode(ISD::MUL, dl,
3972                                N.getValueType(), IdxN, Scale);
3973           }
3974         }
3975       }
3976 
3977       N = DAG.getNode(ISD::ADD, dl,
3978                       N.getValueType(), N, IdxN);
3979     }
3980   }
3981 
3982   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3983   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3984   if (IsVectorGEP) {
3985     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3986     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3987   }
3988 
3989   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3990     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3991 
3992   setValue(&I, N);
3993 }
3994 
3995 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3996   // If this is a fixed sized alloca in the entry block of the function,
3997   // allocate it statically on the stack.
3998   if (FuncInfo.StaticAllocaMap.count(&I))
3999     return;   // getValue will auto-populate this.
4000 
4001   SDLoc dl = getCurSDLoc();
4002   Type *Ty = I.getAllocatedType();
4003   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4004   auto &DL = DAG.getDataLayout();
4005   TypeSize TySize = DL.getTypeAllocSize(Ty);
4006   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4007 
4008   SDValue AllocSize = getValue(I.getArraySize());
4009 
4010   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4011   if (AllocSize.getValueType() != IntPtr)
4012     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4013 
4014   if (TySize.isScalable())
4015     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4016                             DAG.getVScale(dl, IntPtr,
4017                                           APInt(IntPtr.getScalarSizeInBits(),
4018                                                 TySize.getKnownMinValue())));
4019   else
4020     AllocSize =
4021         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4022                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4023 
4024   // Handle alignment.  If the requested alignment is less than or equal to
4025   // the stack alignment, ignore it.  If the size is greater than or equal to
4026   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4027   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4028   if (*Alignment <= StackAlign)
4029     Alignment = None;
4030 
4031   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4032   // Round the size of the allocation up to the stack alignment size
4033   // by add SA-1 to the size. This doesn't overflow because we're computing
4034   // an address inside an alloca.
4035   SDNodeFlags Flags;
4036   Flags.setNoUnsignedWrap(true);
4037   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4038                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4039 
4040   // Mask out the low bits for alignment purposes.
4041   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4042                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4043 
4044   SDValue Ops[] = {
4045       getRoot(), AllocSize,
4046       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4047   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4048   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4049   setValue(&I, DSA);
4050   DAG.setRoot(DSA.getValue(1));
4051 
4052   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4053 }
4054 
4055 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4056   if (I.isAtomic())
4057     return visitAtomicLoad(I);
4058 
4059   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4060   const Value *SV = I.getOperand(0);
4061   if (TLI.supportSwiftError()) {
4062     // Swifterror values can come from either a function parameter with
4063     // swifterror attribute or an alloca with swifterror attribute.
4064     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4065       if (Arg->hasSwiftErrorAttr())
4066         return visitLoadFromSwiftError(I);
4067     }
4068 
4069     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4070       if (Alloca->isSwiftError())
4071         return visitLoadFromSwiftError(I);
4072     }
4073   }
4074 
4075   SDValue Ptr = getValue(SV);
4076 
4077   Type *Ty = I.getType();
4078   Align Alignment = I.getAlign();
4079 
4080   AAMDNodes AAInfo = I.getAAMetadata();
4081   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4082 
4083   SmallVector<EVT, 4> ValueVTs, MemVTs;
4084   SmallVector<uint64_t, 4> Offsets;
4085   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4086   unsigned NumValues = ValueVTs.size();
4087   if (NumValues == 0)
4088     return;
4089 
4090   bool isVolatile = I.isVolatile();
4091   MachineMemOperand::Flags MMOFlags =
4092       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4093 
4094   SDValue Root;
4095   bool ConstantMemory = false;
4096   if (isVolatile)
4097     // Serialize volatile loads with other side effects.
4098     Root = getRoot();
4099   else if (NumValues > MaxParallelChains)
4100     Root = getMemoryRoot();
4101   else if (AA &&
4102            AA->pointsToConstantMemory(MemoryLocation(
4103                SV,
4104                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4105                AAInfo))) {
4106     // Do not serialize (non-volatile) loads of constant memory with anything.
4107     Root = DAG.getEntryNode();
4108     ConstantMemory = true;
4109     MMOFlags |= MachineMemOperand::MOInvariant;
4110 
4111     // FIXME: pointsToConstantMemory probably does not imply dereferenceable,
4112     // but the previous usage implied it did. Probably should check
4113     // isDereferenceableAndAlignedPointer.
4114     MMOFlags |= MachineMemOperand::MODereferenceable;
4115   } else {
4116     // Do not serialize non-volatile loads against each other.
4117     Root = DAG.getRoot();
4118   }
4119 
4120   SDLoc dl = getCurSDLoc();
4121 
4122   if (isVolatile)
4123     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4124 
4125   // An aggregate load cannot wrap around the address space, so offsets to its
4126   // parts don't wrap either.
4127   SDNodeFlags Flags;
4128   Flags.setNoUnsignedWrap(true);
4129 
4130   SmallVector<SDValue, 4> Values(NumValues);
4131   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4132   EVT PtrVT = Ptr.getValueType();
4133 
4134   unsigned ChainI = 0;
4135   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4136     // Serializing loads here may result in excessive register pressure, and
4137     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4138     // could recover a bit by hoisting nodes upward in the chain by recognizing
4139     // they are side-effect free or do not alias. The optimizer should really
4140     // avoid this case by converting large object/array copies to llvm.memcpy
4141     // (MaxParallelChains should always remain as failsafe).
4142     if (ChainI == MaxParallelChains) {
4143       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4144       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4145                                   makeArrayRef(Chains.data(), ChainI));
4146       Root = Chain;
4147       ChainI = 0;
4148     }
4149     SDValue A = DAG.getNode(ISD::ADD, dl,
4150                             PtrVT, Ptr,
4151                             DAG.getConstant(Offsets[i], dl, PtrVT),
4152                             Flags);
4153 
4154     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4155                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4156                             MMOFlags, AAInfo, Ranges);
4157     Chains[ChainI] = L.getValue(1);
4158 
4159     if (MemVTs[i] != ValueVTs[i])
4160       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4161 
4162     Values[i] = L;
4163   }
4164 
4165   if (!ConstantMemory) {
4166     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4167                                 makeArrayRef(Chains.data(), ChainI));
4168     if (isVolatile)
4169       DAG.setRoot(Chain);
4170     else
4171       PendingLoads.push_back(Chain);
4172   }
4173 
4174   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4175                            DAG.getVTList(ValueVTs), Values));
4176 }
4177 
4178 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4179   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4180          "call visitStoreToSwiftError when backend supports swifterror");
4181 
4182   SmallVector<EVT, 4> ValueVTs;
4183   SmallVector<uint64_t, 4> Offsets;
4184   const Value *SrcV = I.getOperand(0);
4185   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4186                   SrcV->getType(), ValueVTs, &Offsets);
4187   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4188          "expect a single EVT for swifterror");
4189 
4190   SDValue Src = getValue(SrcV);
4191   // Create a virtual register, then update the virtual register.
4192   Register VReg =
4193       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4194   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4195   // Chain can be getRoot or getControlRoot.
4196   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4197                                       SDValue(Src.getNode(), Src.getResNo()));
4198   DAG.setRoot(CopyNode);
4199 }
4200 
4201 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4202   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4203          "call visitLoadFromSwiftError when backend supports swifterror");
4204 
4205   assert(!I.isVolatile() &&
4206          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4207          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4208          "Support volatile, non temporal, invariant for load_from_swift_error");
4209 
4210   const Value *SV = I.getOperand(0);
4211   Type *Ty = I.getType();
4212   assert(
4213       (!AA ||
4214        !AA->pointsToConstantMemory(MemoryLocation(
4215            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4216            I.getAAMetadata()))) &&
4217       "load_from_swift_error should not be constant memory");
4218 
4219   SmallVector<EVT, 4> ValueVTs;
4220   SmallVector<uint64_t, 4> Offsets;
4221   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4222                   ValueVTs, &Offsets);
4223   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4224          "expect a single EVT for swifterror");
4225 
4226   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4227   SDValue L = DAG.getCopyFromReg(
4228       getRoot(), getCurSDLoc(),
4229       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4230 
4231   setValue(&I, L);
4232 }
4233 
4234 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4235   if (I.isAtomic())
4236     return visitAtomicStore(I);
4237 
4238   const Value *SrcV = I.getOperand(0);
4239   const Value *PtrV = I.getOperand(1);
4240 
4241   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4242   if (TLI.supportSwiftError()) {
4243     // Swifterror values can come from either a function parameter with
4244     // swifterror attribute or an alloca with swifterror attribute.
4245     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4246       if (Arg->hasSwiftErrorAttr())
4247         return visitStoreToSwiftError(I);
4248     }
4249 
4250     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4251       if (Alloca->isSwiftError())
4252         return visitStoreToSwiftError(I);
4253     }
4254   }
4255 
4256   SmallVector<EVT, 4> ValueVTs, MemVTs;
4257   SmallVector<uint64_t, 4> Offsets;
4258   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4259                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4260   unsigned NumValues = ValueVTs.size();
4261   if (NumValues == 0)
4262     return;
4263 
4264   // Get the lowered operands. Note that we do this after
4265   // checking if NumResults is zero, because with zero results
4266   // the operands won't have values in the map.
4267   SDValue Src = getValue(SrcV);
4268   SDValue Ptr = getValue(PtrV);
4269 
4270   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4271   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4272   SDLoc dl = getCurSDLoc();
4273   Align Alignment = I.getAlign();
4274   AAMDNodes AAInfo = I.getAAMetadata();
4275 
4276   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4277 
4278   // An aggregate load cannot wrap around the address space, so offsets to its
4279   // parts don't wrap either.
4280   SDNodeFlags Flags;
4281   Flags.setNoUnsignedWrap(true);
4282 
4283   unsigned ChainI = 0;
4284   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4285     // See visitLoad comments.
4286     if (ChainI == MaxParallelChains) {
4287       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4288                                   makeArrayRef(Chains.data(), ChainI));
4289       Root = Chain;
4290       ChainI = 0;
4291     }
4292     SDValue Add =
4293         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4294     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4295     if (MemVTs[i] != ValueVTs[i])
4296       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4297     SDValue St =
4298         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4299                      Alignment, MMOFlags, AAInfo);
4300     Chains[ChainI] = St;
4301   }
4302 
4303   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4304                                   makeArrayRef(Chains.data(), ChainI));
4305   DAG.setRoot(StoreNode);
4306 }
4307 
4308 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4309                                            bool IsCompressing) {
4310   SDLoc sdl = getCurSDLoc();
4311 
4312   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4313                                MaybeAlign &Alignment) {
4314     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4315     Src0 = I.getArgOperand(0);
4316     Ptr = I.getArgOperand(1);
4317     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4318     Mask = I.getArgOperand(3);
4319   };
4320   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4321                                     MaybeAlign &Alignment) {
4322     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4323     Src0 = I.getArgOperand(0);
4324     Ptr = I.getArgOperand(1);
4325     Mask = I.getArgOperand(2);
4326     Alignment = None;
4327   };
4328 
4329   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4330   MaybeAlign Alignment;
4331   if (IsCompressing)
4332     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4333   else
4334     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4335 
4336   SDValue Ptr = getValue(PtrOperand);
4337   SDValue Src0 = getValue(Src0Operand);
4338   SDValue Mask = getValue(MaskOperand);
4339   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4340 
4341   EVT VT = Src0.getValueType();
4342   if (!Alignment)
4343     Alignment = DAG.getEVTAlign(VT);
4344 
4345   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4346       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4347       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4348   SDValue StoreNode =
4349       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4350                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4351   DAG.setRoot(StoreNode);
4352   setValue(&I, StoreNode);
4353 }
4354 
4355 // Get a uniform base for the Gather/Scatter intrinsic.
4356 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4357 // We try to represent it as a base pointer + vector of indices.
4358 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4359 // The first operand of the GEP may be a single pointer or a vector of pointers
4360 // Example:
4361 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4362 //  or
4363 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4364 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4365 //
4366 // When the first GEP operand is a single pointer - it is the uniform base we
4367 // are looking for. If first operand of the GEP is a splat vector - we
4368 // extract the splat value and use it as a uniform base.
4369 // In all other cases the function returns 'false'.
4370 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4371                            ISD::MemIndexType &IndexType, SDValue &Scale,
4372                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4373                            uint64_t ElemSize) {
4374   SelectionDAG& DAG = SDB->DAG;
4375   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4376   const DataLayout &DL = DAG.getDataLayout();
4377 
4378   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4379 
4380   // Handle splat constant pointer.
4381   if (auto *C = dyn_cast<Constant>(Ptr)) {
4382     C = C->getSplatValue();
4383     if (!C)
4384       return false;
4385 
4386     Base = SDB->getValue(C);
4387 
4388     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4389     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4390     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4391     IndexType = ISD::SIGNED_SCALED;
4392     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4393     return true;
4394   }
4395 
4396   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4397   if (!GEP || GEP->getParent() != CurBB)
4398     return false;
4399 
4400   if (GEP->getNumOperands() != 2)
4401     return false;
4402 
4403   const Value *BasePtr = GEP->getPointerOperand();
4404   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4405 
4406   // Make sure the base is scalar and the index is a vector.
4407   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4408     return false;
4409 
4410   Base = SDB->getValue(BasePtr);
4411   Index = SDB->getValue(IndexVal);
4412   IndexType = ISD::SIGNED_SCALED;
4413 
4414   // MGATHER/MSCATTER are only required to support scaling by one or by the
4415   // element size. Other scales may be produced using target-specific DAG
4416   // combines.
4417   uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4418   if (ScaleVal != ElemSize && ScaleVal != 1)
4419     return false;
4420 
4421   Scale =
4422       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4423   return true;
4424 }
4425 
4426 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4427   SDLoc sdl = getCurSDLoc();
4428 
4429   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4430   const Value *Ptr = I.getArgOperand(1);
4431   SDValue Src0 = getValue(I.getArgOperand(0));
4432   SDValue Mask = getValue(I.getArgOperand(3));
4433   EVT VT = Src0.getValueType();
4434   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4435                         ->getMaybeAlignValue()
4436                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4438 
4439   SDValue Base;
4440   SDValue Index;
4441   ISD::MemIndexType IndexType;
4442   SDValue Scale;
4443   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4444                                     I.getParent(), VT.getScalarStoreSize());
4445 
4446   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4447   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4448       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4449       // TODO: Make MachineMemOperands aware of scalable
4450       // vectors.
4451       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4452   if (!UniformBase) {
4453     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4454     Index = getValue(Ptr);
4455     IndexType = ISD::SIGNED_SCALED;
4456     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4457   }
4458 
4459   EVT IdxVT = Index.getValueType();
4460   EVT EltTy = IdxVT.getVectorElementType();
4461   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4462     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4463     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4464   }
4465 
4466   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4467   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4468                                          Ops, MMO, IndexType, false);
4469   DAG.setRoot(Scatter);
4470   setValue(&I, Scatter);
4471 }
4472 
4473 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4474   SDLoc sdl = getCurSDLoc();
4475 
4476   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4477                               MaybeAlign &Alignment) {
4478     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4479     Ptr = I.getArgOperand(0);
4480     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4481     Mask = I.getArgOperand(2);
4482     Src0 = I.getArgOperand(3);
4483   };
4484   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4485                                  MaybeAlign &Alignment) {
4486     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4487     Ptr = I.getArgOperand(0);
4488     Alignment = None;
4489     Mask = I.getArgOperand(1);
4490     Src0 = I.getArgOperand(2);
4491   };
4492 
4493   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4494   MaybeAlign Alignment;
4495   if (IsExpanding)
4496     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4497   else
4498     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4499 
4500   SDValue Ptr = getValue(PtrOperand);
4501   SDValue Src0 = getValue(Src0Operand);
4502   SDValue Mask = getValue(MaskOperand);
4503   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4504 
4505   EVT VT = Src0.getValueType();
4506   if (!Alignment)
4507     Alignment = DAG.getEVTAlign(VT);
4508 
4509   AAMDNodes AAInfo = I.getAAMetadata();
4510   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4511 
4512   // Do not serialize masked loads of constant memory with anything.
4513   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4514   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4515 
4516   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4517 
4518   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4519       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4520       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4521 
4522   SDValue Load =
4523       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4524                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4525   if (AddToChain)
4526     PendingLoads.push_back(Load.getValue(1));
4527   setValue(&I, Load);
4528 }
4529 
4530 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4531   SDLoc sdl = getCurSDLoc();
4532 
4533   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4534   const Value *Ptr = I.getArgOperand(0);
4535   SDValue Src0 = getValue(I.getArgOperand(3));
4536   SDValue Mask = getValue(I.getArgOperand(2));
4537 
4538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4539   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4540   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4541                         ->getMaybeAlignValue()
4542                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4543 
4544   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4545 
4546   SDValue Root = DAG.getRoot();
4547   SDValue Base;
4548   SDValue Index;
4549   ISD::MemIndexType IndexType;
4550   SDValue Scale;
4551   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4552                                     I.getParent(), VT.getScalarStoreSize());
4553   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4554   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4555       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4556       // TODO: Make MachineMemOperands aware of scalable
4557       // vectors.
4558       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4559 
4560   if (!UniformBase) {
4561     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4562     Index = getValue(Ptr);
4563     IndexType = ISD::SIGNED_SCALED;
4564     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4565   }
4566 
4567   EVT IdxVT = Index.getValueType();
4568   EVT EltTy = IdxVT.getVectorElementType();
4569   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4570     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4571     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4572   }
4573 
4574   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4575   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4576                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4577 
4578   PendingLoads.push_back(Gather.getValue(1));
4579   setValue(&I, Gather);
4580 }
4581 
4582 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4583   SDLoc dl = getCurSDLoc();
4584   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4585   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4586   SyncScope::ID SSID = I.getSyncScopeID();
4587 
4588   SDValue InChain = getRoot();
4589 
4590   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4591   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4592 
4593   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4594   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4595 
4596   MachineFunction &MF = DAG.getMachineFunction();
4597   MachineMemOperand *MMO = MF.getMachineMemOperand(
4598       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4599       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4600       FailureOrdering);
4601 
4602   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4603                                    dl, MemVT, VTs, InChain,
4604                                    getValue(I.getPointerOperand()),
4605                                    getValue(I.getCompareOperand()),
4606                                    getValue(I.getNewValOperand()), MMO);
4607 
4608   SDValue OutChain = L.getValue(2);
4609 
4610   setValue(&I, L);
4611   DAG.setRoot(OutChain);
4612 }
4613 
4614 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4615   SDLoc dl = getCurSDLoc();
4616   ISD::NodeType NT;
4617   switch (I.getOperation()) {
4618   default: llvm_unreachable("Unknown atomicrmw operation");
4619   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4620   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4621   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4622   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4623   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4624   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4625   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4626   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4627   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4628   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4629   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4630   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4631   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4632   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4633   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4634   }
4635   AtomicOrdering Ordering = I.getOrdering();
4636   SyncScope::ID SSID = I.getSyncScopeID();
4637 
4638   SDValue InChain = getRoot();
4639 
4640   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4641   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4642   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4643 
4644   MachineFunction &MF = DAG.getMachineFunction();
4645   MachineMemOperand *MMO = MF.getMachineMemOperand(
4646       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4647       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4648 
4649   SDValue L =
4650     DAG.getAtomic(NT, dl, MemVT, InChain,
4651                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4652                   MMO);
4653 
4654   SDValue OutChain = L.getValue(1);
4655 
4656   setValue(&I, L);
4657   DAG.setRoot(OutChain);
4658 }
4659 
4660 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4661   SDLoc dl = getCurSDLoc();
4662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4663   SDValue Ops[3];
4664   Ops[0] = getRoot();
4665   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4666                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4667   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4668                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4669   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4670 }
4671 
4672 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4673   SDLoc dl = getCurSDLoc();
4674   AtomicOrdering Order = I.getOrdering();
4675   SyncScope::ID SSID = I.getSyncScopeID();
4676 
4677   SDValue InChain = getRoot();
4678 
4679   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4680   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4681   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4682 
4683   if (!TLI.supportsUnalignedAtomics() &&
4684       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4685     report_fatal_error("Cannot generate unaligned atomic load");
4686 
4687   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4688 
4689   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4690       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4691       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4692 
4693   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4694 
4695   SDValue Ptr = getValue(I.getPointerOperand());
4696 
4697   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4698     // TODO: Once this is better exercised by tests, it should be merged with
4699     // the normal path for loads to prevent future divergence.
4700     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4701     if (MemVT != VT)
4702       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4703 
4704     setValue(&I, L);
4705     SDValue OutChain = L.getValue(1);
4706     if (!I.isUnordered())
4707       DAG.setRoot(OutChain);
4708     else
4709       PendingLoads.push_back(OutChain);
4710     return;
4711   }
4712 
4713   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4714                             Ptr, MMO);
4715 
4716   SDValue OutChain = L.getValue(1);
4717   if (MemVT != VT)
4718     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4719 
4720   setValue(&I, L);
4721   DAG.setRoot(OutChain);
4722 }
4723 
4724 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4725   SDLoc dl = getCurSDLoc();
4726 
4727   AtomicOrdering Ordering = I.getOrdering();
4728   SyncScope::ID SSID = I.getSyncScopeID();
4729 
4730   SDValue InChain = getRoot();
4731 
4732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4733   EVT MemVT =
4734       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4735 
4736   if (!TLI.supportsUnalignedAtomics() &&
4737       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4738     report_fatal_error("Cannot generate unaligned atomic store");
4739 
4740   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4741 
4742   MachineFunction &MF = DAG.getMachineFunction();
4743   MachineMemOperand *MMO = MF.getMachineMemOperand(
4744       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4745       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4746 
4747   SDValue Val = getValue(I.getValueOperand());
4748   if (Val.getValueType() != MemVT)
4749     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4750   SDValue Ptr = getValue(I.getPointerOperand());
4751 
4752   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4753     // TODO: Once this is better exercised by tests, it should be merged with
4754     // the normal path for stores to prevent future divergence.
4755     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4756     DAG.setRoot(S);
4757     return;
4758   }
4759   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4760                                    Ptr, Val, MMO);
4761 
4762 
4763   DAG.setRoot(OutChain);
4764 }
4765 
4766 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4767 /// node.
4768 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4769                                                unsigned Intrinsic) {
4770   // Ignore the callsite's attributes. A specific call site may be marked with
4771   // readnone, but the lowering code will expect the chain based on the
4772   // definition.
4773   const Function *F = I.getCalledFunction();
4774   bool HasChain = !F->doesNotAccessMemory();
4775   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4776 
4777   // Build the operand list.
4778   SmallVector<SDValue, 8> Ops;
4779   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4780     if (OnlyLoad) {
4781       // We don't need to serialize loads against other loads.
4782       Ops.push_back(DAG.getRoot());
4783     } else {
4784       Ops.push_back(getRoot());
4785     }
4786   }
4787 
4788   // Info is set by getTgtMemIntrinsic
4789   TargetLowering::IntrinsicInfo Info;
4790   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4791   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4792                                                DAG.getMachineFunction(),
4793                                                Intrinsic);
4794 
4795   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4796   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4797       Info.opc == ISD::INTRINSIC_W_CHAIN)
4798     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4799                                         TLI.getPointerTy(DAG.getDataLayout())));
4800 
4801   // Add all operands of the call to the operand list.
4802   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4803     const Value *Arg = I.getArgOperand(i);
4804     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4805       Ops.push_back(getValue(Arg));
4806       continue;
4807     }
4808 
4809     // Use TargetConstant instead of a regular constant for immarg.
4810     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4811     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4812       assert(CI->getBitWidth() <= 64 &&
4813              "large intrinsic immediates not handled");
4814       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4815     } else {
4816       Ops.push_back(
4817           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4818     }
4819   }
4820 
4821   SmallVector<EVT, 4> ValueVTs;
4822   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4823 
4824   if (HasChain)
4825     ValueVTs.push_back(MVT::Other);
4826 
4827   SDVTList VTs = DAG.getVTList(ValueVTs);
4828 
4829   // Propagate fast-math-flags from IR to node(s).
4830   SDNodeFlags Flags;
4831   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4832     Flags.copyFMF(*FPMO);
4833   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4834 
4835   // Create the node.
4836   SDValue Result;
4837   if (IsTgtIntrinsic) {
4838     // This is target intrinsic that touches memory
4839     Result =
4840         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4841                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4842                                 Info.align, Info.flags, Info.size,
4843                                 I.getAAMetadata());
4844   } else if (!HasChain) {
4845     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4846   } else if (!I.getType()->isVoidTy()) {
4847     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4848   } else {
4849     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4850   }
4851 
4852   if (HasChain) {
4853     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4854     if (OnlyLoad)
4855       PendingLoads.push_back(Chain);
4856     else
4857       DAG.setRoot(Chain);
4858   }
4859 
4860   if (!I.getType()->isVoidTy()) {
4861     if (!isa<VectorType>(I.getType()))
4862       Result = lowerRangeToAssertZExt(DAG, I, Result);
4863 
4864     MaybeAlign Alignment = I.getRetAlign();
4865     if (!Alignment)
4866       Alignment = F->getAttributes().getRetAlignment();
4867     // Insert `assertalign` node if there's an alignment.
4868     if (InsertAssertAlign && Alignment) {
4869       Result =
4870           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4871     }
4872 
4873     setValue(&I, Result);
4874   }
4875 }
4876 
4877 /// GetSignificand - Get the significand and build it into a floating-point
4878 /// number with exponent of 1:
4879 ///
4880 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4881 ///
4882 /// where Op is the hexadecimal representation of floating point value.
4883 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4884   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4885                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4886   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4887                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4888   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4889 }
4890 
4891 /// GetExponent - Get the exponent:
4892 ///
4893 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4894 ///
4895 /// where Op is the hexadecimal representation of floating point value.
4896 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4897                            const TargetLowering &TLI, const SDLoc &dl) {
4898   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4899                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4900   SDValue t1 = DAG.getNode(
4901       ISD::SRL, dl, MVT::i32, t0,
4902       DAG.getConstant(23, dl,
4903                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4904   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4905                            DAG.getConstant(127, dl, MVT::i32));
4906   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4907 }
4908 
4909 /// getF32Constant - Get 32-bit floating point constant.
4910 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4911                               const SDLoc &dl) {
4912   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4913                            MVT::f32);
4914 }
4915 
4916 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4917                                        SelectionDAG &DAG) {
4918   // TODO: What fast-math-flags should be set on the floating-point nodes?
4919 
4920   //   IntegerPartOfX = ((int32_t)(t0);
4921   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4922 
4923   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4924   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4925   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4926 
4927   //   IntegerPartOfX <<= 23;
4928   IntegerPartOfX =
4929       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4930                   DAG.getConstant(23, dl,
4931                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
4932                                       MVT::i32, DAG.getDataLayout())));
4933 
4934   SDValue TwoToFractionalPartOfX;
4935   if (LimitFloatPrecision <= 6) {
4936     // For floating-point precision of 6:
4937     //
4938     //   TwoToFractionalPartOfX =
4939     //     0.997535578f +
4940     //       (0.735607626f + 0.252464424f * x) * x;
4941     //
4942     // error 0.0144103317, which is 6 bits
4943     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4944                              getF32Constant(DAG, 0x3e814304, dl));
4945     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4946                              getF32Constant(DAG, 0x3f3c50c8, dl));
4947     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4948     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4949                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4950   } else if (LimitFloatPrecision <= 12) {
4951     // For floating-point precision of 12:
4952     //
4953     //   TwoToFractionalPartOfX =
4954     //     0.999892986f +
4955     //       (0.696457318f +
4956     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4957     //
4958     // error 0.000107046256, which is 13 to 14 bits
4959     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4960                              getF32Constant(DAG, 0x3da235e3, dl));
4961     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4962                              getF32Constant(DAG, 0x3e65b8f3, dl));
4963     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4964     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4965                              getF32Constant(DAG, 0x3f324b07, dl));
4966     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4967     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4968                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4969   } else { // LimitFloatPrecision <= 18
4970     // For floating-point precision of 18:
4971     //
4972     //   TwoToFractionalPartOfX =
4973     //     0.999999982f +
4974     //       (0.693148872f +
4975     //         (0.240227044f +
4976     //           (0.554906021e-1f +
4977     //             (0.961591928e-2f +
4978     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4979     // error 2.47208000*10^(-7), which is better than 18 bits
4980     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4981                              getF32Constant(DAG, 0x3924b03e, dl));
4982     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4983                              getF32Constant(DAG, 0x3ab24b87, dl));
4984     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4985     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4986                              getF32Constant(DAG, 0x3c1d8c17, dl));
4987     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4988     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4989                              getF32Constant(DAG, 0x3d634a1d, dl));
4990     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4991     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4992                              getF32Constant(DAG, 0x3e75fe14, dl));
4993     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4994     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4995                               getF32Constant(DAG, 0x3f317234, dl));
4996     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4997     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4998                                          getF32Constant(DAG, 0x3f800000, dl));
4999   }
5000 
5001   // Add the exponent into the result in integer domain.
5002   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5003   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5004                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5005 }
5006 
5007 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5008 /// limited-precision mode.
5009 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5010                          const TargetLowering &TLI, SDNodeFlags Flags) {
5011   if (Op.getValueType() == MVT::f32 &&
5012       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5013 
5014     // Put the exponent in the right bit position for later addition to the
5015     // final result:
5016     //
5017     // t0 = Op * log2(e)
5018 
5019     // TODO: What fast-math-flags should be set here?
5020     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5021                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5022     return getLimitedPrecisionExp2(t0, dl, DAG);
5023   }
5024 
5025   // No special expansion.
5026   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5027 }
5028 
5029 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5030 /// limited-precision mode.
5031 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5032                          const TargetLowering &TLI, SDNodeFlags Flags) {
5033   // TODO: What fast-math-flags should be set on the floating-point nodes?
5034 
5035   if (Op.getValueType() == MVT::f32 &&
5036       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5037     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5038 
5039     // Scale the exponent by log(2).
5040     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5041     SDValue LogOfExponent =
5042         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5043                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5044 
5045     // Get the significand and build it into a floating-point number with
5046     // exponent of 1.
5047     SDValue X = GetSignificand(DAG, Op1, dl);
5048 
5049     SDValue LogOfMantissa;
5050     if (LimitFloatPrecision <= 6) {
5051       // For floating-point precision of 6:
5052       //
5053       //   LogofMantissa =
5054       //     -1.1609546f +
5055       //       (1.4034025f - 0.23903021f * x) * x;
5056       //
5057       // error 0.0034276066, which is better than 8 bits
5058       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5059                                getF32Constant(DAG, 0xbe74c456, dl));
5060       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5061                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5062       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5063       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5064                                   getF32Constant(DAG, 0x3f949a29, dl));
5065     } else if (LimitFloatPrecision <= 12) {
5066       // For floating-point precision of 12:
5067       //
5068       //   LogOfMantissa =
5069       //     -1.7417939f +
5070       //       (2.8212026f +
5071       //         (-1.4699568f +
5072       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5073       //
5074       // error 0.000061011436, which is 14 bits
5075       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5076                                getF32Constant(DAG, 0xbd67b6d6, dl));
5077       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5078                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5079       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5080       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5081                                getF32Constant(DAG, 0x3fbc278b, dl));
5082       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5083       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5084                                getF32Constant(DAG, 0x40348e95, dl));
5085       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5086       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5087                                   getF32Constant(DAG, 0x3fdef31a, dl));
5088     } else { // LimitFloatPrecision <= 18
5089       // For floating-point precision of 18:
5090       //
5091       //   LogOfMantissa =
5092       //     -2.1072184f +
5093       //       (4.2372794f +
5094       //         (-3.7029485f +
5095       //           (2.2781945f +
5096       //             (-0.87823314f +
5097       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5098       //
5099       // error 0.0000023660568, which is better than 18 bits
5100       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5101                                getF32Constant(DAG, 0xbc91e5ac, dl));
5102       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5103                                getF32Constant(DAG, 0x3e4350aa, dl));
5104       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5105       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5106                                getF32Constant(DAG, 0x3f60d3e3, dl));
5107       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5108       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5109                                getF32Constant(DAG, 0x4011cdf0, dl));
5110       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5111       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5112                                getF32Constant(DAG, 0x406cfd1c, dl));
5113       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5114       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5115                                getF32Constant(DAG, 0x408797cb, dl));
5116       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5117       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5118                                   getF32Constant(DAG, 0x4006dcab, dl));
5119     }
5120 
5121     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5122   }
5123 
5124   // No special expansion.
5125   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5126 }
5127 
5128 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5129 /// limited-precision mode.
5130 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5131                           const TargetLowering &TLI, SDNodeFlags Flags) {
5132   // TODO: What fast-math-flags should be set on the floating-point nodes?
5133 
5134   if (Op.getValueType() == MVT::f32 &&
5135       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5136     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5137 
5138     // Get the exponent.
5139     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5140 
5141     // Get the significand and build it into a floating-point number with
5142     // exponent of 1.
5143     SDValue X = GetSignificand(DAG, Op1, dl);
5144 
5145     // Different possible minimax approximations of significand in
5146     // floating-point for various degrees of accuracy over [1,2].
5147     SDValue Log2ofMantissa;
5148     if (LimitFloatPrecision <= 6) {
5149       // For floating-point precision of 6:
5150       //
5151       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5152       //
5153       // error 0.0049451742, which is more than 7 bits
5154       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5155                                getF32Constant(DAG, 0xbeb08fe0, dl));
5156       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5157                                getF32Constant(DAG, 0x40019463, dl));
5158       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5159       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5160                                    getF32Constant(DAG, 0x3fd6633d, dl));
5161     } else if (LimitFloatPrecision <= 12) {
5162       // For floating-point precision of 12:
5163       //
5164       //   Log2ofMantissa =
5165       //     -2.51285454f +
5166       //       (4.07009056f +
5167       //         (-2.12067489f +
5168       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5169       //
5170       // error 0.0000876136000, which is better than 13 bits
5171       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5172                                getF32Constant(DAG, 0xbda7262e, dl));
5173       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5174                                getF32Constant(DAG, 0x3f25280b, dl));
5175       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5176       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5177                                getF32Constant(DAG, 0x4007b923, dl));
5178       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5179       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5180                                getF32Constant(DAG, 0x40823e2f, dl));
5181       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5182       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5183                                    getF32Constant(DAG, 0x4020d29c, dl));
5184     } else { // LimitFloatPrecision <= 18
5185       // For floating-point precision of 18:
5186       //
5187       //   Log2ofMantissa =
5188       //     -3.0400495f +
5189       //       (6.1129976f +
5190       //         (-5.3420409f +
5191       //           (3.2865683f +
5192       //             (-1.2669343f +
5193       //               (0.27515199f -
5194       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5195       //
5196       // error 0.0000018516, which is better than 18 bits
5197       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5198                                getF32Constant(DAG, 0xbcd2769e, dl));
5199       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5200                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5201       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5202       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5203                                getF32Constant(DAG, 0x3fa22ae7, dl));
5204       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5205       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5206                                getF32Constant(DAG, 0x40525723, dl));
5207       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5208       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5209                                getF32Constant(DAG, 0x40aaf200, dl));
5210       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5211       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5212                                getF32Constant(DAG, 0x40c39dad, dl));
5213       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5214       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5215                                    getF32Constant(DAG, 0x4042902c, dl));
5216     }
5217 
5218     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5219   }
5220 
5221   // No special expansion.
5222   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5223 }
5224 
5225 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5226 /// limited-precision mode.
5227 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5228                            const TargetLowering &TLI, SDNodeFlags Flags) {
5229   // TODO: What fast-math-flags should be set on the floating-point nodes?
5230 
5231   if (Op.getValueType() == MVT::f32 &&
5232       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5233     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5234 
5235     // Scale the exponent by log10(2) [0.30102999f].
5236     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5237     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5238                                         getF32Constant(DAG, 0x3e9a209a, dl));
5239 
5240     // Get the significand and build it into a floating-point number with
5241     // exponent of 1.
5242     SDValue X = GetSignificand(DAG, Op1, dl);
5243 
5244     SDValue Log10ofMantissa;
5245     if (LimitFloatPrecision <= 6) {
5246       // For floating-point precision of 6:
5247       //
5248       //   Log10ofMantissa =
5249       //     -0.50419619f +
5250       //       (0.60948995f - 0.10380950f * x) * x;
5251       //
5252       // error 0.0014886165, which is 6 bits
5253       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5254                                getF32Constant(DAG, 0xbdd49a13, dl));
5255       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5256                                getF32Constant(DAG, 0x3f1c0789, dl));
5257       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5258       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5259                                     getF32Constant(DAG, 0x3f011300, dl));
5260     } else if (LimitFloatPrecision <= 12) {
5261       // For floating-point precision of 12:
5262       //
5263       //   Log10ofMantissa =
5264       //     -0.64831180f +
5265       //       (0.91751397f +
5266       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5267       //
5268       // error 0.00019228036, which is better than 12 bits
5269       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5270                                getF32Constant(DAG, 0x3d431f31, dl));
5271       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5272                                getF32Constant(DAG, 0x3ea21fb2, dl));
5273       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5274       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5275                                getF32Constant(DAG, 0x3f6ae232, dl));
5276       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5277       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5278                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5279     } else { // LimitFloatPrecision <= 18
5280       // For floating-point precision of 18:
5281       //
5282       //   Log10ofMantissa =
5283       //     -0.84299375f +
5284       //       (1.5327582f +
5285       //         (-1.0688956f +
5286       //           (0.49102474f +
5287       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5288       //
5289       // error 0.0000037995730, which is better than 18 bits
5290       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5291                                getF32Constant(DAG, 0x3c5d51ce, dl));
5292       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5293                                getF32Constant(DAG, 0x3e00685a, dl));
5294       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5295       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5296                                getF32Constant(DAG, 0x3efb6798, dl));
5297       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5298       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5299                                getF32Constant(DAG, 0x3f88d192, dl));
5300       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5301       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5302                                getF32Constant(DAG, 0x3fc4316c, dl));
5303       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5304       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5305                                     getF32Constant(DAG, 0x3f57ce70, dl));
5306     }
5307 
5308     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5309   }
5310 
5311   // No special expansion.
5312   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5313 }
5314 
5315 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5316 /// limited-precision mode.
5317 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5318                           const TargetLowering &TLI, SDNodeFlags Flags) {
5319   if (Op.getValueType() == MVT::f32 &&
5320       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5321     return getLimitedPrecisionExp2(Op, dl, DAG);
5322 
5323   // No special expansion.
5324   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5325 }
5326 
5327 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5328 /// limited-precision mode with x == 10.0f.
5329 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5330                          SelectionDAG &DAG, const TargetLowering &TLI,
5331                          SDNodeFlags Flags) {
5332   bool IsExp10 = false;
5333   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5334       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5335     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5336       APFloat Ten(10.0f);
5337       IsExp10 = LHSC->isExactlyValue(Ten);
5338     }
5339   }
5340 
5341   // TODO: What fast-math-flags should be set on the FMUL node?
5342   if (IsExp10) {
5343     // Put the exponent in the right bit position for later addition to the
5344     // final result:
5345     //
5346     //   #define LOG2OF10 3.3219281f
5347     //   t0 = Op * LOG2OF10;
5348     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5349                              getF32Constant(DAG, 0x40549a78, dl));
5350     return getLimitedPrecisionExp2(t0, dl, DAG);
5351   }
5352 
5353   // No special expansion.
5354   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5355 }
5356 
5357 /// ExpandPowI - Expand a llvm.powi intrinsic.
5358 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5359                           SelectionDAG &DAG) {
5360   // If RHS is a constant, we can expand this out to a multiplication tree if
5361   // it's beneficial on the target, otherwise we end up lowering to a call to
5362   // __powidf2 (for example).
5363   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5364     unsigned Val = RHSC->getSExtValue();
5365 
5366     // powi(x, 0) -> 1.0
5367     if (Val == 0)
5368       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5369 
5370     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5371             Val, DAG.shouldOptForSize())) {
5372       // Get the exponent as a positive value.
5373       if ((int)Val < 0)
5374         Val = -Val;
5375       // We use the simple binary decomposition method to generate the multiply
5376       // sequence.  There are more optimal ways to do this (for example,
5377       // powi(x,15) generates one more multiply than it should), but this has
5378       // the benefit of being both really simple and much better than a libcall.
5379       SDValue Res; // Logically starts equal to 1.0
5380       SDValue CurSquare = LHS;
5381       // TODO: Intrinsics should have fast-math-flags that propagate to these
5382       // nodes.
5383       while (Val) {
5384         if (Val & 1) {
5385           if (Res.getNode())
5386             Res =
5387                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5388           else
5389             Res = CurSquare; // 1.0*CurSquare.
5390         }
5391 
5392         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5393                                 CurSquare, CurSquare);
5394         Val >>= 1;
5395       }
5396 
5397       // If the original was negative, invert the result, producing 1/(x*x*x).
5398       if (RHSC->getSExtValue() < 0)
5399         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5400                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5401       return Res;
5402     }
5403   }
5404 
5405   // Otherwise, expand to a libcall.
5406   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5407 }
5408 
5409 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5410                             SDValue LHS, SDValue RHS, SDValue Scale,
5411                             SelectionDAG &DAG, const TargetLowering &TLI) {
5412   EVT VT = LHS.getValueType();
5413   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5414   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5415   LLVMContext &Ctx = *DAG.getContext();
5416 
5417   // If the type is legal but the operation isn't, this node might survive all
5418   // the way to operation legalization. If we end up there and we do not have
5419   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5420   // node.
5421 
5422   // Coax the legalizer into expanding the node during type legalization instead
5423   // by bumping the size by one bit. This will force it to Promote, enabling the
5424   // early expansion and avoiding the need to expand later.
5425 
5426   // We don't have to do this if Scale is 0; that can always be expanded, unless
5427   // it's a saturating signed operation. Those can experience true integer
5428   // division overflow, a case which we must avoid.
5429 
5430   // FIXME: We wouldn't have to do this (or any of the early
5431   // expansion/promotion) if it was possible to expand a libcall of an
5432   // illegal type during operation legalization. But it's not, so things
5433   // get a bit hacky.
5434   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5435   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5436       (TLI.isTypeLegal(VT) ||
5437        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5438     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5439         Opcode, VT, ScaleInt);
5440     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5441       EVT PromVT;
5442       if (VT.isScalarInteger())
5443         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5444       else if (VT.isVector()) {
5445         PromVT = VT.getVectorElementType();
5446         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5447         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5448       } else
5449         llvm_unreachable("Wrong VT for DIVFIX?");
5450       if (Signed) {
5451         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5452         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5453       } else {
5454         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5455         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5456       }
5457       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5458       // For saturating operations, we need to shift up the LHS to get the
5459       // proper saturation width, and then shift down again afterwards.
5460       if (Saturating)
5461         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5462                           DAG.getConstant(1, DL, ShiftTy));
5463       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5464       if (Saturating)
5465         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5466                           DAG.getConstant(1, DL, ShiftTy));
5467       return DAG.getZExtOrTrunc(Res, DL, VT);
5468     }
5469   }
5470 
5471   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5472 }
5473 
5474 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5475 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5476 static void
5477 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5478                      const SDValue &N) {
5479   switch (N.getOpcode()) {
5480   case ISD::CopyFromReg: {
5481     SDValue Op = N.getOperand(1);
5482     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5483                       Op.getValueType().getSizeInBits());
5484     return;
5485   }
5486   case ISD::BITCAST:
5487   case ISD::AssertZext:
5488   case ISD::AssertSext:
5489   case ISD::TRUNCATE:
5490     getUnderlyingArgRegs(Regs, N.getOperand(0));
5491     return;
5492   case ISD::BUILD_PAIR:
5493   case ISD::BUILD_VECTOR:
5494   case ISD::CONCAT_VECTORS:
5495     for (SDValue Op : N->op_values())
5496       getUnderlyingArgRegs(Regs, Op);
5497     return;
5498   default:
5499     return;
5500   }
5501 }
5502 
5503 /// If the DbgValueInst is a dbg_value of a function argument, create the
5504 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5505 /// instruction selection, they will be inserted to the entry BB.
5506 /// We don't currently support this for variadic dbg_values, as they shouldn't
5507 /// appear for function arguments or in the prologue.
5508 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5509     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5510     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5511   const Argument *Arg = dyn_cast<Argument>(V);
5512   if (!Arg)
5513     return false;
5514 
5515   MachineFunction &MF = DAG.getMachineFunction();
5516   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5517 
5518   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5519   // we've been asked to pursue.
5520   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5521                               bool Indirect) {
5522     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5523       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5524       // pointing at the VReg, which will be patched up later.
5525       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5526       auto MIB = BuildMI(MF, DL, Inst);
5527       MIB.addReg(Reg);
5528       MIB.addImm(0);
5529       MIB.addMetadata(Variable);
5530       auto *NewDIExpr = FragExpr;
5531       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5532       // the DIExpression.
5533       if (Indirect)
5534         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5535       MIB.addMetadata(NewDIExpr);
5536       return MIB;
5537     } else {
5538       // Create a completely standard DBG_VALUE.
5539       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5540       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5541     }
5542   };
5543 
5544   if (Kind == FuncArgumentDbgValueKind::Value) {
5545     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5546     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5547     // the entry block.
5548     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5549     if (!IsInEntryBlock)
5550       return false;
5551 
5552     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5553     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5554     // variable that also is a param.
5555     //
5556     // Although, if we are at the top of the entry block already, we can still
5557     // emit using ArgDbgValue. This might catch some situations when the
5558     // dbg.value refers to an argument that isn't used in the entry block, so
5559     // any CopyToReg node would be optimized out and the only way to express
5560     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5561     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5562     // we should only emit as ArgDbgValue if the Variable is an argument to the
5563     // current function, and the dbg.value intrinsic is found in the entry
5564     // block.
5565     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5566         !DL->getInlinedAt();
5567     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5568     if (!IsInPrologue && !VariableIsFunctionInputArg)
5569       return false;
5570 
5571     // Here we assume that a function argument on IR level only can be used to
5572     // describe one input parameter on source level. If we for example have
5573     // source code like this
5574     //
5575     //    struct A { long x, y; };
5576     //    void foo(struct A a, long b) {
5577     //      ...
5578     //      b = a.x;
5579     //      ...
5580     //    }
5581     //
5582     // and IR like this
5583     //
5584     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5585     //  entry:
5586     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5587     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5588     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5589     //    ...
5590     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5591     //    ...
5592     //
5593     // then the last dbg.value is describing a parameter "b" using a value that
5594     // is an argument. But since we already has used %a1 to describe a parameter
5595     // we should not handle that last dbg.value here (that would result in an
5596     // incorrect hoisting of the DBG_VALUE to the function entry).
5597     // Notice that we allow one dbg.value per IR level argument, to accommodate
5598     // for the situation with fragments above.
5599     if (VariableIsFunctionInputArg) {
5600       unsigned ArgNo = Arg->getArgNo();
5601       if (ArgNo >= FuncInfo.DescribedArgs.size())
5602         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5603       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5604         return false;
5605       FuncInfo.DescribedArgs.set(ArgNo);
5606     }
5607   }
5608 
5609   bool IsIndirect = false;
5610   Optional<MachineOperand> Op;
5611   // Some arguments' frame index is recorded during argument lowering.
5612   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5613   if (FI != std::numeric_limits<int>::max())
5614     Op = MachineOperand::CreateFI(FI);
5615 
5616   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5617   if (!Op && N.getNode()) {
5618     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5619     Register Reg;
5620     if (ArgRegsAndSizes.size() == 1)
5621       Reg = ArgRegsAndSizes.front().first;
5622 
5623     if (Reg && Reg.isVirtual()) {
5624       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5625       Register PR = RegInfo.getLiveInPhysReg(Reg);
5626       if (PR)
5627         Reg = PR;
5628     }
5629     if (Reg) {
5630       Op = MachineOperand::CreateReg(Reg, false);
5631       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5632     }
5633   }
5634 
5635   if (!Op && N.getNode()) {
5636     // Check if frame index is available.
5637     SDValue LCandidate = peekThroughBitcasts(N);
5638     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5639       if (FrameIndexSDNode *FINode =
5640           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5641         Op = MachineOperand::CreateFI(FINode->getIndex());
5642   }
5643 
5644   if (!Op) {
5645     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5646     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5647                                          SplitRegs) {
5648       unsigned Offset = 0;
5649       for (const auto &RegAndSize : SplitRegs) {
5650         // If the expression is already a fragment, the current register
5651         // offset+size might extend beyond the fragment. In this case, only
5652         // the register bits that are inside the fragment are relevant.
5653         int RegFragmentSizeInBits = RegAndSize.second;
5654         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5655           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5656           // The register is entirely outside the expression fragment,
5657           // so is irrelevant for debug info.
5658           if (Offset >= ExprFragmentSizeInBits)
5659             break;
5660           // The register is partially outside the expression fragment, only
5661           // the low bits within the fragment are relevant for debug info.
5662           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5663             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5664           }
5665         }
5666 
5667         auto FragmentExpr = DIExpression::createFragmentExpression(
5668             Expr, Offset, RegFragmentSizeInBits);
5669         Offset += RegAndSize.second;
5670         // If a valid fragment expression cannot be created, the variable's
5671         // correct value cannot be determined and so it is set as Undef.
5672         if (!FragmentExpr) {
5673           SDDbgValue *SDV = DAG.getConstantDbgValue(
5674               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5675           DAG.AddDbgValue(SDV, false);
5676           continue;
5677         }
5678         MachineInstr *NewMI =
5679             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5680                              Kind != FuncArgumentDbgValueKind::Value);
5681         FuncInfo.ArgDbgValues.push_back(NewMI);
5682       }
5683     };
5684 
5685     // Check if ValueMap has reg number.
5686     DenseMap<const Value *, Register>::const_iterator
5687       VMI = FuncInfo.ValueMap.find(V);
5688     if (VMI != FuncInfo.ValueMap.end()) {
5689       const auto &TLI = DAG.getTargetLoweringInfo();
5690       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5691                        V->getType(), None);
5692       if (RFV.occupiesMultipleRegs()) {
5693         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5694         return true;
5695       }
5696 
5697       Op = MachineOperand::CreateReg(VMI->second, false);
5698       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5699     } else if (ArgRegsAndSizes.size() > 1) {
5700       // This was split due to the calling convention, and no virtual register
5701       // mapping exists for the value.
5702       splitMultiRegDbgValue(ArgRegsAndSizes);
5703       return true;
5704     }
5705   }
5706 
5707   if (!Op)
5708     return false;
5709 
5710   assert(Variable->isValidLocationForIntrinsic(DL) &&
5711          "Expected inlined-at fields to agree");
5712   MachineInstr *NewMI = nullptr;
5713 
5714   if (Op->isReg())
5715     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5716   else
5717     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5718                     Variable, Expr);
5719 
5720   // Otherwise, use ArgDbgValues.
5721   FuncInfo.ArgDbgValues.push_back(NewMI);
5722   return true;
5723 }
5724 
5725 /// Return the appropriate SDDbgValue based on N.
5726 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5727                                              DILocalVariable *Variable,
5728                                              DIExpression *Expr,
5729                                              const DebugLoc &dl,
5730                                              unsigned DbgSDNodeOrder) {
5731   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5732     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5733     // stack slot locations.
5734     //
5735     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5736     // debug values here after optimization:
5737     //
5738     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5739     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5740     //
5741     // Both describe the direct values of their associated variables.
5742     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5743                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5744   }
5745   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5746                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5747 }
5748 
5749 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5750   switch (Intrinsic) {
5751   case Intrinsic::smul_fix:
5752     return ISD::SMULFIX;
5753   case Intrinsic::umul_fix:
5754     return ISD::UMULFIX;
5755   case Intrinsic::smul_fix_sat:
5756     return ISD::SMULFIXSAT;
5757   case Intrinsic::umul_fix_sat:
5758     return ISD::UMULFIXSAT;
5759   case Intrinsic::sdiv_fix:
5760     return ISD::SDIVFIX;
5761   case Intrinsic::udiv_fix:
5762     return ISD::UDIVFIX;
5763   case Intrinsic::sdiv_fix_sat:
5764     return ISD::SDIVFIXSAT;
5765   case Intrinsic::udiv_fix_sat:
5766     return ISD::UDIVFIXSAT;
5767   default:
5768     llvm_unreachable("Unhandled fixed point intrinsic");
5769   }
5770 }
5771 
5772 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5773                                            const char *FunctionName) {
5774   assert(FunctionName && "FunctionName must not be nullptr");
5775   SDValue Callee = DAG.getExternalSymbol(
5776       FunctionName,
5777       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5778   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5779 }
5780 
5781 /// Given a @llvm.call.preallocated.setup, return the corresponding
5782 /// preallocated call.
5783 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5784   assert(cast<CallBase>(PreallocatedSetup)
5785                  ->getCalledFunction()
5786                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5787          "expected call_preallocated_setup Value");
5788   for (const auto *U : PreallocatedSetup->users()) {
5789     auto *UseCall = cast<CallBase>(U);
5790     const Function *Fn = UseCall->getCalledFunction();
5791     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5792       return UseCall;
5793     }
5794   }
5795   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5796 }
5797 
5798 /// Lower the call to the specified intrinsic function.
5799 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5800                                              unsigned Intrinsic) {
5801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5802   SDLoc sdl = getCurSDLoc();
5803   DebugLoc dl = getCurDebugLoc();
5804   SDValue Res;
5805 
5806   SDNodeFlags Flags;
5807   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5808     Flags.copyFMF(*FPOp);
5809 
5810   switch (Intrinsic) {
5811   default:
5812     // By default, turn this into a target intrinsic node.
5813     visitTargetIntrinsic(I, Intrinsic);
5814     return;
5815   case Intrinsic::vscale: {
5816     match(&I, m_VScale(DAG.getDataLayout()));
5817     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5818     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5819     return;
5820   }
5821   case Intrinsic::vastart:  visitVAStart(I); return;
5822   case Intrinsic::vaend:    visitVAEnd(I); return;
5823   case Intrinsic::vacopy:   visitVACopy(I); return;
5824   case Intrinsic::returnaddress:
5825     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5826                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5827                              getValue(I.getArgOperand(0))));
5828     return;
5829   case Intrinsic::addressofreturnaddress:
5830     setValue(&I,
5831              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5832                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5833     return;
5834   case Intrinsic::sponentry:
5835     setValue(&I,
5836              DAG.getNode(ISD::SPONENTRY, sdl,
5837                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5838     return;
5839   case Intrinsic::frameaddress:
5840     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5841                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5842                              getValue(I.getArgOperand(0))));
5843     return;
5844   case Intrinsic::read_volatile_register:
5845   case Intrinsic::read_register: {
5846     Value *Reg = I.getArgOperand(0);
5847     SDValue Chain = getRoot();
5848     SDValue RegName =
5849         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5850     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5851     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5852       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5853     setValue(&I, Res);
5854     DAG.setRoot(Res.getValue(1));
5855     return;
5856   }
5857   case Intrinsic::write_register: {
5858     Value *Reg = I.getArgOperand(0);
5859     Value *RegValue = I.getArgOperand(1);
5860     SDValue Chain = getRoot();
5861     SDValue RegName =
5862         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5863     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5864                             RegName, getValue(RegValue)));
5865     return;
5866   }
5867   case Intrinsic::memcpy: {
5868     const auto &MCI = cast<MemCpyInst>(I);
5869     SDValue Op1 = getValue(I.getArgOperand(0));
5870     SDValue Op2 = getValue(I.getArgOperand(1));
5871     SDValue Op3 = getValue(I.getArgOperand(2));
5872     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5873     Align DstAlign = MCI.getDestAlign().valueOrOne();
5874     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5875     Align Alignment = std::min(DstAlign, SrcAlign);
5876     bool isVol = MCI.isVolatile();
5877     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5878     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5879     // node.
5880     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5881     SDValue MC = DAG.getMemcpy(
5882         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5883         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
5884         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5885     updateDAGForMaybeTailCall(MC);
5886     return;
5887   }
5888   case Intrinsic::memcpy_inline: {
5889     const auto &MCI = cast<MemCpyInlineInst>(I);
5890     SDValue Dst = getValue(I.getArgOperand(0));
5891     SDValue Src = getValue(I.getArgOperand(1));
5892     SDValue Size = getValue(I.getArgOperand(2));
5893     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5894     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5895     Align DstAlign = MCI.getDestAlign().valueOrOne();
5896     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5897     Align Alignment = std::min(DstAlign, SrcAlign);
5898     bool isVol = MCI.isVolatile();
5899     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5900     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5901     // node.
5902     SDValue MC = DAG.getMemcpy(
5903         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5904         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
5905         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5906     updateDAGForMaybeTailCall(MC);
5907     return;
5908   }
5909   case Intrinsic::memset: {
5910     const auto &MSI = cast<MemSetInst>(I);
5911     SDValue Op1 = getValue(I.getArgOperand(0));
5912     SDValue Op2 = getValue(I.getArgOperand(1));
5913     SDValue Op3 = getValue(I.getArgOperand(2));
5914     // @llvm.memset defines 0 and 1 to both mean no alignment.
5915     Align Alignment = MSI.getDestAlign().valueOrOne();
5916     bool isVol = MSI.isVolatile();
5917     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5918     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5919     SDValue MS = DAG.getMemset(
5920         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
5921         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
5922     updateDAGForMaybeTailCall(MS);
5923     return;
5924   }
5925   case Intrinsic::memset_inline: {
5926     const auto &MSII = cast<MemSetInlineInst>(I);
5927     SDValue Dst = getValue(I.getArgOperand(0));
5928     SDValue Value = getValue(I.getArgOperand(1));
5929     SDValue Size = getValue(I.getArgOperand(2));
5930     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
5931     // @llvm.memset defines 0 and 1 to both mean no alignment.
5932     Align DstAlign = MSII.getDestAlign().valueOrOne();
5933     bool isVol = MSII.isVolatile();
5934     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5935     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5936     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
5937                                /* AlwaysInline */ true, isTC,
5938                                MachinePointerInfo(I.getArgOperand(0)),
5939                                I.getAAMetadata());
5940     updateDAGForMaybeTailCall(MC);
5941     return;
5942   }
5943   case Intrinsic::memmove: {
5944     const auto &MMI = cast<MemMoveInst>(I);
5945     SDValue Op1 = getValue(I.getArgOperand(0));
5946     SDValue Op2 = getValue(I.getArgOperand(1));
5947     SDValue Op3 = getValue(I.getArgOperand(2));
5948     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5949     Align DstAlign = MMI.getDestAlign().valueOrOne();
5950     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5951     Align Alignment = std::min(DstAlign, SrcAlign);
5952     bool isVol = MMI.isVolatile();
5953     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5954     // FIXME: Support passing different dest/src alignments to the memmove DAG
5955     // node.
5956     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5957     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5958                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5959                                 MachinePointerInfo(I.getArgOperand(1)),
5960                                 I.getAAMetadata(), AA);
5961     updateDAGForMaybeTailCall(MM);
5962     return;
5963   }
5964   case Intrinsic::memcpy_element_unordered_atomic: {
5965     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5966     SDValue Dst = getValue(MI.getRawDest());
5967     SDValue Src = getValue(MI.getRawSource());
5968     SDValue Length = getValue(MI.getLength());
5969 
5970     Type *LengthTy = MI.getLength()->getType();
5971     unsigned ElemSz = MI.getElementSizeInBytes();
5972     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5973     SDValue MC =
5974         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
5975                             isTC, MachinePointerInfo(MI.getRawDest()),
5976                             MachinePointerInfo(MI.getRawSource()));
5977     updateDAGForMaybeTailCall(MC);
5978     return;
5979   }
5980   case Intrinsic::memmove_element_unordered_atomic: {
5981     auto &MI = cast<AtomicMemMoveInst>(I);
5982     SDValue Dst = getValue(MI.getRawDest());
5983     SDValue Src = getValue(MI.getRawSource());
5984     SDValue Length = getValue(MI.getLength());
5985 
5986     Type *LengthTy = MI.getLength()->getType();
5987     unsigned ElemSz = MI.getElementSizeInBytes();
5988     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5989     SDValue MC =
5990         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
5991                              isTC, MachinePointerInfo(MI.getRawDest()),
5992                              MachinePointerInfo(MI.getRawSource()));
5993     updateDAGForMaybeTailCall(MC);
5994     return;
5995   }
5996   case Intrinsic::memset_element_unordered_atomic: {
5997     auto &MI = cast<AtomicMemSetInst>(I);
5998     SDValue Dst = getValue(MI.getRawDest());
5999     SDValue Val = getValue(MI.getValue());
6000     SDValue Length = getValue(MI.getLength());
6001 
6002     Type *LengthTy = MI.getLength()->getType();
6003     unsigned ElemSz = MI.getElementSizeInBytes();
6004     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6005     SDValue MC =
6006         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6007                             isTC, MachinePointerInfo(MI.getRawDest()));
6008     updateDAGForMaybeTailCall(MC);
6009     return;
6010   }
6011   case Intrinsic::call_preallocated_setup: {
6012     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6013     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6014     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6015                               getRoot(), SrcValue);
6016     setValue(&I, Res);
6017     DAG.setRoot(Res);
6018     return;
6019   }
6020   case Intrinsic::call_preallocated_arg: {
6021     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6022     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6023     SDValue Ops[3];
6024     Ops[0] = getRoot();
6025     Ops[1] = SrcValue;
6026     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6027                                    MVT::i32); // arg index
6028     SDValue Res = DAG.getNode(
6029         ISD::PREALLOCATED_ARG, sdl,
6030         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6031     setValue(&I, Res);
6032     DAG.setRoot(Res.getValue(1));
6033     return;
6034   }
6035   case Intrinsic::dbg_addr:
6036   case Intrinsic::dbg_declare: {
6037     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6038     // they are non-variadic.
6039     const auto &DI = cast<DbgVariableIntrinsic>(I);
6040     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6041     DILocalVariable *Variable = DI.getVariable();
6042     DIExpression *Expression = DI.getExpression();
6043     dropDanglingDebugInfo(Variable, Expression);
6044     assert(Variable && "Missing variable");
6045     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6046                       << "\n");
6047     // Check if address has undef value.
6048     const Value *Address = DI.getVariableLocationOp(0);
6049     if (!Address || isa<UndefValue>(Address) ||
6050         (Address->use_empty() && !isa<Argument>(Address))) {
6051       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6052                         << " (bad/undef/unused-arg address)\n");
6053       return;
6054     }
6055 
6056     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6057 
6058     // Check if this variable can be described by a frame index, typically
6059     // either as a static alloca or a byval parameter.
6060     int FI = std::numeric_limits<int>::max();
6061     if (const auto *AI =
6062             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6063       if (AI->isStaticAlloca()) {
6064         auto I = FuncInfo.StaticAllocaMap.find(AI);
6065         if (I != FuncInfo.StaticAllocaMap.end())
6066           FI = I->second;
6067       }
6068     } else if (const auto *Arg = dyn_cast<Argument>(
6069                    Address->stripInBoundsConstantOffsets())) {
6070       FI = FuncInfo.getArgumentFrameIndex(Arg);
6071     }
6072 
6073     // llvm.dbg.addr is control dependent and always generates indirect
6074     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6075     // the MachineFunction variable table.
6076     if (FI != std::numeric_limits<int>::max()) {
6077       if (Intrinsic == Intrinsic::dbg_addr) {
6078         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6079             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6080             dl, SDNodeOrder);
6081         DAG.AddDbgValue(SDV, isParameter);
6082       } else {
6083         LLVM_DEBUG(dbgs() << "Skipping " << DI
6084                           << " (variable info stashed in MF side table)\n");
6085       }
6086       return;
6087     }
6088 
6089     SDValue &N = NodeMap[Address];
6090     if (!N.getNode() && isa<Argument>(Address))
6091       // Check unused arguments map.
6092       N = UnusedArgNodeMap[Address];
6093     SDDbgValue *SDV;
6094     if (N.getNode()) {
6095       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6096         Address = BCI->getOperand(0);
6097       // Parameters are handled specially.
6098       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6099       if (isParameter && FINode) {
6100         // Byval parameter. We have a frame index at this point.
6101         SDV =
6102             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6103                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6104       } else if (isa<Argument>(Address)) {
6105         // Address is an argument, so try to emit its dbg value using
6106         // virtual register info from the FuncInfo.ValueMap.
6107         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6108                                  FuncArgumentDbgValueKind::Declare, N);
6109         return;
6110       } else {
6111         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6112                               true, dl, SDNodeOrder);
6113       }
6114       DAG.AddDbgValue(SDV, isParameter);
6115     } else {
6116       // If Address is an argument then try to emit its dbg value using
6117       // virtual register info from the FuncInfo.ValueMap.
6118       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6119                                     FuncArgumentDbgValueKind::Declare, N)) {
6120         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6121                           << " (could not emit func-arg dbg_value)\n");
6122       }
6123     }
6124     return;
6125   }
6126   case Intrinsic::dbg_label: {
6127     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6128     DILabel *Label = DI.getLabel();
6129     assert(Label && "Missing label");
6130 
6131     SDDbgLabel *SDV;
6132     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6133     DAG.AddDbgLabel(SDV);
6134     return;
6135   }
6136   case Intrinsic::dbg_value: {
6137     const DbgValueInst &DI = cast<DbgValueInst>(I);
6138     assert(DI.getVariable() && "Missing variable");
6139 
6140     DILocalVariable *Variable = DI.getVariable();
6141     DIExpression *Expression = DI.getExpression();
6142     dropDanglingDebugInfo(Variable, Expression);
6143     SmallVector<Value *, 4> Values(DI.getValues());
6144     if (Values.empty())
6145       return;
6146 
6147     if (llvm::is_contained(Values, nullptr))
6148       return;
6149 
6150     bool IsVariadic = DI.hasArgList();
6151     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6152                           SDNodeOrder, IsVariadic))
6153       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6154     return;
6155   }
6156 
6157   case Intrinsic::eh_typeid_for: {
6158     // Find the type id for the given typeinfo.
6159     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6160     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6161     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6162     setValue(&I, Res);
6163     return;
6164   }
6165 
6166   case Intrinsic::eh_return_i32:
6167   case Intrinsic::eh_return_i64:
6168     DAG.getMachineFunction().setCallsEHReturn(true);
6169     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6170                             MVT::Other,
6171                             getControlRoot(),
6172                             getValue(I.getArgOperand(0)),
6173                             getValue(I.getArgOperand(1))));
6174     return;
6175   case Intrinsic::eh_unwind_init:
6176     DAG.getMachineFunction().setCallsUnwindInit(true);
6177     return;
6178   case Intrinsic::eh_dwarf_cfa:
6179     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6180                              TLI.getPointerTy(DAG.getDataLayout()),
6181                              getValue(I.getArgOperand(0))));
6182     return;
6183   case Intrinsic::eh_sjlj_callsite: {
6184     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6185     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6186     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6187 
6188     MMI.setCurrentCallSite(CI->getZExtValue());
6189     return;
6190   }
6191   case Intrinsic::eh_sjlj_functioncontext: {
6192     // Get and store the index of the function context.
6193     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6194     AllocaInst *FnCtx =
6195       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6196     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6197     MFI.setFunctionContextIndex(FI);
6198     return;
6199   }
6200   case Intrinsic::eh_sjlj_setjmp: {
6201     SDValue Ops[2];
6202     Ops[0] = getRoot();
6203     Ops[1] = getValue(I.getArgOperand(0));
6204     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6205                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6206     setValue(&I, Op.getValue(0));
6207     DAG.setRoot(Op.getValue(1));
6208     return;
6209   }
6210   case Intrinsic::eh_sjlj_longjmp:
6211     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6212                             getRoot(), getValue(I.getArgOperand(0))));
6213     return;
6214   case Intrinsic::eh_sjlj_setup_dispatch:
6215     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6216                             getRoot()));
6217     return;
6218   case Intrinsic::masked_gather:
6219     visitMaskedGather(I);
6220     return;
6221   case Intrinsic::masked_load:
6222     visitMaskedLoad(I);
6223     return;
6224   case Intrinsic::masked_scatter:
6225     visitMaskedScatter(I);
6226     return;
6227   case Intrinsic::masked_store:
6228     visitMaskedStore(I);
6229     return;
6230   case Intrinsic::masked_expandload:
6231     visitMaskedLoad(I, true /* IsExpanding */);
6232     return;
6233   case Intrinsic::masked_compressstore:
6234     visitMaskedStore(I, true /* IsCompressing */);
6235     return;
6236   case Intrinsic::powi:
6237     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6238                             getValue(I.getArgOperand(1)), DAG));
6239     return;
6240   case Intrinsic::log:
6241     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6242     return;
6243   case Intrinsic::log2:
6244     setValue(&I,
6245              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6246     return;
6247   case Intrinsic::log10:
6248     setValue(&I,
6249              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6250     return;
6251   case Intrinsic::exp:
6252     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6253     return;
6254   case Intrinsic::exp2:
6255     setValue(&I,
6256              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6257     return;
6258   case Intrinsic::pow:
6259     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6260                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6261     return;
6262   case Intrinsic::sqrt:
6263   case Intrinsic::fabs:
6264   case Intrinsic::sin:
6265   case Intrinsic::cos:
6266   case Intrinsic::floor:
6267   case Intrinsic::ceil:
6268   case Intrinsic::trunc:
6269   case Intrinsic::rint:
6270   case Intrinsic::nearbyint:
6271   case Intrinsic::round:
6272   case Intrinsic::roundeven:
6273   case Intrinsic::canonicalize: {
6274     unsigned Opcode;
6275     switch (Intrinsic) {
6276     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6277     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6278     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6279     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6280     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6281     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6282     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6283     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6284     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6285     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6286     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6287     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6288     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6289     }
6290 
6291     setValue(&I, DAG.getNode(Opcode, sdl,
6292                              getValue(I.getArgOperand(0)).getValueType(),
6293                              getValue(I.getArgOperand(0)), Flags));
6294     return;
6295   }
6296   case Intrinsic::lround:
6297   case Intrinsic::llround:
6298   case Intrinsic::lrint:
6299   case Intrinsic::llrint: {
6300     unsigned Opcode;
6301     switch (Intrinsic) {
6302     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6303     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6304     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6305     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6306     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6307     }
6308 
6309     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6310     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6311                              getValue(I.getArgOperand(0))));
6312     return;
6313   }
6314   case Intrinsic::minnum:
6315     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6316                              getValue(I.getArgOperand(0)).getValueType(),
6317                              getValue(I.getArgOperand(0)),
6318                              getValue(I.getArgOperand(1)), Flags));
6319     return;
6320   case Intrinsic::maxnum:
6321     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6322                              getValue(I.getArgOperand(0)).getValueType(),
6323                              getValue(I.getArgOperand(0)),
6324                              getValue(I.getArgOperand(1)), Flags));
6325     return;
6326   case Intrinsic::minimum:
6327     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6328                              getValue(I.getArgOperand(0)).getValueType(),
6329                              getValue(I.getArgOperand(0)),
6330                              getValue(I.getArgOperand(1)), Flags));
6331     return;
6332   case Intrinsic::maximum:
6333     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6334                              getValue(I.getArgOperand(0)).getValueType(),
6335                              getValue(I.getArgOperand(0)),
6336                              getValue(I.getArgOperand(1)), Flags));
6337     return;
6338   case Intrinsic::copysign:
6339     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6340                              getValue(I.getArgOperand(0)).getValueType(),
6341                              getValue(I.getArgOperand(0)),
6342                              getValue(I.getArgOperand(1)), Flags));
6343     return;
6344   case Intrinsic::arithmetic_fence: {
6345     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6346                              getValue(I.getArgOperand(0)).getValueType(),
6347                              getValue(I.getArgOperand(0)), Flags));
6348     return;
6349   }
6350   case Intrinsic::fma:
6351     setValue(&I, DAG.getNode(
6352                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6353                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6354                      getValue(I.getArgOperand(2)), Flags));
6355     return;
6356 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6357   case Intrinsic::INTRINSIC:
6358 #include "llvm/IR/ConstrainedOps.def"
6359     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6360     return;
6361 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6362 #include "llvm/IR/VPIntrinsics.def"
6363     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6364     return;
6365   case Intrinsic::fptrunc_round: {
6366     // Get the last argument, the metadata and convert it to an integer in the
6367     // call
6368     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6369     Optional<RoundingMode> RoundMode =
6370         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6371 
6372     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6373 
6374     // Propagate fast-math-flags from IR to node(s).
6375     SDNodeFlags Flags;
6376     Flags.copyFMF(*cast<FPMathOperator>(&I));
6377     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6378 
6379     SDValue Result;
6380     Result = DAG.getNode(
6381         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6382         DAG.getTargetConstant((int)*RoundMode, sdl,
6383                               TLI.getPointerTy(DAG.getDataLayout())));
6384     setValue(&I, Result);
6385 
6386     return;
6387   }
6388   case Intrinsic::fmuladd: {
6389     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6390     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6391         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6392       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6393                                getValue(I.getArgOperand(0)).getValueType(),
6394                                getValue(I.getArgOperand(0)),
6395                                getValue(I.getArgOperand(1)),
6396                                getValue(I.getArgOperand(2)), Flags));
6397     } else {
6398       // TODO: Intrinsic calls should have fast-math-flags.
6399       SDValue Mul = DAG.getNode(
6400           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6401           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6402       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6403                                 getValue(I.getArgOperand(0)).getValueType(),
6404                                 Mul, getValue(I.getArgOperand(2)), Flags);
6405       setValue(&I, Add);
6406     }
6407     return;
6408   }
6409   case Intrinsic::convert_to_fp16:
6410     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6411                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6412                                          getValue(I.getArgOperand(0)),
6413                                          DAG.getTargetConstant(0, sdl,
6414                                                                MVT::i32))));
6415     return;
6416   case Intrinsic::convert_from_fp16:
6417     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6418                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6419                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6420                                          getValue(I.getArgOperand(0)))));
6421     return;
6422   case Intrinsic::fptosi_sat: {
6423     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6424     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6425                              getValue(I.getArgOperand(0)),
6426                              DAG.getValueType(VT.getScalarType())));
6427     return;
6428   }
6429   case Intrinsic::fptoui_sat: {
6430     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6431     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6432                              getValue(I.getArgOperand(0)),
6433                              DAG.getValueType(VT.getScalarType())));
6434     return;
6435   }
6436   case Intrinsic::set_rounding:
6437     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6438                       {getRoot(), getValue(I.getArgOperand(0))});
6439     setValue(&I, Res);
6440     DAG.setRoot(Res.getValue(0));
6441     return;
6442   case Intrinsic::is_fpclass: {
6443     const DataLayout DLayout = DAG.getDataLayout();
6444     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6445     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6446     unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6447     MachineFunction &MF = DAG.getMachineFunction();
6448     const Function &F = MF.getFunction();
6449     SDValue Op = getValue(I.getArgOperand(0));
6450     SDNodeFlags Flags;
6451     Flags.setNoFPExcept(
6452         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6453     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6454     // expansion can use illegal types. Making expansion early allows
6455     // legalizing these types prior to selection.
6456     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6457       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6458       setValue(&I, Result);
6459       return;
6460     }
6461 
6462     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6463     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6464     setValue(&I, V);
6465     return;
6466   }
6467   case Intrinsic::pcmarker: {
6468     SDValue Tmp = getValue(I.getArgOperand(0));
6469     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6470     return;
6471   }
6472   case Intrinsic::readcyclecounter: {
6473     SDValue Op = getRoot();
6474     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6475                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6476     setValue(&I, Res);
6477     DAG.setRoot(Res.getValue(1));
6478     return;
6479   }
6480   case Intrinsic::bitreverse:
6481     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6482                              getValue(I.getArgOperand(0)).getValueType(),
6483                              getValue(I.getArgOperand(0))));
6484     return;
6485   case Intrinsic::bswap:
6486     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6487                              getValue(I.getArgOperand(0)).getValueType(),
6488                              getValue(I.getArgOperand(0))));
6489     return;
6490   case Intrinsic::cttz: {
6491     SDValue Arg = getValue(I.getArgOperand(0));
6492     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6493     EVT Ty = Arg.getValueType();
6494     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6495                              sdl, Ty, Arg));
6496     return;
6497   }
6498   case Intrinsic::ctlz: {
6499     SDValue Arg = getValue(I.getArgOperand(0));
6500     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6501     EVT Ty = Arg.getValueType();
6502     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6503                              sdl, Ty, Arg));
6504     return;
6505   }
6506   case Intrinsic::ctpop: {
6507     SDValue Arg = getValue(I.getArgOperand(0));
6508     EVT Ty = Arg.getValueType();
6509     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6510     return;
6511   }
6512   case Intrinsic::fshl:
6513   case Intrinsic::fshr: {
6514     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6515     SDValue X = getValue(I.getArgOperand(0));
6516     SDValue Y = getValue(I.getArgOperand(1));
6517     SDValue Z = getValue(I.getArgOperand(2));
6518     EVT VT = X.getValueType();
6519 
6520     if (X == Y) {
6521       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6522       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6523     } else {
6524       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6525       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6526     }
6527     return;
6528   }
6529   case Intrinsic::sadd_sat: {
6530     SDValue Op1 = getValue(I.getArgOperand(0));
6531     SDValue Op2 = getValue(I.getArgOperand(1));
6532     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6533     return;
6534   }
6535   case Intrinsic::uadd_sat: {
6536     SDValue Op1 = getValue(I.getArgOperand(0));
6537     SDValue Op2 = getValue(I.getArgOperand(1));
6538     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6539     return;
6540   }
6541   case Intrinsic::ssub_sat: {
6542     SDValue Op1 = getValue(I.getArgOperand(0));
6543     SDValue Op2 = getValue(I.getArgOperand(1));
6544     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6545     return;
6546   }
6547   case Intrinsic::usub_sat: {
6548     SDValue Op1 = getValue(I.getArgOperand(0));
6549     SDValue Op2 = getValue(I.getArgOperand(1));
6550     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6551     return;
6552   }
6553   case Intrinsic::sshl_sat: {
6554     SDValue Op1 = getValue(I.getArgOperand(0));
6555     SDValue Op2 = getValue(I.getArgOperand(1));
6556     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6557     return;
6558   }
6559   case Intrinsic::ushl_sat: {
6560     SDValue Op1 = getValue(I.getArgOperand(0));
6561     SDValue Op2 = getValue(I.getArgOperand(1));
6562     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6563     return;
6564   }
6565   case Intrinsic::smul_fix:
6566   case Intrinsic::umul_fix:
6567   case Intrinsic::smul_fix_sat:
6568   case Intrinsic::umul_fix_sat: {
6569     SDValue Op1 = getValue(I.getArgOperand(0));
6570     SDValue Op2 = getValue(I.getArgOperand(1));
6571     SDValue Op3 = getValue(I.getArgOperand(2));
6572     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6573                              Op1.getValueType(), Op1, Op2, Op3));
6574     return;
6575   }
6576   case Intrinsic::sdiv_fix:
6577   case Intrinsic::udiv_fix:
6578   case Intrinsic::sdiv_fix_sat:
6579   case Intrinsic::udiv_fix_sat: {
6580     SDValue Op1 = getValue(I.getArgOperand(0));
6581     SDValue Op2 = getValue(I.getArgOperand(1));
6582     SDValue Op3 = getValue(I.getArgOperand(2));
6583     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6584                               Op1, Op2, Op3, DAG, TLI));
6585     return;
6586   }
6587   case Intrinsic::smax: {
6588     SDValue Op1 = getValue(I.getArgOperand(0));
6589     SDValue Op2 = getValue(I.getArgOperand(1));
6590     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6591     return;
6592   }
6593   case Intrinsic::smin: {
6594     SDValue Op1 = getValue(I.getArgOperand(0));
6595     SDValue Op2 = getValue(I.getArgOperand(1));
6596     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6597     return;
6598   }
6599   case Intrinsic::umax: {
6600     SDValue Op1 = getValue(I.getArgOperand(0));
6601     SDValue Op2 = getValue(I.getArgOperand(1));
6602     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6603     return;
6604   }
6605   case Intrinsic::umin: {
6606     SDValue Op1 = getValue(I.getArgOperand(0));
6607     SDValue Op2 = getValue(I.getArgOperand(1));
6608     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6609     return;
6610   }
6611   case Intrinsic::abs: {
6612     // TODO: Preserve "int min is poison" arg in SDAG?
6613     SDValue Op1 = getValue(I.getArgOperand(0));
6614     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6615     return;
6616   }
6617   case Intrinsic::stacksave: {
6618     SDValue Op = getRoot();
6619     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6620     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6621     setValue(&I, Res);
6622     DAG.setRoot(Res.getValue(1));
6623     return;
6624   }
6625   case Intrinsic::stackrestore:
6626     Res = getValue(I.getArgOperand(0));
6627     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6628     return;
6629   case Intrinsic::get_dynamic_area_offset: {
6630     SDValue Op = getRoot();
6631     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6632     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6633     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6634     // target.
6635     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6636       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6637                          " intrinsic!");
6638     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6639                       Op);
6640     DAG.setRoot(Op);
6641     setValue(&I, Res);
6642     return;
6643   }
6644   case Intrinsic::stackguard: {
6645     MachineFunction &MF = DAG.getMachineFunction();
6646     const Module &M = *MF.getFunction().getParent();
6647     SDValue Chain = getRoot();
6648     if (TLI.useLoadStackGuardNode()) {
6649       Res = getLoadStackGuard(DAG, sdl, Chain);
6650     } else {
6651       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6652       const Value *Global = TLI.getSDagStackGuard(M);
6653       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6654       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6655                         MachinePointerInfo(Global, 0), Align,
6656                         MachineMemOperand::MOVolatile);
6657     }
6658     if (TLI.useStackGuardXorFP())
6659       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6660     DAG.setRoot(Chain);
6661     setValue(&I, Res);
6662     return;
6663   }
6664   case Intrinsic::stackprotector: {
6665     // Emit code into the DAG to store the stack guard onto the stack.
6666     MachineFunction &MF = DAG.getMachineFunction();
6667     MachineFrameInfo &MFI = MF.getFrameInfo();
6668     SDValue Src, Chain = getRoot();
6669 
6670     if (TLI.useLoadStackGuardNode())
6671       Src = getLoadStackGuard(DAG, sdl, Chain);
6672     else
6673       Src = getValue(I.getArgOperand(0));   // The guard's value.
6674 
6675     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6676 
6677     int FI = FuncInfo.StaticAllocaMap[Slot];
6678     MFI.setStackProtectorIndex(FI);
6679     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6680 
6681     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6682 
6683     // Store the stack protector onto the stack.
6684     Res = DAG.getStore(
6685         Chain, sdl, Src, FIN,
6686         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6687         MaybeAlign(), MachineMemOperand::MOVolatile);
6688     setValue(&I, Res);
6689     DAG.setRoot(Res);
6690     return;
6691   }
6692   case Intrinsic::objectsize:
6693     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6694 
6695   case Intrinsic::is_constant:
6696     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6697 
6698   case Intrinsic::annotation:
6699   case Intrinsic::ptr_annotation:
6700   case Intrinsic::launder_invariant_group:
6701   case Intrinsic::strip_invariant_group:
6702     // Drop the intrinsic, but forward the value
6703     setValue(&I, getValue(I.getOperand(0)));
6704     return;
6705 
6706   case Intrinsic::assume:
6707   case Intrinsic::experimental_noalias_scope_decl:
6708   case Intrinsic::var_annotation:
6709   case Intrinsic::sideeffect:
6710     // Discard annotate attributes, noalias scope declarations, assumptions, and
6711     // artificial side-effects.
6712     return;
6713 
6714   case Intrinsic::codeview_annotation: {
6715     // Emit a label associated with this metadata.
6716     MachineFunction &MF = DAG.getMachineFunction();
6717     MCSymbol *Label =
6718         MF.getMMI().getContext().createTempSymbol("annotation", true);
6719     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6720     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6721     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6722     DAG.setRoot(Res);
6723     return;
6724   }
6725 
6726   case Intrinsic::init_trampoline: {
6727     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6728 
6729     SDValue Ops[6];
6730     Ops[0] = getRoot();
6731     Ops[1] = getValue(I.getArgOperand(0));
6732     Ops[2] = getValue(I.getArgOperand(1));
6733     Ops[3] = getValue(I.getArgOperand(2));
6734     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6735     Ops[5] = DAG.getSrcValue(F);
6736 
6737     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6738 
6739     DAG.setRoot(Res);
6740     return;
6741   }
6742   case Intrinsic::adjust_trampoline:
6743     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6744                              TLI.getPointerTy(DAG.getDataLayout()),
6745                              getValue(I.getArgOperand(0))));
6746     return;
6747   case Intrinsic::gcroot: {
6748     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6749            "only valid in functions with gc specified, enforced by Verifier");
6750     assert(GFI && "implied by previous");
6751     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6752     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6753 
6754     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6755     GFI->addStackRoot(FI->getIndex(), TypeMap);
6756     return;
6757   }
6758   case Intrinsic::gcread:
6759   case Intrinsic::gcwrite:
6760     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6761   case Intrinsic::flt_rounds:
6762     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6763     setValue(&I, Res);
6764     DAG.setRoot(Res.getValue(1));
6765     return;
6766 
6767   case Intrinsic::expect:
6768     // Just replace __builtin_expect(exp, c) with EXP.
6769     setValue(&I, getValue(I.getArgOperand(0)));
6770     return;
6771 
6772   case Intrinsic::ubsantrap:
6773   case Intrinsic::debugtrap:
6774   case Intrinsic::trap: {
6775     StringRef TrapFuncName =
6776         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6777     if (TrapFuncName.empty()) {
6778       switch (Intrinsic) {
6779       case Intrinsic::trap:
6780         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6781         break;
6782       case Intrinsic::debugtrap:
6783         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6784         break;
6785       case Intrinsic::ubsantrap:
6786         DAG.setRoot(DAG.getNode(
6787             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6788             DAG.getTargetConstant(
6789                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6790                 MVT::i32)));
6791         break;
6792       default: llvm_unreachable("unknown trap intrinsic");
6793       }
6794       return;
6795     }
6796     TargetLowering::ArgListTy Args;
6797     if (Intrinsic == Intrinsic::ubsantrap) {
6798       Args.push_back(TargetLoweringBase::ArgListEntry());
6799       Args[0].Val = I.getArgOperand(0);
6800       Args[0].Node = getValue(Args[0].Val);
6801       Args[0].Ty = Args[0].Val->getType();
6802     }
6803 
6804     TargetLowering::CallLoweringInfo CLI(DAG);
6805     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6806         CallingConv::C, I.getType(),
6807         DAG.getExternalSymbol(TrapFuncName.data(),
6808                               TLI.getPointerTy(DAG.getDataLayout())),
6809         std::move(Args));
6810 
6811     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6812     DAG.setRoot(Result.second);
6813     return;
6814   }
6815 
6816   case Intrinsic::uadd_with_overflow:
6817   case Intrinsic::sadd_with_overflow:
6818   case Intrinsic::usub_with_overflow:
6819   case Intrinsic::ssub_with_overflow:
6820   case Intrinsic::umul_with_overflow:
6821   case Intrinsic::smul_with_overflow: {
6822     ISD::NodeType Op;
6823     switch (Intrinsic) {
6824     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6825     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6826     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6827     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6828     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6829     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6830     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6831     }
6832     SDValue Op1 = getValue(I.getArgOperand(0));
6833     SDValue Op2 = getValue(I.getArgOperand(1));
6834 
6835     EVT ResultVT = Op1.getValueType();
6836     EVT OverflowVT = MVT::i1;
6837     if (ResultVT.isVector())
6838       OverflowVT = EVT::getVectorVT(
6839           *Context, OverflowVT, ResultVT.getVectorElementCount());
6840 
6841     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6842     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6843     return;
6844   }
6845   case Intrinsic::prefetch: {
6846     SDValue Ops[5];
6847     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6848     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6849     Ops[0] = DAG.getRoot();
6850     Ops[1] = getValue(I.getArgOperand(0));
6851     Ops[2] = getValue(I.getArgOperand(1));
6852     Ops[3] = getValue(I.getArgOperand(2));
6853     Ops[4] = getValue(I.getArgOperand(3));
6854     SDValue Result = DAG.getMemIntrinsicNode(
6855         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6856         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6857         /* align */ None, Flags);
6858 
6859     // Chain the prefetch in parallell with any pending loads, to stay out of
6860     // the way of later optimizations.
6861     PendingLoads.push_back(Result);
6862     Result = getRoot();
6863     DAG.setRoot(Result);
6864     return;
6865   }
6866   case Intrinsic::lifetime_start:
6867   case Intrinsic::lifetime_end: {
6868     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6869     // Stack coloring is not enabled in O0, discard region information.
6870     if (TM.getOptLevel() == CodeGenOpt::None)
6871       return;
6872 
6873     const int64_t ObjectSize =
6874         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6875     Value *const ObjectPtr = I.getArgOperand(1);
6876     SmallVector<const Value *, 4> Allocas;
6877     getUnderlyingObjects(ObjectPtr, Allocas);
6878 
6879     for (const Value *Alloca : Allocas) {
6880       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6881 
6882       // Could not find an Alloca.
6883       if (!LifetimeObject)
6884         continue;
6885 
6886       // First check that the Alloca is static, otherwise it won't have a
6887       // valid frame index.
6888       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6889       if (SI == FuncInfo.StaticAllocaMap.end())
6890         return;
6891 
6892       const int FrameIndex = SI->second;
6893       int64_t Offset;
6894       if (GetPointerBaseWithConstantOffset(
6895               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6896         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6897       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6898                                 Offset);
6899       DAG.setRoot(Res);
6900     }
6901     return;
6902   }
6903   case Intrinsic::pseudoprobe: {
6904     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6905     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6906     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6907     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6908     DAG.setRoot(Res);
6909     return;
6910   }
6911   case Intrinsic::invariant_start:
6912     // Discard region information.
6913     setValue(&I,
6914              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
6915     return;
6916   case Intrinsic::invariant_end:
6917     // Discard region information.
6918     return;
6919   case Intrinsic::clear_cache:
6920     /// FunctionName may be null.
6921     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6922       lowerCallToExternalSymbol(I, FunctionName);
6923     return;
6924   case Intrinsic::donothing:
6925   case Intrinsic::seh_try_begin:
6926   case Intrinsic::seh_scope_begin:
6927   case Intrinsic::seh_try_end:
6928   case Intrinsic::seh_scope_end:
6929     // ignore
6930     return;
6931   case Intrinsic::experimental_stackmap:
6932     visitStackmap(I);
6933     return;
6934   case Intrinsic::experimental_patchpoint_void:
6935   case Intrinsic::experimental_patchpoint_i64:
6936     visitPatchpoint(I);
6937     return;
6938   case Intrinsic::experimental_gc_statepoint:
6939     LowerStatepoint(cast<GCStatepointInst>(I));
6940     return;
6941   case Intrinsic::experimental_gc_result:
6942     visitGCResult(cast<GCResultInst>(I));
6943     return;
6944   case Intrinsic::experimental_gc_relocate:
6945     visitGCRelocate(cast<GCRelocateInst>(I));
6946     return;
6947   case Intrinsic::instrprof_cover:
6948     llvm_unreachable("instrprof failed to lower a cover");
6949   case Intrinsic::instrprof_increment:
6950     llvm_unreachable("instrprof failed to lower an increment");
6951   case Intrinsic::instrprof_value_profile:
6952     llvm_unreachable("instrprof failed to lower a value profiling call");
6953   case Intrinsic::localescape: {
6954     MachineFunction &MF = DAG.getMachineFunction();
6955     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6956 
6957     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6958     // is the same on all targets.
6959     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6960       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6961       if (isa<ConstantPointerNull>(Arg))
6962         continue; // Skip null pointers. They represent a hole in index space.
6963       AllocaInst *Slot = cast<AllocaInst>(Arg);
6964       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6965              "can only escape static allocas");
6966       int FI = FuncInfo.StaticAllocaMap[Slot];
6967       MCSymbol *FrameAllocSym =
6968           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6969               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6970       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6971               TII->get(TargetOpcode::LOCAL_ESCAPE))
6972           .addSym(FrameAllocSym)
6973           .addFrameIndex(FI);
6974     }
6975 
6976     return;
6977   }
6978 
6979   case Intrinsic::localrecover: {
6980     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6981     MachineFunction &MF = DAG.getMachineFunction();
6982 
6983     // Get the symbol that defines the frame offset.
6984     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6985     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6986     unsigned IdxVal =
6987         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6988     MCSymbol *FrameAllocSym =
6989         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6990             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6991 
6992     Value *FP = I.getArgOperand(1);
6993     SDValue FPVal = getValue(FP);
6994     EVT PtrVT = FPVal.getValueType();
6995 
6996     // Create a MCSymbol for the label to avoid any target lowering
6997     // that would make this PC relative.
6998     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6999     SDValue OffsetVal =
7000         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7001 
7002     // Add the offset to the FP.
7003     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7004     setValue(&I, Add);
7005 
7006     return;
7007   }
7008 
7009   case Intrinsic::eh_exceptionpointer:
7010   case Intrinsic::eh_exceptioncode: {
7011     // Get the exception pointer vreg, copy from it, and resize it to fit.
7012     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7013     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7014     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7015     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7016     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7017     if (Intrinsic == Intrinsic::eh_exceptioncode)
7018       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7019     setValue(&I, N);
7020     return;
7021   }
7022   case Intrinsic::xray_customevent: {
7023     // Here we want to make sure that the intrinsic behaves as if it has a
7024     // specific calling convention, and only for x86_64.
7025     // FIXME: Support other platforms later.
7026     const auto &Triple = DAG.getTarget().getTargetTriple();
7027     if (Triple.getArch() != Triple::x86_64)
7028       return;
7029 
7030     SmallVector<SDValue, 8> Ops;
7031 
7032     // We want to say that we always want the arguments in registers.
7033     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7034     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7035     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7036     SDValue Chain = getRoot();
7037     Ops.push_back(LogEntryVal);
7038     Ops.push_back(StrSizeVal);
7039     Ops.push_back(Chain);
7040 
7041     // We need to enforce the calling convention for the callsite, so that
7042     // argument ordering is enforced correctly, and that register allocation can
7043     // see that some registers may be assumed clobbered and have to preserve
7044     // them across calls to the intrinsic.
7045     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7046                                            sdl, NodeTys, Ops);
7047     SDValue patchableNode = SDValue(MN, 0);
7048     DAG.setRoot(patchableNode);
7049     setValue(&I, patchableNode);
7050     return;
7051   }
7052   case Intrinsic::xray_typedevent: {
7053     // Here we want to make sure that the intrinsic behaves as if it has a
7054     // specific calling convention, and only for x86_64.
7055     // FIXME: Support other platforms later.
7056     const auto &Triple = DAG.getTarget().getTargetTriple();
7057     if (Triple.getArch() != Triple::x86_64)
7058       return;
7059 
7060     SmallVector<SDValue, 8> Ops;
7061 
7062     // We want to say that we always want the arguments in registers.
7063     // It's unclear to me how manipulating the selection DAG here forces callers
7064     // to provide arguments in registers instead of on the stack.
7065     SDValue LogTypeId = getValue(I.getArgOperand(0));
7066     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7067     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7068     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7069     SDValue Chain = getRoot();
7070     Ops.push_back(LogTypeId);
7071     Ops.push_back(LogEntryVal);
7072     Ops.push_back(StrSizeVal);
7073     Ops.push_back(Chain);
7074 
7075     // We need to enforce the calling convention for the callsite, so that
7076     // argument ordering is enforced correctly, and that register allocation can
7077     // see that some registers may be assumed clobbered and have to preserve
7078     // them across calls to the intrinsic.
7079     MachineSDNode *MN = DAG.getMachineNode(
7080         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7081     SDValue patchableNode = SDValue(MN, 0);
7082     DAG.setRoot(patchableNode);
7083     setValue(&I, patchableNode);
7084     return;
7085   }
7086   case Intrinsic::experimental_deoptimize:
7087     LowerDeoptimizeCall(&I);
7088     return;
7089   case Intrinsic::experimental_stepvector:
7090     visitStepVector(I);
7091     return;
7092   case Intrinsic::vector_reduce_fadd:
7093   case Intrinsic::vector_reduce_fmul:
7094   case Intrinsic::vector_reduce_add:
7095   case Intrinsic::vector_reduce_mul:
7096   case Intrinsic::vector_reduce_and:
7097   case Intrinsic::vector_reduce_or:
7098   case Intrinsic::vector_reduce_xor:
7099   case Intrinsic::vector_reduce_smax:
7100   case Intrinsic::vector_reduce_smin:
7101   case Intrinsic::vector_reduce_umax:
7102   case Intrinsic::vector_reduce_umin:
7103   case Intrinsic::vector_reduce_fmax:
7104   case Intrinsic::vector_reduce_fmin:
7105     visitVectorReduce(I, Intrinsic);
7106     return;
7107 
7108   case Intrinsic::icall_branch_funnel: {
7109     SmallVector<SDValue, 16> Ops;
7110     Ops.push_back(getValue(I.getArgOperand(0)));
7111 
7112     int64_t Offset;
7113     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7114         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7115     if (!Base)
7116       report_fatal_error(
7117           "llvm.icall.branch.funnel operand must be a GlobalValue");
7118     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7119 
7120     struct BranchFunnelTarget {
7121       int64_t Offset;
7122       SDValue Target;
7123     };
7124     SmallVector<BranchFunnelTarget, 8> Targets;
7125 
7126     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7127       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7128           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7129       if (ElemBase != Base)
7130         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7131                            "to the same GlobalValue");
7132 
7133       SDValue Val = getValue(I.getArgOperand(Op + 1));
7134       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7135       if (!GA)
7136         report_fatal_error(
7137             "llvm.icall.branch.funnel operand must be a GlobalValue");
7138       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7139                                      GA->getGlobal(), sdl, Val.getValueType(),
7140                                      GA->getOffset())});
7141     }
7142     llvm::sort(Targets,
7143                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7144                  return T1.Offset < T2.Offset;
7145                });
7146 
7147     for (auto &T : Targets) {
7148       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7149       Ops.push_back(T.Target);
7150     }
7151 
7152     Ops.push_back(DAG.getRoot()); // Chain
7153     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7154                                  MVT::Other, Ops),
7155               0);
7156     DAG.setRoot(N);
7157     setValue(&I, N);
7158     HasTailCall = true;
7159     return;
7160   }
7161 
7162   case Intrinsic::wasm_landingpad_index:
7163     // Information this intrinsic contained has been transferred to
7164     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7165     // delete it now.
7166     return;
7167 
7168   case Intrinsic::aarch64_settag:
7169   case Intrinsic::aarch64_settag_zero: {
7170     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7171     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7172     SDValue Val = TSI.EmitTargetCodeForSetTag(
7173         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7174         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7175         ZeroMemory);
7176     DAG.setRoot(Val);
7177     setValue(&I, Val);
7178     return;
7179   }
7180   case Intrinsic::ptrmask: {
7181     SDValue Ptr = getValue(I.getOperand(0));
7182     SDValue Const = getValue(I.getOperand(1));
7183 
7184     EVT PtrVT = Ptr.getValueType();
7185     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7186                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7187     return;
7188   }
7189   case Intrinsic::threadlocal_address: {
7190     setValue(&I, getValue(I.getOperand(0)));
7191     return;
7192   }
7193   case Intrinsic::get_active_lane_mask: {
7194     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7195     SDValue Index = getValue(I.getOperand(0));
7196     EVT ElementVT = Index.getValueType();
7197 
7198     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7199       visitTargetIntrinsic(I, Intrinsic);
7200       return;
7201     }
7202 
7203     SDValue TripCount = getValue(I.getOperand(1));
7204     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7205 
7206     SDValue VectorIndex, VectorTripCount;
7207     if (VecTy.isScalableVector()) {
7208       VectorIndex = DAG.getSplatVector(VecTy, sdl, Index);
7209       VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount);
7210     } else {
7211       VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index);
7212       VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount);
7213     }
7214     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7215     SDValue VectorInduction = DAG.getNode(
7216         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7217     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7218                                  VectorTripCount, ISD::CondCode::SETULT);
7219     setValue(&I, SetCC);
7220     return;
7221   }
7222   case Intrinsic::vector_insert: {
7223     SDValue Vec = getValue(I.getOperand(0));
7224     SDValue SubVec = getValue(I.getOperand(1));
7225     SDValue Index = getValue(I.getOperand(2));
7226 
7227     // The intrinsic's index type is i64, but the SDNode requires an index type
7228     // suitable for the target. Convert the index as required.
7229     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7230     if (Index.getValueType() != VectorIdxTy)
7231       Index = DAG.getVectorIdxConstant(
7232           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7233 
7234     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7235     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7236                              Index));
7237     return;
7238   }
7239   case Intrinsic::vector_extract: {
7240     SDValue Vec = getValue(I.getOperand(0));
7241     SDValue Index = getValue(I.getOperand(1));
7242     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7243 
7244     // The intrinsic's index type is i64, but the SDNode requires an index type
7245     // suitable for the target. Convert the index as required.
7246     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7247     if (Index.getValueType() != VectorIdxTy)
7248       Index = DAG.getVectorIdxConstant(
7249           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7250 
7251     setValue(&I,
7252              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7253     return;
7254   }
7255   case Intrinsic::experimental_vector_reverse:
7256     visitVectorReverse(I);
7257     return;
7258   case Intrinsic::experimental_vector_splice:
7259     visitVectorSplice(I);
7260     return;
7261   }
7262 }
7263 
7264 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7265     const ConstrainedFPIntrinsic &FPI) {
7266   SDLoc sdl = getCurSDLoc();
7267 
7268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7269   SmallVector<EVT, 4> ValueVTs;
7270   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7271   ValueVTs.push_back(MVT::Other); // Out chain
7272 
7273   // We do not need to serialize constrained FP intrinsics against
7274   // each other or against (nonvolatile) loads, so they can be
7275   // chained like loads.
7276   SDValue Chain = DAG.getRoot();
7277   SmallVector<SDValue, 4> Opers;
7278   Opers.push_back(Chain);
7279   if (FPI.isUnaryOp()) {
7280     Opers.push_back(getValue(FPI.getArgOperand(0)));
7281   } else if (FPI.isTernaryOp()) {
7282     Opers.push_back(getValue(FPI.getArgOperand(0)));
7283     Opers.push_back(getValue(FPI.getArgOperand(1)));
7284     Opers.push_back(getValue(FPI.getArgOperand(2)));
7285   } else {
7286     Opers.push_back(getValue(FPI.getArgOperand(0)));
7287     Opers.push_back(getValue(FPI.getArgOperand(1)));
7288   }
7289 
7290   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7291     assert(Result.getNode()->getNumValues() == 2);
7292 
7293     // Push node to the appropriate list so that future instructions can be
7294     // chained up correctly.
7295     SDValue OutChain = Result.getValue(1);
7296     switch (EB) {
7297     case fp::ExceptionBehavior::ebIgnore:
7298       // The only reason why ebIgnore nodes still need to be chained is that
7299       // they might depend on the current rounding mode, and therefore must
7300       // not be moved across instruction that may change that mode.
7301       [[fallthrough]];
7302     case fp::ExceptionBehavior::ebMayTrap:
7303       // These must not be moved across calls or instructions that may change
7304       // floating-point exception masks.
7305       PendingConstrainedFP.push_back(OutChain);
7306       break;
7307     case fp::ExceptionBehavior::ebStrict:
7308       // These must not be moved across calls or instructions that may change
7309       // floating-point exception masks or read floating-point exception flags.
7310       // In addition, they cannot be optimized out even if unused.
7311       PendingConstrainedFPStrict.push_back(OutChain);
7312       break;
7313     }
7314   };
7315 
7316   SDVTList VTs = DAG.getVTList(ValueVTs);
7317   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7318 
7319   SDNodeFlags Flags;
7320   if (EB == fp::ExceptionBehavior::ebIgnore)
7321     Flags.setNoFPExcept(true);
7322 
7323   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7324     Flags.copyFMF(*FPOp);
7325 
7326   unsigned Opcode;
7327   switch (FPI.getIntrinsicID()) {
7328   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7329 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7330   case Intrinsic::INTRINSIC:                                                   \
7331     Opcode = ISD::STRICT_##DAGN;                                               \
7332     break;
7333 #include "llvm/IR/ConstrainedOps.def"
7334   case Intrinsic::experimental_constrained_fmuladd: {
7335     Opcode = ISD::STRICT_FMA;
7336     // Break fmuladd into fmul and fadd.
7337     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7338         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7339                                         ValueVTs[0])) {
7340       Opers.pop_back();
7341       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7342       pushOutChain(Mul, EB);
7343       Opcode = ISD::STRICT_FADD;
7344       Opers.clear();
7345       Opers.push_back(Mul.getValue(1));
7346       Opers.push_back(Mul.getValue(0));
7347       Opers.push_back(getValue(FPI.getArgOperand(2)));
7348     }
7349     break;
7350   }
7351   }
7352 
7353   // A few strict DAG nodes carry additional operands that are not
7354   // set up by the default code above.
7355   switch (Opcode) {
7356   default: break;
7357   case ISD::STRICT_FP_ROUND:
7358     Opers.push_back(
7359         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7360     break;
7361   case ISD::STRICT_FSETCC:
7362   case ISD::STRICT_FSETCCS: {
7363     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7364     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7365     if (TM.Options.NoNaNsFPMath)
7366       Condition = getFCmpCodeWithoutNaN(Condition);
7367     Opers.push_back(DAG.getCondCode(Condition));
7368     break;
7369   }
7370   }
7371 
7372   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7373   pushOutChain(Result, EB);
7374 
7375   SDValue FPResult = Result.getValue(0);
7376   setValue(&FPI, FPResult);
7377 }
7378 
7379 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7380   Optional<unsigned> ResOPC;
7381   switch (VPIntrin.getIntrinsicID()) {
7382 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7383   case Intrinsic::VPID:                                                        \
7384     ResOPC = ISD::VPSD;                                                        \
7385     break;
7386 #include "llvm/IR/VPIntrinsics.def"
7387   }
7388 
7389   if (!ResOPC)
7390     llvm_unreachable(
7391         "Inconsistency: no SDNode available for this VPIntrinsic!");
7392 
7393   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7394       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7395     if (VPIntrin.getFastMathFlags().allowReassoc())
7396       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7397                                                 : ISD::VP_REDUCE_FMUL;
7398   }
7399 
7400   return *ResOPC;
7401 }
7402 
7403 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT,
7404                                             SmallVector<SDValue, 7> &OpValues,
7405                                             bool IsGather) {
7406   SDLoc DL = getCurSDLoc();
7407   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7408   Value *PtrOperand = VPIntrin.getArgOperand(0);
7409   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7410   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7411   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7412   SDValue LD;
7413   bool AddToChain = true;
7414   if (!IsGather) {
7415     // Do not serialize variable-length loads of constant memory with
7416     // anything.
7417     if (!Alignment)
7418       Alignment = DAG.getEVTAlign(VT);
7419     MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7420     AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7421     SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7422     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7423         MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7424         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7425     LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7426                        MMO, false /*IsExpanding */);
7427   } else {
7428     if (!Alignment)
7429       Alignment = DAG.getEVTAlign(VT.getScalarType());
7430     unsigned AS =
7431         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7432     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7433         MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7434         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7435     SDValue Base, Index, Scale;
7436     ISD::MemIndexType IndexType;
7437     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7438                                       this, VPIntrin.getParent(),
7439                                       VT.getScalarStoreSize());
7440     if (!UniformBase) {
7441       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7442       Index = getValue(PtrOperand);
7443       IndexType = ISD::SIGNED_SCALED;
7444       Scale =
7445           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7446     }
7447     EVT IdxVT = Index.getValueType();
7448     EVT EltTy = IdxVT.getVectorElementType();
7449     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7450       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7451       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7452     }
7453     LD = DAG.getGatherVP(
7454         DAG.getVTList(VT, MVT::Other), VT, DL,
7455         {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7456         IndexType);
7457   }
7458   if (AddToChain)
7459     PendingLoads.push_back(LD.getValue(1));
7460   setValue(&VPIntrin, LD);
7461 }
7462 
7463 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin,
7464                                               SmallVector<SDValue, 7> &OpValues,
7465                                               bool IsScatter) {
7466   SDLoc DL = getCurSDLoc();
7467   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7468   Value *PtrOperand = VPIntrin.getArgOperand(1);
7469   EVT VT = OpValues[0].getValueType();
7470   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7471   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7472   SDValue ST;
7473   if (!IsScatter) {
7474     if (!Alignment)
7475       Alignment = DAG.getEVTAlign(VT);
7476     SDValue Ptr = OpValues[1];
7477     SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7478     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7479         MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7480         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7481     ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7482                         OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7483                         /* IsTruncating */ false, /*IsCompressing*/ false);
7484   } else {
7485     if (!Alignment)
7486       Alignment = DAG.getEVTAlign(VT.getScalarType());
7487     unsigned AS =
7488         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7489     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7490         MachinePointerInfo(AS), MachineMemOperand::MOStore,
7491         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7492     SDValue Base, Index, Scale;
7493     ISD::MemIndexType IndexType;
7494     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7495                                       this, VPIntrin.getParent(),
7496                                       VT.getScalarStoreSize());
7497     if (!UniformBase) {
7498       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7499       Index = getValue(PtrOperand);
7500       IndexType = ISD::SIGNED_SCALED;
7501       Scale =
7502           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7503     }
7504     EVT IdxVT = Index.getValueType();
7505     EVT EltTy = IdxVT.getVectorElementType();
7506     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7507       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7508       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7509     }
7510     ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7511                           {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7512                            OpValues[2], OpValues[3]},
7513                           MMO, IndexType);
7514   }
7515   DAG.setRoot(ST);
7516   setValue(&VPIntrin, ST);
7517 }
7518 
7519 void SelectionDAGBuilder::visitVPStridedLoad(
7520     const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
7521   SDLoc DL = getCurSDLoc();
7522   Value *PtrOperand = VPIntrin.getArgOperand(0);
7523   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7524   if (!Alignment)
7525     Alignment = DAG.getEVTAlign(VT.getScalarType());
7526   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7527   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7528   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7529   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7530   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7531   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7532       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7533       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7534 
7535   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7536                                     OpValues[2], OpValues[3], MMO,
7537                                     false /*IsExpanding*/);
7538 
7539   if (AddToChain)
7540     PendingLoads.push_back(LD.getValue(1));
7541   setValue(&VPIntrin, LD);
7542 }
7543 
7544 void SelectionDAGBuilder::visitVPStridedStore(
7545     const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
7546   SDLoc DL = getCurSDLoc();
7547   Value *PtrOperand = VPIntrin.getArgOperand(1);
7548   EVT VT = OpValues[0].getValueType();
7549   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7550   if (!Alignment)
7551     Alignment = DAG.getEVTAlign(VT.getScalarType());
7552   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7553   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7554       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7555       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7556 
7557   SDValue ST = DAG.getStridedStoreVP(
7558       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7559       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7560       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7561       /*IsCompressing*/ false);
7562 
7563   DAG.setRoot(ST);
7564   setValue(&VPIntrin, ST);
7565 }
7566 
7567 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7569   SDLoc DL = getCurSDLoc();
7570 
7571   ISD::CondCode Condition;
7572   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7573   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7574   if (IsFP) {
7575     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7576     // flags, but calls that don't return floating-point types can't be
7577     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7578     Condition = getFCmpCondCode(CondCode);
7579     if (TM.Options.NoNaNsFPMath)
7580       Condition = getFCmpCodeWithoutNaN(Condition);
7581   } else {
7582     Condition = getICmpCondCode(CondCode);
7583   }
7584 
7585   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7586   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7587   // #2 is the condition code
7588   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7589   SDValue EVL = getValue(VPIntrin.getOperand(4));
7590   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7591   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7592          "Unexpected target EVL type");
7593   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7594 
7595   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7596                                                         VPIntrin.getType());
7597   setValue(&VPIntrin,
7598            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7599 }
7600 
7601 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7602     const VPIntrinsic &VPIntrin) {
7603   SDLoc DL = getCurSDLoc();
7604   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7605 
7606   auto IID = VPIntrin.getIntrinsicID();
7607 
7608   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7609     return visitVPCmp(*CmpI);
7610 
7611   SmallVector<EVT, 4> ValueVTs;
7612   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7613   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7614   SDVTList VTs = DAG.getVTList(ValueVTs);
7615 
7616   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7617 
7618   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7619   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7620          "Unexpected target EVL type");
7621 
7622   // Request operands.
7623   SmallVector<SDValue, 7> OpValues;
7624   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7625     auto Op = getValue(VPIntrin.getArgOperand(I));
7626     if (I == EVLParamPos)
7627       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7628     OpValues.push_back(Op);
7629   }
7630 
7631   switch (Opcode) {
7632   default: {
7633     SDNodeFlags SDFlags;
7634     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7635       SDFlags.copyFMF(*FPMO);
7636     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7637     setValue(&VPIntrin, Result);
7638     break;
7639   }
7640   case ISD::VP_LOAD:
7641   case ISD::VP_GATHER:
7642     visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues,
7643                       Opcode == ISD::VP_GATHER);
7644     break;
7645   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7646     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7647     break;
7648   case ISD::VP_STORE:
7649   case ISD::VP_SCATTER:
7650     visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER);
7651     break;
7652   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7653     visitVPStridedStore(VPIntrin, OpValues);
7654     break;
7655   }
7656 }
7657 
7658 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7659                                           const BasicBlock *EHPadBB,
7660                                           MCSymbol *&BeginLabel) {
7661   MachineFunction &MF = DAG.getMachineFunction();
7662   MachineModuleInfo &MMI = MF.getMMI();
7663 
7664   // Insert a label before the invoke call to mark the try range.  This can be
7665   // used to detect deletion of the invoke via the MachineModuleInfo.
7666   BeginLabel = MMI.getContext().createTempSymbol();
7667 
7668   // For SjLj, keep track of which landing pads go with which invokes
7669   // so as to maintain the ordering of pads in the LSDA.
7670   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7671   if (CallSiteIndex) {
7672     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7673     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7674 
7675     // Now that the call site is handled, stop tracking it.
7676     MMI.setCurrentCallSite(0);
7677   }
7678 
7679   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7680 }
7681 
7682 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7683                                         const BasicBlock *EHPadBB,
7684                                         MCSymbol *BeginLabel) {
7685   assert(BeginLabel && "BeginLabel should've been set");
7686 
7687   MachineFunction &MF = DAG.getMachineFunction();
7688   MachineModuleInfo &MMI = MF.getMMI();
7689 
7690   // Insert a label at the end of the invoke call to mark the try range.  This
7691   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7692   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7693   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7694 
7695   // Inform MachineModuleInfo of range.
7696   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7697   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7698   // actually use outlined funclets and their LSDA info style.
7699   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7700     assert(II && "II should've been set");
7701     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7702     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7703   } else if (!isScopedEHPersonality(Pers)) {
7704     assert(EHPadBB);
7705     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7706   }
7707 
7708   return Chain;
7709 }
7710 
7711 std::pair<SDValue, SDValue>
7712 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7713                                     const BasicBlock *EHPadBB) {
7714   MCSymbol *BeginLabel = nullptr;
7715 
7716   if (EHPadBB) {
7717     // Both PendingLoads and PendingExports must be flushed here;
7718     // this call might not return.
7719     (void)getRoot();
7720     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7721     CLI.setChain(getRoot());
7722   }
7723 
7724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7725   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7726 
7727   assert((CLI.IsTailCall || Result.second.getNode()) &&
7728          "Non-null chain expected with non-tail call!");
7729   assert((Result.second.getNode() || !Result.first.getNode()) &&
7730          "Null value expected with tail call!");
7731 
7732   if (!Result.second.getNode()) {
7733     // As a special case, a null chain means that a tail call has been emitted
7734     // and the DAG root is already updated.
7735     HasTailCall = true;
7736 
7737     // Since there's no actual continuation from this block, nothing can be
7738     // relying on us setting vregs for them.
7739     PendingExports.clear();
7740   } else {
7741     DAG.setRoot(Result.second);
7742   }
7743 
7744   if (EHPadBB) {
7745     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7746                            BeginLabel));
7747   }
7748 
7749   return Result;
7750 }
7751 
7752 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7753                                       bool isTailCall,
7754                                       bool isMustTailCall,
7755                                       const BasicBlock *EHPadBB) {
7756   auto &DL = DAG.getDataLayout();
7757   FunctionType *FTy = CB.getFunctionType();
7758   Type *RetTy = CB.getType();
7759 
7760   TargetLowering::ArgListTy Args;
7761   Args.reserve(CB.arg_size());
7762 
7763   const Value *SwiftErrorVal = nullptr;
7764   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7765 
7766   if (isTailCall) {
7767     // Avoid emitting tail calls in functions with the disable-tail-calls
7768     // attribute.
7769     auto *Caller = CB.getParent()->getParent();
7770     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7771         "true" && !isMustTailCall)
7772       isTailCall = false;
7773 
7774     // We can't tail call inside a function with a swifterror argument. Lowering
7775     // does not support this yet. It would have to move into the swifterror
7776     // register before the call.
7777     if (TLI.supportSwiftError() &&
7778         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7779       isTailCall = false;
7780   }
7781 
7782   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7783     TargetLowering::ArgListEntry Entry;
7784     const Value *V = *I;
7785 
7786     // Skip empty types
7787     if (V->getType()->isEmptyTy())
7788       continue;
7789 
7790     SDValue ArgNode = getValue(V);
7791     Entry.Node = ArgNode; Entry.Ty = V->getType();
7792 
7793     Entry.setAttributes(&CB, I - CB.arg_begin());
7794 
7795     // Use swifterror virtual register as input to the call.
7796     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7797       SwiftErrorVal = V;
7798       // We find the virtual register for the actual swifterror argument.
7799       // Instead of using the Value, we use the virtual register instead.
7800       Entry.Node =
7801           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7802                           EVT(TLI.getPointerTy(DL)));
7803     }
7804 
7805     Args.push_back(Entry);
7806 
7807     // If we have an explicit sret argument that is an Instruction, (i.e., it
7808     // might point to function-local memory), we can't meaningfully tail-call.
7809     if (Entry.IsSRet && isa<Instruction>(V))
7810       isTailCall = false;
7811   }
7812 
7813   // If call site has a cfguardtarget operand bundle, create and add an
7814   // additional ArgListEntry.
7815   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7816     TargetLowering::ArgListEntry Entry;
7817     Value *V = Bundle->Inputs[0];
7818     SDValue ArgNode = getValue(V);
7819     Entry.Node = ArgNode;
7820     Entry.Ty = V->getType();
7821     Entry.IsCFGuardTarget = true;
7822     Args.push_back(Entry);
7823   }
7824 
7825   // Check if target-independent constraints permit a tail call here.
7826   // Target-dependent constraints are checked within TLI->LowerCallTo.
7827   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7828     isTailCall = false;
7829 
7830   // Disable tail calls if there is an swifterror argument. Targets have not
7831   // been updated to support tail calls.
7832   if (TLI.supportSwiftError() && SwiftErrorVal)
7833     isTailCall = false;
7834 
7835   TargetLowering::CallLoweringInfo CLI(DAG);
7836   CLI.setDebugLoc(getCurSDLoc())
7837       .setChain(getRoot())
7838       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7839       .setTailCall(isTailCall)
7840       .setConvergent(CB.isConvergent())
7841       .setIsPreallocated(
7842           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7843   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7844 
7845   if (Result.first.getNode()) {
7846     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7847     setValue(&CB, Result.first);
7848   }
7849 
7850   // The last element of CLI.InVals has the SDValue for swifterror return.
7851   // Here we copy it to a virtual register and update SwiftErrorMap for
7852   // book-keeping.
7853   if (SwiftErrorVal && TLI.supportSwiftError()) {
7854     // Get the last element of InVals.
7855     SDValue Src = CLI.InVals.back();
7856     Register VReg =
7857         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7858     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7859     DAG.setRoot(CopyNode);
7860   }
7861 }
7862 
7863 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7864                              SelectionDAGBuilder &Builder) {
7865   // Check to see if this load can be trivially constant folded, e.g. if the
7866   // input is from a string literal.
7867   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7868     // Cast pointer to the type we really want to load.
7869     Type *LoadTy =
7870         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7871     if (LoadVT.isVector())
7872       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7873 
7874     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7875                                          PointerType::getUnqual(LoadTy));
7876 
7877     if (const Constant *LoadCst =
7878             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7879                                          LoadTy, Builder.DAG.getDataLayout()))
7880       return Builder.getValue(LoadCst);
7881   }
7882 
7883   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7884   // still constant memory, the input chain can be the entry node.
7885   SDValue Root;
7886   bool ConstantMemory = false;
7887 
7888   // Do not serialize (non-volatile) loads of constant memory with anything.
7889   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7890     Root = Builder.DAG.getEntryNode();
7891     ConstantMemory = true;
7892   } else {
7893     // Do not serialize non-volatile loads against each other.
7894     Root = Builder.DAG.getRoot();
7895   }
7896 
7897   SDValue Ptr = Builder.getValue(PtrVal);
7898   SDValue LoadVal =
7899       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7900                           MachinePointerInfo(PtrVal), Align(1));
7901 
7902   if (!ConstantMemory)
7903     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7904   return LoadVal;
7905 }
7906 
7907 /// Record the value for an instruction that produces an integer result,
7908 /// converting the type where necessary.
7909 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7910                                                   SDValue Value,
7911                                                   bool IsSigned) {
7912   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7913                                                     I.getType(), true);
7914   if (IsSigned)
7915     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7916   else
7917     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7918   setValue(&I, Value);
7919 }
7920 
7921 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7922 /// true and lower it. Otherwise return false, and it will be lowered like a
7923 /// normal call.
7924 /// The caller already checked that \p I calls the appropriate LibFunc with a
7925 /// correct prototype.
7926 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7927   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7928   const Value *Size = I.getArgOperand(2);
7929   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
7930   if (CSize && CSize->getZExtValue() == 0) {
7931     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7932                                                           I.getType(), true);
7933     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7934     return true;
7935   }
7936 
7937   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7938   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7939       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7940       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7941   if (Res.first.getNode()) {
7942     processIntegerCallValue(I, Res.first, true);
7943     PendingLoads.push_back(Res.second);
7944     return true;
7945   }
7946 
7947   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7948   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7949   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7950     return false;
7951 
7952   // If the target has a fast compare for the given size, it will return a
7953   // preferred load type for that size. Require that the load VT is legal and
7954   // that the target supports unaligned loads of that type. Otherwise, return
7955   // INVALID.
7956   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7957     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7958     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7959     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7960       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7961       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7962       // TODO: Check alignment of src and dest ptrs.
7963       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7964       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7965       if (!TLI.isTypeLegal(LVT) ||
7966           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7967           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7968         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7969     }
7970 
7971     return LVT;
7972   };
7973 
7974   // This turns into unaligned loads. We only do this if the target natively
7975   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7976   // we'll only produce a small number of byte loads.
7977   MVT LoadVT;
7978   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7979   switch (NumBitsToCompare) {
7980   default:
7981     return false;
7982   case 16:
7983     LoadVT = MVT::i16;
7984     break;
7985   case 32:
7986     LoadVT = MVT::i32;
7987     break;
7988   case 64:
7989   case 128:
7990   case 256:
7991     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7992     break;
7993   }
7994 
7995   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7996     return false;
7997 
7998   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7999   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8000 
8001   // Bitcast to a wide integer type if the loads are vectors.
8002   if (LoadVT.isVector()) {
8003     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8004     LoadL = DAG.getBitcast(CmpVT, LoadL);
8005     LoadR = DAG.getBitcast(CmpVT, LoadR);
8006   }
8007 
8008   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8009   processIntegerCallValue(I, Cmp, false);
8010   return true;
8011 }
8012 
8013 /// See if we can lower a memchr call into an optimized form. If so, return
8014 /// true and lower it. Otherwise return false, and it will be lowered like a
8015 /// normal call.
8016 /// The caller already checked that \p I calls the appropriate LibFunc with a
8017 /// correct prototype.
8018 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8019   const Value *Src = I.getArgOperand(0);
8020   const Value *Char = I.getArgOperand(1);
8021   const Value *Length = I.getArgOperand(2);
8022 
8023   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8024   std::pair<SDValue, SDValue> Res =
8025     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8026                                 getValue(Src), getValue(Char), getValue(Length),
8027                                 MachinePointerInfo(Src));
8028   if (Res.first.getNode()) {
8029     setValue(&I, Res.first);
8030     PendingLoads.push_back(Res.second);
8031     return true;
8032   }
8033 
8034   return false;
8035 }
8036 
8037 /// See if we can lower a mempcpy call into an optimized form. If so, return
8038 /// true and lower it. Otherwise return false, and it will be lowered like a
8039 /// normal call.
8040 /// The caller already checked that \p I calls the appropriate LibFunc with a
8041 /// correct prototype.
8042 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8043   SDValue Dst = getValue(I.getArgOperand(0));
8044   SDValue Src = getValue(I.getArgOperand(1));
8045   SDValue Size = getValue(I.getArgOperand(2));
8046 
8047   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8048   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8049   // DAG::getMemcpy needs Alignment to be defined.
8050   Align Alignment = std::min(DstAlign, SrcAlign);
8051 
8052   bool isVol = false;
8053   SDLoc sdl = getCurSDLoc();
8054 
8055   // In the mempcpy context we need to pass in a false value for isTailCall
8056   // because the return pointer needs to be adjusted by the size of
8057   // the copied memory.
8058   SDValue Root = isVol ? getRoot() : getMemoryRoot();
8059   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8060                              /*isTailCall=*/false,
8061                              MachinePointerInfo(I.getArgOperand(0)),
8062                              MachinePointerInfo(I.getArgOperand(1)),
8063                              I.getAAMetadata());
8064   assert(MC.getNode() != nullptr &&
8065          "** memcpy should not be lowered as TailCall in mempcpy context **");
8066   DAG.setRoot(MC);
8067 
8068   // Check if Size needs to be truncated or extended.
8069   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8070 
8071   // Adjust return pointer to point just past the last dst byte.
8072   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8073                                     Dst, Size);
8074   setValue(&I, DstPlusSize);
8075   return true;
8076 }
8077 
8078 /// See if we can lower a strcpy call into an optimized form.  If so, return
8079 /// true and lower it, otherwise return false and it will be lowered like a
8080 /// normal call.
8081 /// The caller already checked that \p I calls the appropriate LibFunc with a
8082 /// correct prototype.
8083 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8084   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8085 
8086   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8087   std::pair<SDValue, SDValue> Res =
8088     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8089                                 getValue(Arg0), getValue(Arg1),
8090                                 MachinePointerInfo(Arg0),
8091                                 MachinePointerInfo(Arg1), isStpcpy);
8092   if (Res.first.getNode()) {
8093     setValue(&I, Res.first);
8094     DAG.setRoot(Res.second);
8095     return true;
8096   }
8097 
8098   return false;
8099 }
8100 
8101 /// See if we can lower a strcmp call into an optimized form.  If so, return
8102 /// true and lower it, otherwise return false and it will be lowered like a
8103 /// normal call.
8104 /// The caller already checked that \p I calls the appropriate LibFunc with a
8105 /// correct prototype.
8106 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8107   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8108 
8109   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8110   std::pair<SDValue, SDValue> Res =
8111     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8112                                 getValue(Arg0), getValue(Arg1),
8113                                 MachinePointerInfo(Arg0),
8114                                 MachinePointerInfo(Arg1));
8115   if (Res.first.getNode()) {
8116     processIntegerCallValue(I, Res.first, true);
8117     PendingLoads.push_back(Res.second);
8118     return true;
8119   }
8120 
8121   return false;
8122 }
8123 
8124 /// See if we can lower a strlen call into an optimized form.  If so, return
8125 /// true and lower it, otherwise return false and it will be lowered like a
8126 /// normal call.
8127 /// The caller already checked that \p I calls the appropriate LibFunc with a
8128 /// correct prototype.
8129 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8130   const Value *Arg0 = I.getArgOperand(0);
8131 
8132   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8133   std::pair<SDValue, SDValue> Res =
8134     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8135                                 getValue(Arg0), MachinePointerInfo(Arg0));
8136   if (Res.first.getNode()) {
8137     processIntegerCallValue(I, Res.first, false);
8138     PendingLoads.push_back(Res.second);
8139     return true;
8140   }
8141 
8142   return false;
8143 }
8144 
8145 /// See if we can lower a strnlen call into an optimized form.  If so, return
8146 /// true and lower it, otherwise return false and it will be lowered like a
8147 /// normal call.
8148 /// The caller already checked that \p I calls the appropriate LibFunc with a
8149 /// correct prototype.
8150 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8151   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8152 
8153   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8154   std::pair<SDValue, SDValue> Res =
8155     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8156                                  getValue(Arg0), getValue(Arg1),
8157                                  MachinePointerInfo(Arg0));
8158   if (Res.first.getNode()) {
8159     processIntegerCallValue(I, Res.first, false);
8160     PendingLoads.push_back(Res.second);
8161     return true;
8162   }
8163 
8164   return false;
8165 }
8166 
8167 /// See if we can lower a unary floating-point operation into an SDNode with
8168 /// the specified Opcode.  If so, return true and lower it, otherwise return
8169 /// false and it will be lowered like a normal call.
8170 /// The caller already checked that \p I calls the appropriate LibFunc with a
8171 /// correct prototype.
8172 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8173                                               unsigned Opcode) {
8174   // We already checked this call's prototype; verify it doesn't modify errno.
8175   if (!I.onlyReadsMemory())
8176     return false;
8177 
8178   SDNodeFlags Flags;
8179   Flags.copyFMF(cast<FPMathOperator>(I));
8180 
8181   SDValue Tmp = getValue(I.getArgOperand(0));
8182   setValue(&I,
8183            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8184   return true;
8185 }
8186 
8187 /// See if we can lower a binary floating-point operation into an SDNode with
8188 /// the specified Opcode. If so, return true and lower it. Otherwise return
8189 /// false, and it will be lowered like a normal call.
8190 /// The caller already checked that \p I calls the appropriate LibFunc with a
8191 /// correct prototype.
8192 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8193                                                unsigned Opcode) {
8194   // We already checked this call's prototype; verify it doesn't modify errno.
8195   if (!I.onlyReadsMemory())
8196     return false;
8197 
8198   SDNodeFlags Flags;
8199   Flags.copyFMF(cast<FPMathOperator>(I));
8200 
8201   SDValue Tmp0 = getValue(I.getArgOperand(0));
8202   SDValue Tmp1 = getValue(I.getArgOperand(1));
8203   EVT VT = Tmp0.getValueType();
8204   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8205   return true;
8206 }
8207 
8208 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8209   // Handle inline assembly differently.
8210   if (I.isInlineAsm()) {
8211     visitInlineAsm(I);
8212     return;
8213   }
8214 
8215   if (Function *F = I.getCalledFunction()) {
8216     diagnoseDontCall(I);
8217 
8218     if (F->isDeclaration()) {
8219       // Is this an LLVM intrinsic or a target-specific intrinsic?
8220       unsigned IID = F->getIntrinsicID();
8221       if (!IID)
8222         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8223           IID = II->getIntrinsicID(F);
8224 
8225       if (IID) {
8226         visitIntrinsicCall(I, IID);
8227         return;
8228       }
8229     }
8230 
8231     // Check for well-known libc/libm calls.  If the function is internal, it
8232     // can't be a library call.  Don't do the check if marked as nobuiltin for
8233     // some reason or the call site requires strict floating point semantics.
8234     LibFunc Func;
8235     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8236         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8237         LibInfo->hasOptimizedCodeGen(Func)) {
8238       switch (Func) {
8239       default: break;
8240       case LibFunc_bcmp:
8241         if (visitMemCmpBCmpCall(I))
8242           return;
8243         break;
8244       case LibFunc_copysign:
8245       case LibFunc_copysignf:
8246       case LibFunc_copysignl:
8247         // We already checked this call's prototype; verify it doesn't modify
8248         // errno.
8249         if (I.onlyReadsMemory()) {
8250           SDValue LHS = getValue(I.getArgOperand(0));
8251           SDValue RHS = getValue(I.getArgOperand(1));
8252           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8253                                    LHS.getValueType(), LHS, RHS));
8254           return;
8255         }
8256         break;
8257       case LibFunc_fabs:
8258       case LibFunc_fabsf:
8259       case LibFunc_fabsl:
8260         if (visitUnaryFloatCall(I, ISD::FABS))
8261           return;
8262         break;
8263       case LibFunc_fmin:
8264       case LibFunc_fminf:
8265       case LibFunc_fminl:
8266         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8267           return;
8268         break;
8269       case LibFunc_fmax:
8270       case LibFunc_fmaxf:
8271       case LibFunc_fmaxl:
8272         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8273           return;
8274         break;
8275       case LibFunc_sin:
8276       case LibFunc_sinf:
8277       case LibFunc_sinl:
8278         if (visitUnaryFloatCall(I, ISD::FSIN))
8279           return;
8280         break;
8281       case LibFunc_cos:
8282       case LibFunc_cosf:
8283       case LibFunc_cosl:
8284         if (visitUnaryFloatCall(I, ISD::FCOS))
8285           return;
8286         break;
8287       case LibFunc_sqrt:
8288       case LibFunc_sqrtf:
8289       case LibFunc_sqrtl:
8290       case LibFunc_sqrt_finite:
8291       case LibFunc_sqrtf_finite:
8292       case LibFunc_sqrtl_finite:
8293         if (visitUnaryFloatCall(I, ISD::FSQRT))
8294           return;
8295         break;
8296       case LibFunc_floor:
8297       case LibFunc_floorf:
8298       case LibFunc_floorl:
8299         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8300           return;
8301         break;
8302       case LibFunc_nearbyint:
8303       case LibFunc_nearbyintf:
8304       case LibFunc_nearbyintl:
8305         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8306           return;
8307         break;
8308       case LibFunc_ceil:
8309       case LibFunc_ceilf:
8310       case LibFunc_ceill:
8311         if (visitUnaryFloatCall(I, ISD::FCEIL))
8312           return;
8313         break;
8314       case LibFunc_rint:
8315       case LibFunc_rintf:
8316       case LibFunc_rintl:
8317         if (visitUnaryFloatCall(I, ISD::FRINT))
8318           return;
8319         break;
8320       case LibFunc_round:
8321       case LibFunc_roundf:
8322       case LibFunc_roundl:
8323         if (visitUnaryFloatCall(I, ISD::FROUND))
8324           return;
8325         break;
8326       case LibFunc_trunc:
8327       case LibFunc_truncf:
8328       case LibFunc_truncl:
8329         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8330           return;
8331         break;
8332       case LibFunc_log2:
8333       case LibFunc_log2f:
8334       case LibFunc_log2l:
8335         if (visitUnaryFloatCall(I, ISD::FLOG2))
8336           return;
8337         break;
8338       case LibFunc_exp2:
8339       case LibFunc_exp2f:
8340       case LibFunc_exp2l:
8341         if (visitUnaryFloatCall(I, ISD::FEXP2))
8342           return;
8343         break;
8344       case LibFunc_memcmp:
8345         if (visitMemCmpBCmpCall(I))
8346           return;
8347         break;
8348       case LibFunc_mempcpy:
8349         if (visitMemPCpyCall(I))
8350           return;
8351         break;
8352       case LibFunc_memchr:
8353         if (visitMemChrCall(I))
8354           return;
8355         break;
8356       case LibFunc_strcpy:
8357         if (visitStrCpyCall(I, false))
8358           return;
8359         break;
8360       case LibFunc_stpcpy:
8361         if (visitStrCpyCall(I, true))
8362           return;
8363         break;
8364       case LibFunc_strcmp:
8365         if (visitStrCmpCall(I))
8366           return;
8367         break;
8368       case LibFunc_strlen:
8369         if (visitStrLenCall(I))
8370           return;
8371         break;
8372       case LibFunc_strnlen:
8373         if (visitStrNLenCall(I))
8374           return;
8375         break;
8376       }
8377     }
8378   }
8379 
8380   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8381   // have to do anything here to lower funclet bundles.
8382   // CFGuardTarget bundles are lowered in LowerCallTo.
8383   assert(!I.hasOperandBundlesOtherThan(
8384              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8385               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8386               LLVMContext::OB_clang_arc_attachedcall}) &&
8387          "Cannot lower calls with arbitrary operand bundles!");
8388 
8389   SDValue Callee = getValue(I.getCalledOperand());
8390 
8391   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8392     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8393   else
8394     // Check if we can potentially perform a tail call. More detailed checking
8395     // is be done within LowerCallTo, after more information about the call is
8396     // known.
8397     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8398 }
8399 
8400 namespace {
8401 
8402 /// AsmOperandInfo - This contains information for each constraint that we are
8403 /// lowering.
8404 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8405 public:
8406   /// CallOperand - If this is the result output operand or a clobber
8407   /// this is null, otherwise it is the incoming operand to the CallInst.
8408   /// This gets modified as the asm is processed.
8409   SDValue CallOperand;
8410 
8411   /// AssignedRegs - If this is a register or register class operand, this
8412   /// contains the set of register corresponding to the operand.
8413   RegsForValue AssignedRegs;
8414 
8415   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8416     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8417   }
8418 
8419   /// Whether or not this operand accesses memory
8420   bool hasMemory(const TargetLowering &TLI) const {
8421     // Indirect operand accesses access memory.
8422     if (isIndirect)
8423       return true;
8424 
8425     for (const auto &Code : Codes)
8426       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8427         return true;
8428 
8429     return false;
8430   }
8431 };
8432 
8433 
8434 } // end anonymous namespace
8435 
8436 /// Make sure that the output operand \p OpInfo and its corresponding input
8437 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8438 /// out).
8439 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8440                                SDISelAsmOperandInfo &MatchingOpInfo,
8441                                SelectionDAG &DAG) {
8442   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8443     return;
8444 
8445   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8446   const auto &TLI = DAG.getTargetLoweringInfo();
8447 
8448   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8449       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8450                                        OpInfo.ConstraintVT);
8451   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8452       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8453                                        MatchingOpInfo.ConstraintVT);
8454   if ((OpInfo.ConstraintVT.isInteger() !=
8455        MatchingOpInfo.ConstraintVT.isInteger()) ||
8456       (MatchRC.second != InputRC.second)) {
8457     // FIXME: error out in a more elegant fashion
8458     report_fatal_error("Unsupported asm: input constraint"
8459                        " with a matching output constraint of"
8460                        " incompatible type!");
8461   }
8462   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8463 }
8464 
8465 /// Get a direct memory input to behave well as an indirect operand.
8466 /// This may introduce stores, hence the need for a \p Chain.
8467 /// \return The (possibly updated) chain.
8468 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8469                                         SDISelAsmOperandInfo &OpInfo,
8470                                         SelectionDAG &DAG) {
8471   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8472 
8473   // If we don't have an indirect input, put it in the constpool if we can,
8474   // otherwise spill it to a stack slot.
8475   // TODO: This isn't quite right. We need to handle these according to
8476   // the addressing mode that the constraint wants. Also, this may take
8477   // an additional register for the computation and we don't want that
8478   // either.
8479 
8480   // If the operand is a float, integer, or vector constant, spill to a
8481   // constant pool entry to get its address.
8482   const Value *OpVal = OpInfo.CallOperandVal;
8483   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8484       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8485     OpInfo.CallOperand = DAG.getConstantPool(
8486         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8487     return Chain;
8488   }
8489 
8490   // Otherwise, create a stack slot and emit a store to it before the asm.
8491   Type *Ty = OpVal->getType();
8492   auto &DL = DAG.getDataLayout();
8493   uint64_t TySize = DL.getTypeAllocSize(Ty);
8494   MachineFunction &MF = DAG.getMachineFunction();
8495   int SSFI = MF.getFrameInfo().CreateStackObject(
8496       TySize, DL.getPrefTypeAlign(Ty), false);
8497   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8498   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8499                             MachinePointerInfo::getFixedStack(MF, SSFI),
8500                             TLI.getMemValueType(DL, Ty));
8501   OpInfo.CallOperand = StackSlot;
8502 
8503   return Chain;
8504 }
8505 
8506 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8507 /// specified operand.  We prefer to assign virtual registers, to allow the
8508 /// register allocator to handle the assignment process.  However, if the asm
8509 /// uses features that we can't model on machineinstrs, we have SDISel do the
8510 /// allocation.  This produces generally horrible, but correct, code.
8511 ///
8512 ///   OpInfo describes the operand
8513 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8514 static llvm::Optional<unsigned>
8515 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8516                      SDISelAsmOperandInfo &OpInfo,
8517                      SDISelAsmOperandInfo &RefOpInfo) {
8518   LLVMContext &Context = *DAG.getContext();
8519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8520 
8521   MachineFunction &MF = DAG.getMachineFunction();
8522   SmallVector<unsigned, 4> Regs;
8523   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8524 
8525   // No work to do for memory/address operands.
8526   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8527       OpInfo.ConstraintType == TargetLowering::C_Address)
8528     return None;
8529 
8530   // If this is a constraint for a single physreg, or a constraint for a
8531   // register class, find it.
8532   unsigned AssignedReg;
8533   const TargetRegisterClass *RC;
8534   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8535       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8536   // RC is unset only on failure. Return immediately.
8537   if (!RC)
8538     return None;
8539 
8540   // Get the actual register value type.  This is important, because the user
8541   // may have asked for (e.g.) the AX register in i32 type.  We need to
8542   // remember that AX is actually i16 to get the right extension.
8543   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8544 
8545   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8546     // If this is an FP operand in an integer register (or visa versa), or more
8547     // generally if the operand value disagrees with the register class we plan
8548     // to stick it in, fix the operand type.
8549     //
8550     // If this is an input value, the bitcast to the new type is done now.
8551     // Bitcast for output value is done at the end of visitInlineAsm().
8552     if ((OpInfo.Type == InlineAsm::isOutput ||
8553          OpInfo.Type == InlineAsm::isInput) &&
8554         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8555       // Try to convert to the first EVT that the reg class contains.  If the
8556       // types are identical size, use a bitcast to convert (e.g. two differing
8557       // vector types).  Note: output bitcast is done at the end of
8558       // visitInlineAsm().
8559       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8560         // Exclude indirect inputs while they are unsupported because the code
8561         // to perform the load is missing and thus OpInfo.CallOperand still
8562         // refers to the input address rather than the pointed-to value.
8563         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8564           OpInfo.CallOperand =
8565               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8566         OpInfo.ConstraintVT = RegVT;
8567         // If the operand is an FP value and we want it in integer registers,
8568         // use the corresponding integer type. This turns an f64 value into
8569         // i64, which can be passed with two i32 values on a 32-bit machine.
8570       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8571         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8572         if (OpInfo.Type == InlineAsm::isInput)
8573           OpInfo.CallOperand =
8574               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8575         OpInfo.ConstraintVT = VT;
8576       }
8577     }
8578   }
8579 
8580   // No need to allocate a matching input constraint since the constraint it's
8581   // matching to has already been allocated.
8582   if (OpInfo.isMatchingInputConstraint())
8583     return None;
8584 
8585   EVT ValueVT = OpInfo.ConstraintVT;
8586   if (OpInfo.ConstraintVT == MVT::Other)
8587     ValueVT = RegVT;
8588 
8589   // Initialize NumRegs.
8590   unsigned NumRegs = 1;
8591   if (OpInfo.ConstraintVT != MVT::Other)
8592     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8593 
8594   // If this is a constraint for a specific physical register, like {r17},
8595   // assign it now.
8596 
8597   // If this associated to a specific register, initialize iterator to correct
8598   // place. If virtual, make sure we have enough registers
8599 
8600   // Initialize iterator if necessary
8601   TargetRegisterClass::iterator I = RC->begin();
8602   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8603 
8604   // Do not check for single registers.
8605   if (AssignedReg) {
8606     I = std::find(I, RC->end(), AssignedReg);
8607     if (I == RC->end()) {
8608       // RC does not contain the selected register, which indicates a
8609       // mismatch between the register and the required type/bitwidth.
8610       return {AssignedReg};
8611     }
8612   }
8613 
8614   for (; NumRegs; --NumRegs, ++I) {
8615     assert(I != RC->end() && "Ran out of registers to allocate!");
8616     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8617     Regs.push_back(R);
8618   }
8619 
8620   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8621   return None;
8622 }
8623 
8624 static unsigned
8625 findMatchingInlineAsmOperand(unsigned OperandNo,
8626                              const std::vector<SDValue> &AsmNodeOperands) {
8627   // Scan until we find the definition we already emitted of this operand.
8628   unsigned CurOp = InlineAsm::Op_FirstOperand;
8629   for (; OperandNo; --OperandNo) {
8630     // Advance to the next operand.
8631     unsigned OpFlag =
8632         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8633     assert((InlineAsm::isRegDefKind(OpFlag) ||
8634             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8635             InlineAsm::isMemKind(OpFlag)) &&
8636            "Skipped past definitions?");
8637     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8638   }
8639   return CurOp;
8640 }
8641 
8642 namespace {
8643 
8644 class ExtraFlags {
8645   unsigned Flags = 0;
8646 
8647 public:
8648   explicit ExtraFlags(const CallBase &Call) {
8649     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8650     if (IA->hasSideEffects())
8651       Flags |= InlineAsm::Extra_HasSideEffects;
8652     if (IA->isAlignStack())
8653       Flags |= InlineAsm::Extra_IsAlignStack;
8654     if (Call.isConvergent())
8655       Flags |= InlineAsm::Extra_IsConvergent;
8656     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8657   }
8658 
8659   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8660     // Ideally, we would only check against memory constraints.  However, the
8661     // meaning of an Other constraint can be target-specific and we can't easily
8662     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8663     // for Other constraints as well.
8664     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8665         OpInfo.ConstraintType == TargetLowering::C_Other) {
8666       if (OpInfo.Type == InlineAsm::isInput)
8667         Flags |= InlineAsm::Extra_MayLoad;
8668       else if (OpInfo.Type == InlineAsm::isOutput)
8669         Flags |= InlineAsm::Extra_MayStore;
8670       else if (OpInfo.Type == InlineAsm::isClobber)
8671         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8672     }
8673   }
8674 
8675   unsigned get() const { return Flags; }
8676 };
8677 
8678 } // end anonymous namespace
8679 
8680 /// visitInlineAsm - Handle a call to an InlineAsm object.
8681 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8682                                          const BasicBlock *EHPadBB) {
8683   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8684 
8685   /// ConstraintOperands - Information about all of the constraints.
8686   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8687 
8688   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8689   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8690       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8691 
8692   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8693   // AsmDialect, MayLoad, MayStore).
8694   bool HasSideEffect = IA->hasSideEffects();
8695   ExtraFlags ExtraInfo(Call);
8696 
8697   for (auto &T : TargetConstraints) {
8698     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8699     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8700 
8701     if (OpInfo.CallOperandVal)
8702       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8703 
8704     if (!HasSideEffect)
8705       HasSideEffect = OpInfo.hasMemory(TLI);
8706 
8707     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8708     // FIXME: Could we compute this on OpInfo rather than T?
8709 
8710     // Compute the constraint code and ConstraintType to use.
8711     TLI.ComputeConstraintToUse(T, SDValue());
8712 
8713     if (T.ConstraintType == TargetLowering::C_Immediate &&
8714         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8715       // We've delayed emitting a diagnostic like the "n" constraint because
8716       // inlining could cause an integer showing up.
8717       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8718                                           "' expects an integer constant "
8719                                           "expression");
8720 
8721     ExtraInfo.update(T);
8722   }
8723 
8724   // We won't need to flush pending loads if this asm doesn't touch
8725   // memory and is nonvolatile.
8726   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8727 
8728   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8729   if (EmitEHLabels) {
8730     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8731   }
8732   bool IsCallBr = isa<CallBrInst>(Call);
8733 
8734   if (IsCallBr || EmitEHLabels) {
8735     // If this is a callbr or invoke we need to flush pending exports since
8736     // inlineasm_br and invoke are terminators.
8737     // We need to do this before nodes are glued to the inlineasm_br node.
8738     Chain = getControlRoot();
8739   }
8740 
8741   MCSymbol *BeginLabel = nullptr;
8742   if (EmitEHLabels) {
8743     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8744   }
8745 
8746   // Second pass over the constraints: compute which constraint option to use.
8747   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8748     // If this is an output operand with a matching input operand, look up the
8749     // matching input. If their types mismatch, e.g. one is an integer, the
8750     // other is floating point, or their sizes are different, flag it as an
8751     // error.
8752     if (OpInfo.hasMatchingInput()) {
8753       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8754       patchMatchingInput(OpInfo, Input, DAG);
8755     }
8756 
8757     // Compute the constraint code and ConstraintType to use.
8758     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8759 
8760     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8761          OpInfo.Type == InlineAsm::isClobber) ||
8762         OpInfo.ConstraintType == TargetLowering::C_Address)
8763       continue;
8764 
8765     // If this is a memory input, and if the operand is not indirect, do what we
8766     // need to provide an address for the memory input.
8767     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8768         !OpInfo.isIndirect) {
8769       assert((OpInfo.isMultipleAlternative ||
8770               (OpInfo.Type == InlineAsm::isInput)) &&
8771              "Can only indirectify direct input operands!");
8772 
8773       // Memory operands really want the address of the value.
8774       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8775 
8776       // There is no longer a Value* corresponding to this operand.
8777       OpInfo.CallOperandVal = nullptr;
8778 
8779       // It is now an indirect operand.
8780       OpInfo.isIndirect = true;
8781     }
8782 
8783   }
8784 
8785   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8786   std::vector<SDValue> AsmNodeOperands;
8787   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8788   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8789       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8790 
8791   // If we have a !srcloc metadata node associated with it, we want to attach
8792   // this to the ultimately generated inline asm machineinstr.  To do this, we
8793   // pass in the third operand as this (potentially null) inline asm MDNode.
8794   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8795   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8796 
8797   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8798   // bits as operand 3.
8799   AsmNodeOperands.push_back(DAG.getTargetConstant(
8800       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8801 
8802   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8803   // this, assign virtual and physical registers for inputs and otput.
8804   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8805     // Assign Registers.
8806     SDISelAsmOperandInfo &RefOpInfo =
8807         OpInfo.isMatchingInputConstraint()
8808             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8809             : OpInfo;
8810     const auto RegError =
8811         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8812     if (RegError) {
8813       const MachineFunction &MF = DAG.getMachineFunction();
8814       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8815       const char *RegName = TRI.getName(RegError.value());
8816       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8817                                    "' allocated for constraint '" +
8818                                    Twine(OpInfo.ConstraintCode) +
8819                                    "' does not match required type");
8820       return;
8821     }
8822 
8823     auto DetectWriteToReservedRegister = [&]() {
8824       const MachineFunction &MF = DAG.getMachineFunction();
8825       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8826       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8827         if (Register::isPhysicalRegister(Reg) &&
8828             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8829           const char *RegName = TRI.getName(Reg);
8830           emitInlineAsmError(Call, "write to reserved register '" +
8831                                        Twine(RegName) + "'");
8832           return true;
8833         }
8834       }
8835       return false;
8836     };
8837     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
8838             (OpInfo.Type == InlineAsm::isInput &&
8839              !OpInfo.isMatchingInputConstraint())) &&
8840            "Only address as input operand is allowed.");
8841 
8842     switch (OpInfo.Type) {
8843     case InlineAsm::isOutput:
8844       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8845         unsigned ConstraintID =
8846             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8847         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8848                "Failed to convert memory constraint code to constraint id.");
8849 
8850         // Add information to the INLINEASM node to know about this output.
8851         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8852         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8853         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8854                                                         MVT::i32));
8855         AsmNodeOperands.push_back(OpInfo.CallOperand);
8856       } else {
8857         // Otherwise, this outputs to a register (directly for C_Register /
8858         // C_RegisterClass, and a target-defined fashion for
8859         // C_Immediate/C_Other). Find a register that we can use.
8860         if (OpInfo.AssignedRegs.Regs.empty()) {
8861           emitInlineAsmError(
8862               Call, "couldn't allocate output register for constraint '" +
8863                         Twine(OpInfo.ConstraintCode) + "'");
8864           return;
8865         }
8866 
8867         if (DetectWriteToReservedRegister())
8868           return;
8869 
8870         // Add information to the INLINEASM node to know that this register is
8871         // set.
8872         OpInfo.AssignedRegs.AddInlineAsmOperands(
8873             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8874                                   : InlineAsm::Kind_RegDef,
8875             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8876       }
8877       break;
8878 
8879     case InlineAsm::isInput:
8880     case InlineAsm::isLabel: {
8881       SDValue InOperandVal = OpInfo.CallOperand;
8882 
8883       if (OpInfo.isMatchingInputConstraint()) {
8884         // If this is required to match an output register we have already set,
8885         // just use its register.
8886         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8887                                                   AsmNodeOperands);
8888         unsigned OpFlag =
8889           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8890         if (InlineAsm::isRegDefKind(OpFlag) ||
8891             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8892           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8893           if (OpInfo.isIndirect) {
8894             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8895             emitInlineAsmError(Call, "inline asm not supported yet: "
8896                                      "don't know how to handle tied "
8897                                      "indirect register inputs");
8898             return;
8899           }
8900 
8901           SmallVector<unsigned, 4> Regs;
8902           MachineFunction &MF = DAG.getMachineFunction();
8903           MachineRegisterInfo &MRI = MF.getRegInfo();
8904           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8905           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8906           Register TiedReg = R->getReg();
8907           MVT RegVT = R->getSimpleValueType(0);
8908           const TargetRegisterClass *RC =
8909               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
8910               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
8911                                       : TRI.getMinimalPhysRegClass(TiedReg);
8912           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8913           for (unsigned i = 0; i != NumRegs; ++i)
8914             Regs.push_back(MRI.createVirtualRegister(RC));
8915 
8916           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8917 
8918           SDLoc dl = getCurSDLoc();
8919           // Use the produced MatchedRegs object to
8920           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8921           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8922                                            true, OpInfo.getMatchedOperand(), dl,
8923                                            DAG, AsmNodeOperands);
8924           break;
8925         }
8926 
8927         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8928         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8929                "Unexpected number of operands");
8930         // Add information to the INLINEASM node to know about this input.
8931         // See InlineAsm.h isUseOperandTiedToDef.
8932         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8933         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8934                                                     OpInfo.getMatchedOperand());
8935         AsmNodeOperands.push_back(DAG.getTargetConstant(
8936             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8937         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8938         break;
8939       }
8940 
8941       // Treat indirect 'X' constraint as memory.
8942       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8943           OpInfo.isIndirect)
8944         OpInfo.ConstraintType = TargetLowering::C_Memory;
8945 
8946       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8947           OpInfo.ConstraintType == TargetLowering::C_Other) {
8948         std::vector<SDValue> Ops;
8949         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8950                                           Ops, DAG);
8951         if (Ops.empty()) {
8952           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8953             if (isa<ConstantSDNode>(InOperandVal)) {
8954               emitInlineAsmError(Call, "value out of range for constraint '" +
8955                                            Twine(OpInfo.ConstraintCode) + "'");
8956               return;
8957             }
8958 
8959           emitInlineAsmError(Call,
8960                              "invalid operand for inline asm constraint '" +
8961                                  Twine(OpInfo.ConstraintCode) + "'");
8962           return;
8963         }
8964 
8965         // Add information to the INLINEASM node to know about this input.
8966         unsigned ResOpType =
8967           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8968         AsmNodeOperands.push_back(DAG.getTargetConstant(
8969             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8970         llvm::append_range(AsmNodeOperands, Ops);
8971         break;
8972       }
8973 
8974       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8975           OpInfo.ConstraintType == TargetLowering::C_Address) {
8976         assert((OpInfo.isIndirect ||
8977                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
8978                "Operand must be indirect to be a mem!");
8979         assert(InOperandVal.getValueType() ==
8980                    TLI.getPointerTy(DAG.getDataLayout()) &&
8981                "Memory operands expect pointer values");
8982 
8983         unsigned ConstraintID =
8984             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8985         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8986                "Failed to convert memory constraint code to constraint id.");
8987 
8988         // Add information to the INLINEASM node to know about this input.
8989         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8990         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8991         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8992                                                         getCurSDLoc(),
8993                                                         MVT::i32));
8994         AsmNodeOperands.push_back(InOperandVal);
8995         break;
8996       }
8997 
8998       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8999               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9000              "Unknown constraint type!");
9001 
9002       // TODO: Support this.
9003       if (OpInfo.isIndirect) {
9004         emitInlineAsmError(
9005             Call, "Don't know how to handle indirect register inputs yet "
9006                   "for constraint '" +
9007                       Twine(OpInfo.ConstraintCode) + "'");
9008         return;
9009       }
9010 
9011       // Copy the input into the appropriate registers.
9012       if (OpInfo.AssignedRegs.Regs.empty()) {
9013         emitInlineAsmError(Call,
9014                            "couldn't allocate input reg for constraint '" +
9015                                Twine(OpInfo.ConstraintCode) + "'");
9016         return;
9017       }
9018 
9019       if (DetectWriteToReservedRegister())
9020         return;
9021 
9022       SDLoc dl = getCurSDLoc();
9023 
9024       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
9025                                         &Call);
9026 
9027       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9028                                                dl, DAG, AsmNodeOperands);
9029       break;
9030     }
9031     case InlineAsm::isClobber:
9032       // Add the clobbered value to the operand list, so that the register
9033       // allocator is aware that the physreg got clobbered.
9034       if (!OpInfo.AssignedRegs.Regs.empty())
9035         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9036                                                  false, 0, getCurSDLoc(), DAG,
9037                                                  AsmNodeOperands);
9038       break;
9039     }
9040   }
9041 
9042   // Finish up input operands.  Set the input chain and add the flag last.
9043   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9044   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
9045 
9046   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9047   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9048                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9049   Flag = Chain.getValue(1);
9050 
9051   // Do additional work to generate outputs.
9052 
9053   SmallVector<EVT, 1> ResultVTs;
9054   SmallVector<SDValue, 1> ResultValues;
9055   SmallVector<SDValue, 8> OutChains;
9056 
9057   llvm::Type *CallResultType = Call.getType();
9058   ArrayRef<Type *> ResultTypes;
9059   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9060     ResultTypes = StructResult->elements();
9061   else if (!CallResultType->isVoidTy())
9062     ResultTypes = makeArrayRef(CallResultType);
9063 
9064   auto CurResultType = ResultTypes.begin();
9065   auto handleRegAssign = [&](SDValue V) {
9066     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9067     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9068     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9069     ++CurResultType;
9070     // If the type of the inline asm call site return value is different but has
9071     // same size as the type of the asm output bitcast it.  One example of this
9072     // is for vectors with different width / number of elements.  This can
9073     // happen for register classes that can contain multiple different value
9074     // types.  The preg or vreg allocated may not have the same VT as was
9075     // expected.
9076     //
9077     // This can also happen for a return value that disagrees with the register
9078     // class it is put in, eg. a double in a general-purpose register on a
9079     // 32-bit machine.
9080     if (ResultVT != V.getValueType() &&
9081         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9082       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9083     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9084              V.getValueType().isInteger()) {
9085       // If a result value was tied to an input value, the computed result
9086       // may have a wider width than the expected result.  Extract the
9087       // relevant portion.
9088       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9089     }
9090     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9091     ResultVTs.push_back(ResultVT);
9092     ResultValues.push_back(V);
9093   };
9094 
9095   // Deal with output operands.
9096   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9097     if (OpInfo.Type == InlineAsm::isOutput) {
9098       SDValue Val;
9099       // Skip trivial output operands.
9100       if (OpInfo.AssignedRegs.Regs.empty())
9101         continue;
9102 
9103       switch (OpInfo.ConstraintType) {
9104       case TargetLowering::C_Register:
9105       case TargetLowering::C_RegisterClass:
9106         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9107                                                   Chain, &Flag, &Call);
9108         break;
9109       case TargetLowering::C_Immediate:
9110       case TargetLowering::C_Other:
9111         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9112                                               OpInfo, DAG);
9113         break;
9114       case TargetLowering::C_Memory:
9115         break; // Already handled.
9116       case TargetLowering::C_Address:
9117         break; // Silence warning.
9118       case TargetLowering::C_Unknown:
9119         assert(false && "Unexpected unknown constraint");
9120       }
9121 
9122       // Indirect output manifest as stores. Record output chains.
9123       if (OpInfo.isIndirect) {
9124         const Value *Ptr = OpInfo.CallOperandVal;
9125         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9126         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9127                                      MachinePointerInfo(Ptr));
9128         OutChains.push_back(Store);
9129       } else {
9130         // generate CopyFromRegs to associated registers.
9131         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9132         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9133           for (const SDValue &V : Val->op_values())
9134             handleRegAssign(V);
9135         } else
9136           handleRegAssign(Val);
9137       }
9138     }
9139   }
9140 
9141   // Set results.
9142   if (!ResultValues.empty()) {
9143     assert(CurResultType == ResultTypes.end() &&
9144            "Mismatch in number of ResultTypes");
9145     assert(ResultValues.size() == ResultTypes.size() &&
9146            "Mismatch in number of output operands in asm result");
9147 
9148     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9149                             DAG.getVTList(ResultVTs), ResultValues);
9150     setValue(&Call, V);
9151   }
9152 
9153   // Collect store chains.
9154   if (!OutChains.empty())
9155     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9156 
9157   if (EmitEHLabels) {
9158     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9159   }
9160 
9161   // Only Update Root if inline assembly has a memory effect.
9162   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9163       EmitEHLabels)
9164     DAG.setRoot(Chain);
9165 }
9166 
9167 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9168                                              const Twine &Message) {
9169   LLVMContext &Ctx = *DAG.getContext();
9170   Ctx.emitError(&Call, Message);
9171 
9172   // Make sure we leave the DAG in a valid state
9173   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9174   SmallVector<EVT, 1> ValueVTs;
9175   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9176 
9177   if (ValueVTs.empty())
9178     return;
9179 
9180   SmallVector<SDValue, 1> Ops;
9181   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9182     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9183 
9184   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9185 }
9186 
9187 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9188   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9189                           MVT::Other, getRoot(),
9190                           getValue(I.getArgOperand(0)),
9191                           DAG.getSrcValue(I.getArgOperand(0))));
9192 }
9193 
9194 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9196   const DataLayout &DL = DAG.getDataLayout();
9197   SDValue V = DAG.getVAArg(
9198       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9199       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9200       DL.getABITypeAlign(I.getType()).value());
9201   DAG.setRoot(V.getValue(1));
9202 
9203   if (I.getType()->isPointerTy())
9204     V = DAG.getPtrExtOrTrunc(
9205         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9206   setValue(&I, V);
9207 }
9208 
9209 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9210   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9211                           MVT::Other, getRoot(),
9212                           getValue(I.getArgOperand(0)),
9213                           DAG.getSrcValue(I.getArgOperand(0))));
9214 }
9215 
9216 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9217   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9218                           MVT::Other, getRoot(),
9219                           getValue(I.getArgOperand(0)),
9220                           getValue(I.getArgOperand(1)),
9221                           DAG.getSrcValue(I.getArgOperand(0)),
9222                           DAG.getSrcValue(I.getArgOperand(1))));
9223 }
9224 
9225 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9226                                                     const Instruction &I,
9227                                                     SDValue Op) {
9228   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9229   if (!Range)
9230     return Op;
9231 
9232   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9233   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9234     return Op;
9235 
9236   APInt Lo = CR.getUnsignedMin();
9237   if (!Lo.isMinValue())
9238     return Op;
9239 
9240   APInt Hi = CR.getUnsignedMax();
9241   unsigned Bits = std::max(Hi.getActiveBits(),
9242                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9243 
9244   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9245 
9246   SDLoc SL = getCurSDLoc();
9247 
9248   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9249                              DAG.getValueType(SmallVT));
9250   unsigned NumVals = Op.getNode()->getNumValues();
9251   if (NumVals == 1)
9252     return ZExt;
9253 
9254   SmallVector<SDValue, 4> Ops;
9255 
9256   Ops.push_back(ZExt);
9257   for (unsigned I = 1; I != NumVals; ++I)
9258     Ops.push_back(Op.getValue(I));
9259 
9260   return DAG.getMergeValues(Ops, SL);
9261 }
9262 
9263 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9264 /// the call being lowered.
9265 ///
9266 /// This is a helper for lowering intrinsics that follow a target calling
9267 /// convention or require stack pointer adjustment. Only a subset of the
9268 /// intrinsic's operands need to participate in the calling convention.
9269 void SelectionDAGBuilder::populateCallLoweringInfo(
9270     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9271     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9272     bool IsPatchPoint) {
9273   TargetLowering::ArgListTy Args;
9274   Args.reserve(NumArgs);
9275 
9276   // Populate the argument list.
9277   // Attributes for args start at offset 1, after the return attribute.
9278   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9279        ArgI != ArgE; ++ArgI) {
9280     const Value *V = Call->getOperand(ArgI);
9281 
9282     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9283 
9284     TargetLowering::ArgListEntry Entry;
9285     Entry.Node = getValue(V);
9286     Entry.Ty = V->getType();
9287     Entry.setAttributes(Call, ArgI);
9288     Args.push_back(Entry);
9289   }
9290 
9291   CLI.setDebugLoc(getCurSDLoc())
9292       .setChain(getRoot())
9293       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9294       .setDiscardResult(Call->use_empty())
9295       .setIsPatchPoint(IsPatchPoint)
9296       .setIsPreallocated(
9297           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9298 }
9299 
9300 /// Add a stack map intrinsic call's live variable operands to a stackmap
9301 /// or patchpoint target node's operand list.
9302 ///
9303 /// Constants are converted to TargetConstants purely as an optimization to
9304 /// avoid constant materialization and register allocation.
9305 ///
9306 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9307 /// generate addess computation nodes, and so FinalizeISel can convert the
9308 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9309 /// address materialization and register allocation, but may also be required
9310 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9311 /// alloca in the entry block, then the runtime may assume that the alloca's
9312 /// StackMap location can be read immediately after compilation and that the
9313 /// location is valid at any point during execution (this is similar to the
9314 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9315 /// only available in a register, then the runtime would need to trap when
9316 /// execution reaches the StackMap in order to read the alloca's location.
9317 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9318                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9319                                 SelectionDAGBuilder &Builder) {
9320   SelectionDAG &DAG = Builder.DAG;
9321   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9322     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9323 
9324     // Things on the stack are pointer-typed, meaning that they are already
9325     // legal and can be emitted directly to target nodes.
9326     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9327       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9328     } else {
9329       // Otherwise emit a target independent node to be legalised.
9330       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9331     }
9332   }
9333 }
9334 
9335 /// Lower llvm.experimental.stackmap.
9336 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9337   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9338   //                                  [live variables...])
9339 
9340   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9341 
9342   SDValue Chain, InFlag, Callee, NullPtr;
9343   SmallVector<SDValue, 32> Ops;
9344 
9345   SDLoc DL = getCurSDLoc();
9346   Callee = getValue(CI.getCalledOperand());
9347   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9348 
9349   // The stackmap intrinsic only records the live variables (the arguments
9350   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9351   // intrinsic, this won't be lowered to a function call. This means we don't
9352   // have to worry about calling conventions and target specific lowering code.
9353   // Instead we perform the call lowering right here.
9354   //
9355   // chain, flag = CALLSEQ_START(chain, 0, 0)
9356   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9357   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9358   //
9359   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9360   InFlag = Chain.getValue(1);
9361 
9362   // Add the STACKMAP operands, starting with DAG house-keeping.
9363   Ops.push_back(Chain);
9364   Ops.push_back(InFlag);
9365 
9366   // Add the <id>, <numShadowBytes> operands.
9367   //
9368   // These do not require legalisation, and can be emitted directly to target
9369   // constant nodes.
9370   SDValue ID = getValue(CI.getArgOperand(0));
9371   assert(ID.getValueType() == MVT::i64);
9372   SDValue IDConst = DAG.getTargetConstant(
9373       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9374   Ops.push_back(IDConst);
9375 
9376   SDValue Shad = getValue(CI.getArgOperand(1));
9377   assert(Shad.getValueType() == MVT::i32);
9378   SDValue ShadConst = DAG.getTargetConstant(
9379       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9380   Ops.push_back(ShadConst);
9381 
9382   // Add the live variables.
9383   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9384 
9385   // Create the STACKMAP node.
9386   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9387   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9388   InFlag = Chain.getValue(1);
9389 
9390   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9391 
9392   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9393 
9394   // Set the root to the target-lowered call chain.
9395   DAG.setRoot(Chain);
9396 
9397   // Inform the Frame Information that we have a stackmap in this function.
9398   FuncInfo.MF->getFrameInfo().setHasStackMap();
9399 }
9400 
9401 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9402 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9403                                           const BasicBlock *EHPadBB) {
9404   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9405   //                                                 i32 <numBytes>,
9406   //                                                 i8* <target>,
9407   //                                                 i32 <numArgs>,
9408   //                                                 [Args...],
9409   //                                                 [live variables...])
9410 
9411   CallingConv::ID CC = CB.getCallingConv();
9412   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9413   bool HasDef = !CB.getType()->isVoidTy();
9414   SDLoc dl = getCurSDLoc();
9415   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9416 
9417   // Handle immediate and symbolic callees.
9418   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9419     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9420                                    /*isTarget=*/true);
9421   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9422     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9423                                          SDLoc(SymbolicCallee),
9424                                          SymbolicCallee->getValueType(0));
9425 
9426   // Get the real number of arguments participating in the call <numArgs>
9427   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9428   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9429 
9430   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9431   // Intrinsics include all meta-operands up to but not including CC.
9432   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9433   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9434          "Not enough arguments provided to the patchpoint intrinsic");
9435 
9436   // For AnyRegCC the arguments are lowered later on manually.
9437   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9438   Type *ReturnTy =
9439       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9440 
9441   TargetLowering::CallLoweringInfo CLI(DAG);
9442   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9443                            ReturnTy, true);
9444   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9445 
9446   SDNode *CallEnd = Result.second.getNode();
9447   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9448     CallEnd = CallEnd->getOperand(0).getNode();
9449 
9450   /// Get a call instruction from the call sequence chain.
9451   /// Tail calls are not allowed.
9452   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9453          "Expected a callseq node.");
9454   SDNode *Call = CallEnd->getOperand(0).getNode();
9455   bool HasGlue = Call->getGluedNode();
9456 
9457   // Replace the target specific call node with the patchable intrinsic.
9458   SmallVector<SDValue, 8> Ops;
9459 
9460   // Push the chain.
9461   Ops.push_back(*(Call->op_begin()));
9462 
9463   // Optionally, push the glue (if any).
9464   if (HasGlue)
9465     Ops.push_back(*(Call->op_end() - 1));
9466 
9467   // Push the register mask info.
9468   if (HasGlue)
9469     Ops.push_back(*(Call->op_end() - 2));
9470   else
9471     Ops.push_back(*(Call->op_end() - 1));
9472 
9473   // Add the <id> and <numBytes> constants.
9474   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9475   Ops.push_back(DAG.getTargetConstant(
9476                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9477   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9478   Ops.push_back(DAG.getTargetConstant(
9479                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9480                   MVT::i32));
9481 
9482   // Add the callee.
9483   Ops.push_back(Callee);
9484 
9485   // Adjust <numArgs> to account for any arguments that have been passed on the
9486   // stack instead.
9487   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9488   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9489   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9490   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9491 
9492   // Add the calling convention
9493   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9494 
9495   // Add the arguments we omitted previously. The register allocator should
9496   // place these in any free register.
9497   if (IsAnyRegCC)
9498     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9499       Ops.push_back(getValue(CB.getArgOperand(i)));
9500 
9501   // Push the arguments from the call instruction.
9502   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9503   Ops.append(Call->op_begin() + 2, e);
9504 
9505   // Push live variables for the stack map.
9506   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9507 
9508   SDVTList NodeTys;
9509   if (IsAnyRegCC && HasDef) {
9510     // Create the return types based on the intrinsic definition
9511     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9512     SmallVector<EVT, 3> ValueVTs;
9513     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9514     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9515 
9516     // There is always a chain and a glue type at the end
9517     ValueVTs.push_back(MVT::Other);
9518     ValueVTs.push_back(MVT::Glue);
9519     NodeTys = DAG.getVTList(ValueVTs);
9520   } else
9521     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9522 
9523   // Replace the target specific call node with a PATCHPOINT node.
9524   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9525 
9526   // Update the NodeMap.
9527   if (HasDef) {
9528     if (IsAnyRegCC)
9529       setValue(&CB, SDValue(PPV.getNode(), 0));
9530     else
9531       setValue(&CB, Result.first);
9532   }
9533 
9534   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9535   // call sequence. Furthermore the location of the chain and glue can change
9536   // when the AnyReg calling convention is used and the intrinsic returns a
9537   // value.
9538   if (IsAnyRegCC && HasDef) {
9539     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9540     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9541     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9542   } else
9543     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9544   DAG.DeleteNode(Call);
9545 
9546   // Inform the Frame Information that we have a patchpoint in this function.
9547   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9548 }
9549 
9550 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9551                                             unsigned Intrinsic) {
9552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9553   SDValue Op1 = getValue(I.getArgOperand(0));
9554   SDValue Op2;
9555   if (I.arg_size() > 1)
9556     Op2 = getValue(I.getArgOperand(1));
9557   SDLoc dl = getCurSDLoc();
9558   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9559   SDValue Res;
9560   SDNodeFlags SDFlags;
9561   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9562     SDFlags.copyFMF(*FPMO);
9563 
9564   switch (Intrinsic) {
9565   case Intrinsic::vector_reduce_fadd:
9566     if (SDFlags.hasAllowReassociation())
9567       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9568                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9569                         SDFlags);
9570     else
9571       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9572     break;
9573   case Intrinsic::vector_reduce_fmul:
9574     if (SDFlags.hasAllowReassociation())
9575       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9576                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9577                         SDFlags);
9578     else
9579       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9580     break;
9581   case Intrinsic::vector_reduce_add:
9582     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9583     break;
9584   case Intrinsic::vector_reduce_mul:
9585     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9586     break;
9587   case Intrinsic::vector_reduce_and:
9588     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9589     break;
9590   case Intrinsic::vector_reduce_or:
9591     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9592     break;
9593   case Intrinsic::vector_reduce_xor:
9594     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9595     break;
9596   case Intrinsic::vector_reduce_smax:
9597     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9598     break;
9599   case Intrinsic::vector_reduce_smin:
9600     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9601     break;
9602   case Intrinsic::vector_reduce_umax:
9603     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9604     break;
9605   case Intrinsic::vector_reduce_umin:
9606     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9607     break;
9608   case Intrinsic::vector_reduce_fmax:
9609     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9610     break;
9611   case Intrinsic::vector_reduce_fmin:
9612     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9613     break;
9614   default:
9615     llvm_unreachable("Unhandled vector reduce intrinsic");
9616   }
9617   setValue(&I, Res);
9618 }
9619 
9620 /// Returns an AttributeList representing the attributes applied to the return
9621 /// value of the given call.
9622 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9623   SmallVector<Attribute::AttrKind, 2> Attrs;
9624   if (CLI.RetSExt)
9625     Attrs.push_back(Attribute::SExt);
9626   if (CLI.RetZExt)
9627     Attrs.push_back(Attribute::ZExt);
9628   if (CLI.IsInReg)
9629     Attrs.push_back(Attribute::InReg);
9630 
9631   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9632                             Attrs);
9633 }
9634 
9635 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9636 /// implementation, which just calls LowerCall.
9637 /// FIXME: When all targets are
9638 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9639 std::pair<SDValue, SDValue>
9640 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9641   // Handle the incoming return values from the call.
9642   CLI.Ins.clear();
9643   Type *OrigRetTy = CLI.RetTy;
9644   SmallVector<EVT, 4> RetTys;
9645   SmallVector<uint64_t, 4> Offsets;
9646   auto &DL = CLI.DAG.getDataLayout();
9647   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9648 
9649   if (CLI.IsPostTypeLegalization) {
9650     // If we are lowering a libcall after legalization, split the return type.
9651     SmallVector<EVT, 4> OldRetTys;
9652     SmallVector<uint64_t, 4> OldOffsets;
9653     RetTys.swap(OldRetTys);
9654     Offsets.swap(OldOffsets);
9655 
9656     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9657       EVT RetVT = OldRetTys[i];
9658       uint64_t Offset = OldOffsets[i];
9659       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9660       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9661       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9662       RetTys.append(NumRegs, RegisterVT);
9663       for (unsigned j = 0; j != NumRegs; ++j)
9664         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9665     }
9666   }
9667 
9668   SmallVector<ISD::OutputArg, 4> Outs;
9669   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9670 
9671   bool CanLowerReturn =
9672       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9673                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9674 
9675   SDValue DemoteStackSlot;
9676   int DemoteStackIdx = -100;
9677   if (!CanLowerReturn) {
9678     // FIXME: equivalent assert?
9679     // assert(!CS.hasInAllocaArgument() &&
9680     //        "sret demotion is incompatible with inalloca");
9681     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9682     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9683     MachineFunction &MF = CLI.DAG.getMachineFunction();
9684     DemoteStackIdx =
9685         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9686     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9687                                               DL.getAllocaAddrSpace());
9688 
9689     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9690     ArgListEntry Entry;
9691     Entry.Node = DemoteStackSlot;
9692     Entry.Ty = StackSlotPtrType;
9693     Entry.IsSExt = false;
9694     Entry.IsZExt = false;
9695     Entry.IsInReg = false;
9696     Entry.IsSRet = true;
9697     Entry.IsNest = false;
9698     Entry.IsByVal = false;
9699     Entry.IsByRef = false;
9700     Entry.IsReturned = false;
9701     Entry.IsSwiftSelf = false;
9702     Entry.IsSwiftAsync = false;
9703     Entry.IsSwiftError = false;
9704     Entry.IsCFGuardTarget = false;
9705     Entry.Alignment = Alignment;
9706     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9707     CLI.NumFixedArgs += 1;
9708     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9709 
9710     // sret demotion isn't compatible with tail-calls, since the sret argument
9711     // points into the callers stack frame.
9712     CLI.IsTailCall = false;
9713   } else {
9714     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9715         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9716     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9717       ISD::ArgFlagsTy Flags;
9718       if (NeedsRegBlock) {
9719         Flags.setInConsecutiveRegs();
9720         if (I == RetTys.size() - 1)
9721           Flags.setInConsecutiveRegsLast();
9722       }
9723       EVT VT = RetTys[I];
9724       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9725                                                      CLI.CallConv, VT);
9726       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9727                                                        CLI.CallConv, VT);
9728       for (unsigned i = 0; i != NumRegs; ++i) {
9729         ISD::InputArg MyFlags;
9730         MyFlags.Flags = Flags;
9731         MyFlags.VT = RegisterVT;
9732         MyFlags.ArgVT = VT;
9733         MyFlags.Used = CLI.IsReturnValueUsed;
9734         if (CLI.RetTy->isPointerTy()) {
9735           MyFlags.Flags.setPointer();
9736           MyFlags.Flags.setPointerAddrSpace(
9737               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9738         }
9739         if (CLI.RetSExt)
9740           MyFlags.Flags.setSExt();
9741         if (CLI.RetZExt)
9742           MyFlags.Flags.setZExt();
9743         if (CLI.IsInReg)
9744           MyFlags.Flags.setInReg();
9745         CLI.Ins.push_back(MyFlags);
9746       }
9747     }
9748   }
9749 
9750   // We push in swifterror return as the last element of CLI.Ins.
9751   ArgListTy &Args = CLI.getArgs();
9752   if (supportSwiftError()) {
9753     for (const ArgListEntry &Arg : Args) {
9754       if (Arg.IsSwiftError) {
9755         ISD::InputArg MyFlags;
9756         MyFlags.VT = getPointerTy(DL);
9757         MyFlags.ArgVT = EVT(getPointerTy(DL));
9758         MyFlags.Flags.setSwiftError();
9759         CLI.Ins.push_back(MyFlags);
9760       }
9761     }
9762   }
9763 
9764   // Handle all of the outgoing arguments.
9765   CLI.Outs.clear();
9766   CLI.OutVals.clear();
9767   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9768     SmallVector<EVT, 4> ValueVTs;
9769     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9770     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9771     Type *FinalType = Args[i].Ty;
9772     if (Args[i].IsByVal)
9773       FinalType = Args[i].IndirectType;
9774     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9775         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9776     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9777          ++Value) {
9778       EVT VT = ValueVTs[Value];
9779       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9780       SDValue Op = SDValue(Args[i].Node.getNode(),
9781                            Args[i].Node.getResNo() + Value);
9782       ISD::ArgFlagsTy Flags;
9783 
9784       // Certain targets (such as MIPS), may have a different ABI alignment
9785       // for a type depending on the context. Give the target a chance to
9786       // specify the alignment it wants.
9787       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9788       Flags.setOrigAlign(OriginalAlignment);
9789 
9790       if (Args[i].Ty->isPointerTy()) {
9791         Flags.setPointer();
9792         Flags.setPointerAddrSpace(
9793             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9794       }
9795       if (Args[i].IsZExt)
9796         Flags.setZExt();
9797       if (Args[i].IsSExt)
9798         Flags.setSExt();
9799       if (Args[i].IsInReg) {
9800         // If we are using vectorcall calling convention, a structure that is
9801         // passed InReg - is surely an HVA
9802         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9803             isa<StructType>(FinalType)) {
9804           // The first value of a structure is marked
9805           if (0 == Value)
9806             Flags.setHvaStart();
9807           Flags.setHva();
9808         }
9809         // Set InReg Flag
9810         Flags.setInReg();
9811       }
9812       if (Args[i].IsSRet)
9813         Flags.setSRet();
9814       if (Args[i].IsSwiftSelf)
9815         Flags.setSwiftSelf();
9816       if (Args[i].IsSwiftAsync)
9817         Flags.setSwiftAsync();
9818       if (Args[i].IsSwiftError)
9819         Flags.setSwiftError();
9820       if (Args[i].IsCFGuardTarget)
9821         Flags.setCFGuardTarget();
9822       if (Args[i].IsByVal)
9823         Flags.setByVal();
9824       if (Args[i].IsByRef)
9825         Flags.setByRef();
9826       if (Args[i].IsPreallocated) {
9827         Flags.setPreallocated();
9828         // Set the byval flag for CCAssignFn callbacks that don't know about
9829         // preallocated.  This way we can know how many bytes we should've
9830         // allocated and how many bytes a callee cleanup function will pop.  If
9831         // we port preallocated to more targets, we'll have to add custom
9832         // preallocated handling in the various CC lowering callbacks.
9833         Flags.setByVal();
9834       }
9835       if (Args[i].IsInAlloca) {
9836         Flags.setInAlloca();
9837         // Set the byval flag for CCAssignFn callbacks that don't know about
9838         // inalloca.  This way we can know how many bytes we should've allocated
9839         // and how many bytes a callee cleanup function will pop.  If we port
9840         // inalloca to more targets, we'll have to add custom inalloca handling
9841         // in the various CC lowering callbacks.
9842         Flags.setByVal();
9843       }
9844       Align MemAlign;
9845       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9846         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9847         Flags.setByValSize(FrameSize);
9848 
9849         // info is not there but there are cases it cannot get right.
9850         if (auto MA = Args[i].Alignment)
9851           MemAlign = *MA;
9852         else
9853           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9854       } else if (auto MA = Args[i].Alignment) {
9855         MemAlign = *MA;
9856       } else {
9857         MemAlign = OriginalAlignment;
9858       }
9859       Flags.setMemAlign(MemAlign);
9860       if (Args[i].IsNest)
9861         Flags.setNest();
9862       if (NeedsRegBlock)
9863         Flags.setInConsecutiveRegs();
9864 
9865       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9866                                                  CLI.CallConv, VT);
9867       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9868                                                         CLI.CallConv, VT);
9869       SmallVector<SDValue, 4> Parts(NumParts);
9870       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9871 
9872       if (Args[i].IsSExt)
9873         ExtendKind = ISD::SIGN_EXTEND;
9874       else if (Args[i].IsZExt)
9875         ExtendKind = ISD::ZERO_EXTEND;
9876 
9877       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9878       // for now.
9879       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9880           CanLowerReturn) {
9881         assert((CLI.RetTy == Args[i].Ty ||
9882                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9883                  CLI.RetTy->getPointerAddressSpace() ==
9884                      Args[i].Ty->getPointerAddressSpace())) &&
9885                RetTys.size() == NumValues && "unexpected use of 'returned'");
9886         // Before passing 'returned' to the target lowering code, ensure that
9887         // either the register MVT and the actual EVT are the same size or that
9888         // the return value and argument are extended in the same way; in these
9889         // cases it's safe to pass the argument register value unchanged as the
9890         // return register value (although it's at the target's option whether
9891         // to do so)
9892         // TODO: allow code generation to take advantage of partially preserved
9893         // registers rather than clobbering the entire register when the
9894         // parameter extension method is not compatible with the return
9895         // extension method
9896         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9897             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9898              CLI.RetZExt == Args[i].IsZExt))
9899           Flags.setReturned();
9900       }
9901 
9902       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9903                      CLI.CallConv, ExtendKind);
9904 
9905       for (unsigned j = 0; j != NumParts; ++j) {
9906         // if it isn't first piece, alignment must be 1
9907         // For scalable vectors the scalable part is currently handled
9908         // by individual targets, so we just use the known minimum size here.
9909         ISD::OutputArg MyFlags(
9910             Flags, Parts[j].getValueType().getSimpleVT(), VT,
9911             i < CLI.NumFixedArgs, i,
9912             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
9913         if (NumParts > 1 && j == 0)
9914           MyFlags.Flags.setSplit();
9915         else if (j != 0) {
9916           MyFlags.Flags.setOrigAlign(Align(1));
9917           if (j == NumParts - 1)
9918             MyFlags.Flags.setSplitEnd();
9919         }
9920 
9921         CLI.Outs.push_back(MyFlags);
9922         CLI.OutVals.push_back(Parts[j]);
9923       }
9924 
9925       if (NeedsRegBlock && Value == NumValues - 1)
9926         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9927     }
9928   }
9929 
9930   SmallVector<SDValue, 4> InVals;
9931   CLI.Chain = LowerCall(CLI, InVals);
9932 
9933   // Update CLI.InVals to use outside of this function.
9934   CLI.InVals = InVals;
9935 
9936   // Verify that the target's LowerCall behaved as expected.
9937   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9938          "LowerCall didn't return a valid chain!");
9939   assert((!CLI.IsTailCall || InVals.empty()) &&
9940          "LowerCall emitted a return value for a tail call!");
9941   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9942          "LowerCall didn't emit the correct number of values!");
9943 
9944   // For a tail call, the return value is merely live-out and there aren't
9945   // any nodes in the DAG representing it. Return a special value to
9946   // indicate that a tail call has been emitted and no more Instructions
9947   // should be processed in the current block.
9948   if (CLI.IsTailCall) {
9949     CLI.DAG.setRoot(CLI.Chain);
9950     return std::make_pair(SDValue(), SDValue());
9951   }
9952 
9953 #ifndef NDEBUG
9954   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9955     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9956     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9957            "LowerCall emitted a value with the wrong type!");
9958   }
9959 #endif
9960 
9961   SmallVector<SDValue, 4> ReturnValues;
9962   if (!CanLowerReturn) {
9963     // The instruction result is the result of loading from the
9964     // hidden sret parameter.
9965     SmallVector<EVT, 1> PVTs;
9966     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9967 
9968     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9969     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9970     EVT PtrVT = PVTs[0];
9971 
9972     unsigned NumValues = RetTys.size();
9973     ReturnValues.resize(NumValues);
9974     SmallVector<SDValue, 4> Chains(NumValues);
9975 
9976     // An aggregate return value cannot wrap around the address space, so
9977     // offsets to its parts don't wrap either.
9978     SDNodeFlags Flags;
9979     Flags.setNoUnsignedWrap(true);
9980 
9981     MachineFunction &MF = CLI.DAG.getMachineFunction();
9982     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9983     for (unsigned i = 0; i < NumValues; ++i) {
9984       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9985                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9986                                                         PtrVT), Flags);
9987       SDValue L = CLI.DAG.getLoad(
9988           RetTys[i], CLI.DL, CLI.Chain, Add,
9989           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9990                                             DemoteStackIdx, Offsets[i]),
9991           HiddenSRetAlign);
9992       ReturnValues[i] = L;
9993       Chains[i] = L.getValue(1);
9994     }
9995 
9996     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9997   } else {
9998     // Collect the legal value parts into potentially illegal values
9999     // that correspond to the original function's return values.
10000     Optional<ISD::NodeType> AssertOp;
10001     if (CLI.RetSExt)
10002       AssertOp = ISD::AssertSext;
10003     else if (CLI.RetZExt)
10004       AssertOp = ISD::AssertZext;
10005     unsigned CurReg = 0;
10006     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10007       EVT VT = RetTys[I];
10008       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10009                                                      CLI.CallConv, VT);
10010       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10011                                                        CLI.CallConv, VT);
10012 
10013       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10014                                               NumRegs, RegisterVT, VT, nullptr,
10015                                               CLI.CallConv, AssertOp));
10016       CurReg += NumRegs;
10017     }
10018 
10019     // For a function returning void, there is no return value. We can't create
10020     // such a node, so we just return a null return value in that case. In
10021     // that case, nothing will actually look at the value.
10022     if (ReturnValues.empty())
10023       return std::make_pair(SDValue(), CLI.Chain);
10024   }
10025 
10026   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10027                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10028   return std::make_pair(Res, CLI.Chain);
10029 }
10030 
10031 /// Places new result values for the node in Results (their number
10032 /// and types must exactly match those of the original return values of
10033 /// the node), or leaves Results empty, which indicates that the node is not
10034 /// to be custom lowered after all.
10035 void TargetLowering::LowerOperationWrapper(SDNode *N,
10036                                            SmallVectorImpl<SDValue> &Results,
10037                                            SelectionDAG &DAG) const {
10038   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10039 
10040   if (!Res.getNode())
10041     return;
10042 
10043   // If the original node has one result, take the return value from
10044   // LowerOperation as is. It might not be result number 0.
10045   if (N->getNumValues() == 1) {
10046     Results.push_back(Res);
10047     return;
10048   }
10049 
10050   // If the original node has multiple results, then the return node should
10051   // have the same number of results.
10052   assert((N->getNumValues() == Res->getNumValues()) &&
10053       "Lowering returned the wrong number of results!");
10054 
10055   // Places new result values base on N result number.
10056   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10057     Results.push_back(Res.getValue(I));
10058 }
10059 
10060 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10061   llvm_unreachable("LowerOperation not implemented for this target!");
10062 }
10063 
10064 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10065                                                      unsigned Reg,
10066                                                      ISD::NodeType ExtendType) {
10067   SDValue Op = getNonRegisterValue(V);
10068   assert((Op.getOpcode() != ISD::CopyFromReg ||
10069           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10070          "Copy from a reg to the same reg!");
10071   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10072 
10073   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10074   // If this is an InlineAsm we have to match the registers required, not the
10075   // notional registers required by the type.
10076 
10077   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10078                    None); // This is not an ABI copy.
10079   SDValue Chain = DAG.getEntryNode();
10080 
10081   if (ExtendType == ISD::ANY_EXTEND) {
10082     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10083     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10084       ExtendType = PreferredExtendIt->second;
10085   }
10086   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10087   PendingExports.push_back(Chain);
10088 }
10089 
10090 #include "llvm/CodeGen/SelectionDAGISel.h"
10091 
10092 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10093 /// entry block, return true.  This includes arguments used by switches, since
10094 /// the switch may expand into multiple basic blocks.
10095 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10096   // With FastISel active, we may be splitting blocks, so force creation
10097   // of virtual registers for all non-dead arguments.
10098   if (FastISel)
10099     return A->use_empty();
10100 
10101   const BasicBlock &Entry = A->getParent()->front();
10102   for (const User *U : A->users())
10103     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10104       return false;  // Use not in entry block.
10105 
10106   return true;
10107 }
10108 
10109 using ArgCopyElisionMapTy =
10110     DenseMap<const Argument *,
10111              std::pair<const AllocaInst *, const StoreInst *>>;
10112 
10113 /// Scan the entry block of the function in FuncInfo for arguments that look
10114 /// like copies into a local alloca. Record any copied arguments in
10115 /// ArgCopyElisionCandidates.
10116 static void
10117 findArgumentCopyElisionCandidates(const DataLayout &DL,
10118                                   FunctionLoweringInfo *FuncInfo,
10119                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10120   // Record the state of every static alloca used in the entry block. Argument
10121   // allocas are all used in the entry block, so we need approximately as many
10122   // entries as we have arguments.
10123   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10124   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10125   unsigned NumArgs = FuncInfo->Fn->arg_size();
10126   StaticAllocas.reserve(NumArgs * 2);
10127 
10128   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10129     if (!V)
10130       return nullptr;
10131     V = V->stripPointerCasts();
10132     const auto *AI = dyn_cast<AllocaInst>(V);
10133     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10134       return nullptr;
10135     auto Iter = StaticAllocas.insert({AI, Unknown});
10136     return &Iter.first->second;
10137   };
10138 
10139   // Look for stores of arguments to static allocas. Look through bitcasts and
10140   // GEPs to handle type coercions, as long as the alloca is fully initialized
10141   // by the store. Any non-store use of an alloca escapes it and any subsequent
10142   // unanalyzed store might write it.
10143   // FIXME: Handle structs initialized with multiple stores.
10144   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10145     // Look for stores, and handle non-store uses conservatively.
10146     const auto *SI = dyn_cast<StoreInst>(&I);
10147     if (!SI) {
10148       // We will look through cast uses, so ignore them completely.
10149       if (I.isCast())
10150         continue;
10151       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10152       // to allocas.
10153       if (I.isDebugOrPseudoInst())
10154         continue;
10155       // This is an unknown instruction. Assume it escapes or writes to all
10156       // static alloca operands.
10157       for (const Use &U : I.operands()) {
10158         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10159           *Info = StaticAllocaInfo::Clobbered;
10160       }
10161       continue;
10162     }
10163 
10164     // If the stored value is a static alloca, mark it as escaped.
10165     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10166       *Info = StaticAllocaInfo::Clobbered;
10167 
10168     // Check if the destination is a static alloca.
10169     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10170     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10171     if (!Info)
10172       continue;
10173     const AllocaInst *AI = cast<AllocaInst>(Dst);
10174 
10175     // Skip allocas that have been initialized or clobbered.
10176     if (*Info != StaticAllocaInfo::Unknown)
10177       continue;
10178 
10179     // Check if the stored value is an argument, and that this store fully
10180     // initializes the alloca.
10181     // If the argument type has padding bits we can't directly forward a pointer
10182     // as the upper bits may contain garbage.
10183     // Don't elide copies from the same argument twice.
10184     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10185     const auto *Arg = dyn_cast<Argument>(Val);
10186     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10187         Arg->getType()->isEmptyTy() ||
10188         DL.getTypeStoreSize(Arg->getType()) !=
10189             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10190         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10191         ArgCopyElisionCandidates.count(Arg)) {
10192       *Info = StaticAllocaInfo::Clobbered;
10193       continue;
10194     }
10195 
10196     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10197                       << '\n');
10198 
10199     // Mark this alloca and store for argument copy elision.
10200     *Info = StaticAllocaInfo::Elidable;
10201     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10202 
10203     // Stop scanning if we've seen all arguments. This will happen early in -O0
10204     // builds, which is useful, because -O0 builds have large entry blocks and
10205     // many allocas.
10206     if (ArgCopyElisionCandidates.size() == NumArgs)
10207       break;
10208   }
10209 }
10210 
10211 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10212 /// ArgVal is a load from a suitable fixed stack object.
10213 static void tryToElideArgumentCopy(
10214     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10215     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10216     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10217     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10218     SDValue ArgVal, bool &ArgHasUses) {
10219   // Check if this is a load from a fixed stack object.
10220   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10221   if (!LNode)
10222     return;
10223   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10224   if (!FINode)
10225     return;
10226 
10227   // Check that the fixed stack object is the right size and alignment.
10228   // Look at the alignment that the user wrote on the alloca instead of looking
10229   // at the stack object.
10230   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10231   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10232   const AllocaInst *AI = ArgCopyIter->second.first;
10233   int FixedIndex = FINode->getIndex();
10234   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10235   int OldIndex = AllocaIndex;
10236   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10237   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10238     LLVM_DEBUG(
10239         dbgs() << "  argument copy elision failed due to bad fixed stack "
10240                   "object size\n");
10241     return;
10242   }
10243   Align RequiredAlignment = AI->getAlign();
10244   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10245     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10246                          "greater than stack argument alignment ("
10247                       << DebugStr(RequiredAlignment) << " vs "
10248                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10249     return;
10250   }
10251 
10252   // Perform the elision. Delete the old stack object and replace its only use
10253   // in the variable info map. Mark the stack object as mutable.
10254   LLVM_DEBUG({
10255     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10256            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10257            << '\n';
10258   });
10259   MFI.RemoveStackObject(OldIndex);
10260   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10261   AllocaIndex = FixedIndex;
10262   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10263   Chains.push_back(ArgVal.getValue(1));
10264 
10265   // Avoid emitting code for the store implementing the copy.
10266   const StoreInst *SI = ArgCopyIter->second.second;
10267   ElidedArgCopyInstrs.insert(SI);
10268 
10269   // Check for uses of the argument again so that we can avoid exporting ArgVal
10270   // if it is't used by anything other than the store.
10271   for (const Value *U : Arg.users()) {
10272     if (U != SI) {
10273       ArgHasUses = true;
10274       break;
10275     }
10276   }
10277 }
10278 
10279 void SelectionDAGISel::LowerArguments(const Function &F) {
10280   SelectionDAG &DAG = SDB->DAG;
10281   SDLoc dl = SDB->getCurSDLoc();
10282   const DataLayout &DL = DAG.getDataLayout();
10283   SmallVector<ISD::InputArg, 16> Ins;
10284 
10285   // In Naked functions we aren't going to save any registers.
10286   if (F.hasFnAttribute(Attribute::Naked))
10287     return;
10288 
10289   if (!FuncInfo->CanLowerReturn) {
10290     // Put in an sret pointer parameter before all the other parameters.
10291     SmallVector<EVT, 1> ValueVTs;
10292     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10293                     F.getReturnType()->getPointerTo(
10294                         DAG.getDataLayout().getAllocaAddrSpace()),
10295                     ValueVTs);
10296 
10297     // NOTE: Assuming that a pointer will never break down to more than one VT
10298     // or one register.
10299     ISD::ArgFlagsTy Flags;
10300     Flags.setSRet();
10301     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10302     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10303                          ISD::InputArg::NoArgIndex, 0);
10304     Ins.push_back(RetArg);
10305   }
10306 
10307   // Look for stores of arguments to static allocas. Mark such arguments with a
10308   // flag to ask the target to give us the memory location of that argument if
10309   // available.
10310   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10311   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10312                                     ArgCopyElisionCandidates);
10313 
10314   // Set up the incoming argument description vector.
10315   for (const Argument &Arg : F.args()) {
10316     unsigned ArgNo = Arg.getArgNo();
10317     SmallVector<EVT, 4> ValueVTs;
10318     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10319     bool isArgValueUsed = !Arg.use_empty();
10320     unsigned PartBase = 0;
10321     Type *FinalType = Arg.getType();
10322     if (Arg.hasAttribute(Attribute::ByVal))
10323       FinalType = Arg.getParamByValType();
10324     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10325         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10326     for (unsigned Value = 0, NumValues = ValueVTs.size();
10327          Value != NumValues; ++Value) {
10328       EVT VT = ValueVTs[Value];
10329       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10330       ISD::ArgFlagsTy Flags;
10331 
10332 
10333       if (Arg.getType()->isPointerTy()) {
10334         Flags.setPointer();
10335         Flags.setPointerAddrSpace(
10336             cast<PointerType>(Arg.getType())->getAddressSpace());
10337       }
10338       if (Arg.hasAttribute(Attribute::ZExt))
10339         Flags.setZExt();
10340       if (Arg.hasAttribute(Attribute::SExt))
10341         Flags.setSExt();
10342       if (Arg.hasAttribute(Attribute::InReg)) {
10343         // If we are using vectorcall calling convention, a structure that is
10344         // passed InReg - is surely an HVA
10345         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10346             isa<StructType>(Arg.getType())) {
10347           // The first value of a structure is marked
10348           if (0 == Value)
10349             Flags.setHvaStart();
10350           Flags.setHva();
10351         }
10352         // Set InReg Flag
10353         Flags.setInReg();
10354       }
10355       if (Arg.hasAttribute(Attribute::StructRet))
10356         Flags.setSRet();
10357       if (Arg.hasAttribute(Attribute::SwiftSelf))
10358         Flags.setSwiftSelf();
10359       if (Arg.hasAttribute(Attribute::SwiftAsync))
10360         Flags.setSwiftAsync();
10361       if (Arg.hasAttribute(Attribute::SwiftError))
10362         Flags.setSwiftError();
10363       if (Arg.hasAttribute(Attribute::ByVal))
10364         Flags.setByVal();
10365       if (Arg.hasAttribute(Attribute::ByRef))
10366         Flags.setByRef();
10367       if (Arg.hasAttribute(Attribute::InAlloca)) {
10368         Flags.setInAlloca();
10369         // Set the byval flag for CCAssignFn callbacks that don't know about
10370         // inalloca.  This way we can know how many bytes we should've allocated
10371         // and how many bytes a callee cleanup function will pop.  If we port
10372         // inalloca to more targets, we'll have to add custom inalloca handling
10373         // in the various CC lowering callbacks.
10374         Flags.setByVal();
10375       }
10376       if (Arg.hasAttribute(Attribute::Preallocated)) {
10377         Flags.setPreallocated();
10378         // Set the byval flag for CCAssignFn callbacks that don't know about
10379         // preallocated.  This way we can know how many bytes we should've
10380         // allocated and how many bytes a callee cleanup function will pop.  If
10381         // we port preallocated to more targets, we'll have to add custom
10382         // preallocated handling in the various CC lowering callbacks.
10383         Flags.setByVal();
10384       }
10385 
10386       // Certain targets (such as MIPS), may have a different ABI alignment
10387       // for a type depending on the context. Give the target a chance to
10388       // specify the alignment it wants.
10389       const Align OriginalAlignment(
10390           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10391       Flags.setOrigAlign(OriginalAlignment);
10392 
10393       Align MemAlign;
10394       Type *ArgMemTy = nullptr;
10395       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10396           Flags.isByRef()) {
10397         if (!ArgMemTy)
10398           ArgMemTy = Arg.getPointeeInMemoryValueType();
10399 
10400         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10401 
10402         // For in-memory arguments, size and alignment should be passed from FE.
10403         // BE will guess if this info is not there but there are cases it cannot
10404         // get right.
10405         if (auto ParamAlign = Arg.getParamStackAlign())
10406           MemAlign = *ParamAlign;
10407         else if ((ParamAlign = Arg.getParamAlign()))
10408           MemAlign = *ParamAlign;
10409         else
10410           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10411         if (Flags.isByRef())
10412           Flags.setByRefSize(MemSize);
10413         else
10414           Flags.setByValSize(MemSize);
10415       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10416         MemAlign = *ParamAlign;
10417       } else {
10418         MemAlign = OriginalAlignment;
10419       }
10420       Flags.setMemAlign(MemAlign);
10421 
10422       if (Arg.hasAttribute(Attribute::Nest))
10423         Flags.setNest();
10424       if (NeedsRegBlock)
10425         Flags.setInConsecutiveRegs();
10426       if (ArgCopyElisionCandidates.count(&Arg))
10427         Flags.setCopyElisionCandidate();
10428       if (Arg.hasAttribute(Attribute::Returned))
10429         Flags.setReturned();
10430 
10431       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10432           *CurDAG->getContext(), F.getCallingConv(), VT);
10433       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10434           *CurDAG->getContext(), F.getCallingConv(), VT);
10435       for (unsigned i = 0; i != NumRegs; ++i) {
10436         // For scalable vectors, use the minimum size; individual targets
10437         // are responsible for handling scalable vector arguments and
10438         // return values.
10439         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10440                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10441         if (NumRegs > 1 && i == 0)
10442           MyFlags.Flags.setSplit();
10443         // if it isn't first piece, alignment must be 1
10444         else if (i > 0) {
10445           MyFlags.Flags.setOrigAlign(Align(1));
10446           if (i == NumRegs - 1)
10447             MyFlags.Flags.setSplitEnd();
10448         }
10449         Ins.push_back(MyFlags);
10450       }
10451       if (NeedsRegBlock && Value == NumValues - 1)
10452         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10453       PartBase += VT.getStoreSize().getKnownMinSize();
10454     }
10455   }
10456 
10457   // Call the target to set up the argument values.
10458   SmallVector<SDValue, 8> InVals;
10459   SDValue NewRoot = TLI->LowerFormalArguments(
10460       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10461 
10462   // Verify that the target's LowerFormalArguments behaved as expected.
10463   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10464          "LowerFormalArguments didn't return a valid chain!");
10465   assert(InVals.size() == Ins.size() &&
10466          "LowerFormalArguments didn't emit the correct number of values!");
10467   LLVM_DEBUG({
10468     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10469       assert(InVals[i].getNode() &&
10470              "LowerFormalArguments emitted a null value!");
10471       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10472              "LowerFormalArguments emitted a value with the wrong type!");
10473     }
10474   });
10475 
10476   // Update the DAG with the new chain value resulting from argument lowering.
10477   DAG.setRoot(NewRoot);
10478 
10479   // Set up the argument values.
10480   unsigned i = 0;
10481   if (!FuncInfo->CanLowerReturn) {
10482     // Create a virtual register for the sret pointer, and put in a copy
10483     // from the sret argument into it.
10484     SmallVector<EVT, 1> ValueVTs;
10485     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10486                     F.getReturnType()->getPointerTo(
10487                         DAG.getDataLayout().getAllocaAddrSpace()),
10488                     ValueVTs);
10489     MVT VT = ValueVTs[0].getSimpleVT();
10490     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10491     Optional<ISD::NodeType> AssertOp = None;
10492     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10493                                         nullptr, F.getCallingConv(), AssertOp);
10494 
10495     MachineFunction& MF = SDB->DAG.getMachineFunction();
10496     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10497     Register SRetReg =
10498         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10499     FuncInfo->DemoteRegister = SRetReg;
10500     NewRoot =
10501         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10502     DAG.setRoot(NewRoot);
10503 
10504     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10505     ++i;
10506   }
10507 
10508   SmallVector<SDValue, 4> Chains;
10509   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10510   for (const Argument &Arg : F.args()) {
10511     SmallVector<SDValue, 4> ArgValues;
10512     SmallVector<EVT, 4> ValueVTs;
10513     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10514     unsigned NumValues = ValueVTs.size();
10515     if (NumValues == 0)
10516       continue;
10517 
10518     bool ArgHasUses = !Arg.use_empty();
10519 
10520     // Elide the copying store if the target loaded this argument from a
10521     // suitable fixed stack object.
10522     if (Ins[i].Flags.isCopyElisionCandidate()) {
10523       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10524                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10525                              InVals[i], ArgHasUses);
10526     }
10527 
10528     // If this argument is unused then remember its value. It is used to generate
10529     // debugging information.
10530     bool isSwiftErrorArg =
10531         TLI->supportSwiftError() &&
10532         Arg.hasAttribute(Attribute::SwiftError);
10533     if (!ArgHasUses && !isSwiftErrorArg) {
10534       SDB->setUnusedArgValue(&Arg, InVals[i]);
10535 
10536       // Also remember any frame index for use in FastISel.
10537       if (FrameIndexSDNode *FI =
10538           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10539         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10540     }
10541 
10542     for (unsigned Val = 0; Val != NumValues; ++Val) {
10543       EVT VT = ValueVTs[Val];
10544       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10545                                                       F.getCallingConv(), VT);
10546       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10547           *CurDAG->getContext(), F.getCallingConv(), VT);
10548 
10549       // Even an apparent 'unused' swifterror argument needs to be returned. So
10550       // we do generate a copy for it that can be used on return from the
10551       // function.
10552       if (ArgHasUses || isSwiftErrorArg) {
10553         Optional<ISD::NodeType> AssertOp;
10554         if (Arg.hasAttribute(Attribute::SExt))
10555           AssertOp = ISD::AssertSext;
10556         else if (Arg.hasAttribute(Attribute::ZExt))
10557           AssertOp = ISD::AssertZext;
10558 
10559         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10560                                              PartVT, VT, nullptr,
10561                                              F.getCallingConv(), AssertOp));
10562       }
10563 
10564       i += NumParts;
10565     }
10566 
10567     // We don't need to do anything else for unused arguments.
10568     if (ArgValues.empty())
10569       continue;
10570 
10571     // Note down frame index.
10572     if (FrameIndexSDNode *FI =
10573         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10574       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10575 
10576     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10577                                      SDB->getCurSDLoc());
10578 
10579     SDB->setValue(&Arg, Res);
10580     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10581       // We want to associate the argument with the frame index, among
10582       // involved operands, that correspond to the lowest address. The
10583       // getCopyFromParts function, called earlier, is swapping the order of
10584       // the operands to BUILD_PAIR depending on endianness. The result of
10585       // that swapping is that the least significant bits of the argument will
10586       // be in the first operand of the BUILD_PAIR node, and the most
10587       // significant bits will be in the second operand.
10588       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10589       if (LoadSDNode *LNode =
10590           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10591         if (FrameIndexSDNode *FI =
10592             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10593           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10594     }
10595 
10596     // Analyses past this point are naive and don't expect an assertion.
10597     if (Res.getOpcode() == ISD::AssertZext)
10598       Res = Res.getOperand(0);
10599 
10600     // Update the SwiftErrorVRegDefMap.
10601     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10602       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10603       if (Register::isVirtualRegister(Reg))
10604         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10605                                    Reg);
10606     }
10607 
10608     // If this argument is live outside of the entry block, insert a copy from
10609     // wherever we got it to the vreg that other BB's will reference it as.
10610     if (Res.getOpcode() == ISD::CopyFromReg) {
10611       // If we can, though, try to skip creating an unnecessary vreg.
10612       // FIXME: This isn't very clean... it would be nice to make this more
10613       // general.
10614       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10615       if (Register::isVirtualRegister(Reg)) {
10616         FuncInfo->ValueMap[&Arg] = Reg;
10617         continue;
10618       }
10619     }
10620     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10621       FuncInfo->InitializeRegForValue(&Arg);
10622       SDB->CopyToExportRegsIfNeeded(&Arg);
10623     }
10624   }
10625 
10626   if (!Chains.empty()) {
10627     Chains.push_back(NewRoot);
10628     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10629   }
10630 
10631   DAG.setRoot(NewRoot);
10632 
10633   assert(i == InVals.size() && "Argument register count mismatch!");
10634 
10635   // If any argument copy elisions occurred and we have debug info, update the
10636   // stale frame indices used in the dbg.declare variable info table.
10637   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10638   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10639     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10640       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10641       if (I != ArgCopyElisionFrameIndexMap.end())
10642         VI.Slot = I->second;
10643     }
10644   }
10645 
10646   // Finally, if the target has anything special to do, allow it to do so.
10647   emitFunctionEntryCode();
10648 }
10649 
10650 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10651 /// ensure constants are generated when needed.  Remember the virtual registers
10652 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10653 /// directly add them, because expansion might result in multiple MBB's for one
10654 /// BB.  As such, the start of the BB might correspond to a different MBB than
10655 /// the end.
10656 void
10657 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10658   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10659   const Instruction *TI = LLVMBB->getTerminator();
10660 
10661   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10662 
10663   // Check PHI nodes in successors that expect a value to be available from this
10664   // block.
10665   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10666     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10667     if (!isa<PHINode>(SuccBB->begin())) continue;
10668     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10669 
10670     // If this terminator has multiple identical successors (common for
10671     // switches), only handle each succ once.
10672     if (!SuccsHandled.insert(SuccMBB).second)
10673       continue;
10674 
10675     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10676 
10677     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10678     // nodes and Machine PHI nodes, but the incoming operands have not been
10679     // emitted yet.
10680     for (const PHINode &PN : SuccBB->phis()) {
10681       // Ignore dead phi's.
10682       if (PN.use_empty())
10683         continue;
10684 
10685       // Skip empty types
10686       if (PN.getType()->isEmptyTy())
10687         continue;
10688 
10689       unsigned Reg;
10690       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10691 
10692       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10693         unsigned &RegOut = ConstantsOut[C];
10694         if (RegOut == 0) {
10695           RegOut = FuncInfo.CreateRegs(C);
10696           // We need to zero/sign extend ConstantInt phi operands to match
10697           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10698           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10699           if (auto *CI = dyn_cast<ConstantInt>(C))
10700             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10701                                                     : ISD::ZERO_EXTEND;
10702           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10703         }
10704         Reg = RegOut;
10705       } else {
10706         DenseMap<const Value *, Register>::iterator I =
10707           FuncInfo.ValueMap.find(PHIOp);
10708         if (I != FuncInfo.ValueMap.end())
10709           Reg = I->second;
10710         else {
10711           assert(isa<AllocaInst>(PHIOp) &&
10712                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10713                  "Didn't codegen value into a register!??");
10714           Reg = FuncInfo.CreateRegs(PHIOp);
10715           CopyValueToVirtualRegister(PHIOp, Reg);
10716         }
10717       }
10718 
10719       // Remember that this register needs to added to the machine PHI node as
10720       // the input for this MBB.
10721       SmallVector<EVT, 4> ValueVTs;
10722       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10723       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10724         EVT VT = ValueVTs[vti];
10725         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10726         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10727           FuncInfo.PHINodesToUpdate.push_back(
10728               std::make_pair(&*MBBI++, Reg + i));
10729         Reg += NumRegisters;
10730       }
10731     }
10732   }
10733 
10734   ConstantsOut.clear();
10735 }
10736 
10737 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10738   MachineFunction::iterator I(MBB);
10739   if (++I == FuncInfo.MF->end())
10740     return nullptr;
10741   return &*I;
10742 }
10743 
10744 /// During lowering new call nodes can be created (such as memset, etc.).
10745 /// Those will become new roots of the current DAG, but complications arise
10746 /// when they are tail calls. In such cases, the call lowering will update
10747 /// the root, but the builder still needs to know that a tail call has been
10748 /// lowered in order to avoid generating an additional return.
10749 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10750   // If the node is null, we do have a tail call.
10751   if (MaybeTC.getNode() != nullptr)
10752     DAG.setRoot(MaybeTC);
10753   else
10754     HasTailCall = true;
10755 }
10756 
10757 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10758                                         MachineBasicBlock *SwitchMBB,
10759                                         MachineBasicBlock *DefaultMBB) {
10760   MachineFunction *CurMF = FuncInfo.MF;
10761   MachineBasicBlock *NextMBB = nullptr;
10762   MachineFunction::iterator BBI(W.MBB);
10763   if (++BBI != FuncInfo.MF->end())
10764     NextMBB = &*BBI;
10765 
10766   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10767 
10768   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10769 
10770   if (Size == 2 && W.MBB == SwitchMBB) {
10771     // If any two of the cases has the same destination, and if one value
10772     // is the same as the other, but has one bit unset that the other has set,
10773     // use bit manipulation to do two compares at once.  For example:
10774     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10775     // TODO: This could be extended to merge any 2 cases in switches with 3
10776     // cases.
10777     // TODO: Handle cases where W.CaseBB != SwitchBB.
10778     CaseCluster &Small = *W.FirstCluster;
10779     CaseCluster &Big = *W.LastCluster;
10780 
10781     if (Small.Low == Small.High && Big.Low == Big.High &&
10782         Small.MBB == Big.MBB) {
10783       const APInt &SmallValue = Small.Low->getValue();
10784       const APInt &BigValue = Big.Low->getValue();
10785 
10786       // Check that there is only one bit different.
10787       APInt CommonBit = BigValue ^ SmallValue;
10788       if (CommonBit.isPowerOf2()) {
10789         SDValue CondLHS = getValue(Cond);
10790         EVT VT = CondLHS.getValueType();
10791         SDLoc DL = getCurSDLoc();
10792 
10793         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10794                                  DAG.getConstant(CommonBit, DL, VT));
10795         SDValue Cond = DAG.getSetCC(
10796             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10797             ISD::SETEQ);
10798 
10799         // Update successor info.
10800         // Both Small and Big will jump to Small.BB, so we sum up the
10801         // probabilities.
10802         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10803         if (BPI)
10804           addSuccessorWithProb(
10805               SwitchMBB, DefaultMBB,
10806               // The default destination is the first successor in IR.
10807               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10808         else
10809           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10810 
10811         // Insert the true branch.
10812         SDValue BrCond =
10813             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10814                         DAG.getBasicBlock(Small.MBB));
10815         // Insert the false branch.
10816         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10817                              DAG.getBasicBlock(DefaultMBB));
10818 
10819         DAG.setRoot(BrCond);
10820         return;
10821       }
10822     }
10823   }
10824 
10825   if (TM.getOptLevel() != CodeGenOpt::None) {
10826     // Here, we order cases by probability so the most likely case will be
10827     // checked first. However, two clusters can have the same probability in
10828     // which case their relative ordering is non-deterministic. So we use Low
10829     // as a tie-breaker as clusters are guaranteed to never overlap.
10830     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10831                [](const CaseCluster &a, const CaseCluster &b) {
10832       return a.Prob != b.Prob ?
10833              a.Prob > b.Prob :
10834              a.Low->getValue().slt(b.Low->getValue());
10835     });
10836 
10837     // Rearrange the case blocks so that the last one falls through if possible
10838     // without changing the order of probabilities.
10839     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10840       --I;
10841       if (I->Prob > W.LastCluster->Prob)
10842         break;
10843       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10844         std::swap(*I, *W.LastCluster);
10845         break;
10846       }
10847     }
10848   }
10849 
10850   // Compute total probability.
10851   BranchProbability DefaultProb = W.DefaultProb;
10852   BranchProbability UnhandledProbs = DefaultProb;
10853   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10854     UnhandledProbs += I->Prob;
10855 
10856   MachineBasicBlock *CurMBB = W.MBB;
10857   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10858     bool FallthroughUnreachable = false;
10859     MachineBasicBlock *Fallthrough;
10860     if (I == W.LastCluster) {
10861       // For the last cluster, fall through to the default destination.
10862       Fallthrough = DefaultMBB;
10863       FallthroughUnreachable = isa<UnreachableInst>(
10864           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10865     } else {
10866       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10867       CurMF->insert(BBI, Fallthrough);
10868       // Put Cond in a virtual register to make it available from the new blocks.
10869       ExportFromCurrentBlock(Cond);
10870     }
10871     UnhandledProbs -= I->Prob;
10872 
10873     switch (I->Kind) {
10874       case CC_JumpTable: {
10875         // FIXME: Optimize away range check based on pivot comparisons.
10876         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10877         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10878 
10879         // The jump block hasn't been inserted yet; insert it here.
10880         MachineBasicBlock *JumpMBB = JT->MBB;
10881         CurMF->insert(BBI, JumpMBB);
10882 
10883         auto JumpProb = I->Prob;
10884         auto FallthroughProb = UnhandledProbs;
10885 
10886         // If the default statement is a target of the jump table, we evenly
10887         // distribute the default probability to successors of CurMBB. Also
10888         // update the probability on the edge from JumpMBB to Fallthrough.
10889         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10890                                               SE = JumpMBB->succ_end();
10891              SI != SE; ++SI) {
10892           if (*SI == DefaultMBB) {
10893             JumpProb += DefaultProb / 2;
10894             FallthroughProb -= DefaultProb / 2;
10895             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10896             JumpMBB->normalizeSuccProbs();
10897             break;
10898           }
10899         }
10900 
10901         if (FallthroughUnreachable)
10902           JTH->FallthroughUnreachable = true;
10903 
10904         if (!JTH->FallthroughUnreachable)
10905           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10906         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10907         CurMBB->normalizeSuccProbs();
10908 
10909         // The jump table header will be inserted in our current block, do the
10910         // range check, and fall through to our fallthrough block.
10911         JTH->HeaderBB = CurMBB;
10912         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10913 
10914         // If we're in the right place, emit the jump table header right now.
10915         if (CurMBB == SwitchMBB) {
10916           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10917           JTH->Emitted = true;
10918         }
10919         break;
10920       }
10921       case CC_BitTests: {
10922         // FIXME: Optimize away range check based on pivot comparisons.
10923         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10924 
10925         // The bit test blocks haven't been inserted yet; insert them here.
10926         for (BitTestCase &BTC : BTB->Cases)
10927           CurMF->insert(BBI, BTC.ThisBB);
10928 
10929         // Fill in fields of the BitTestBlock.
10930         BTB->Parent = CurMBB;
10931         BTB->Default = Fallthrough;
10932 
10933         BTB->DefaultProb = UnhandledProbs;
10934         // If the cases in bit test don't form a contiguous range, we evenly
10935         // distribute the probability on the edge to Fallthrough to two
10936         // successors of CurMBB.
10937         if (!BTB->ContiguousRange) {
10938           BTB->Prob += DefaultProb / 2;
10939           BTB->DefaultProb -= DefaultProb / 2;
10940         }
10941 
10942         if (FallthroughUnreachable)
10943           BTB->FallthroughUnreachable = true;
10944 
10945         // If we're in the right place, emit the bit test header right now.
10946         if (CurMBB == SwitchMBB) {
10947           visitBitTestHeader(*BTB, SwitchMBB);
10948           BTB->Emitted = true;
10949         }
10950         break;
10951       }
10952       case CC_Range: {
10953         const Value *RHS, *LHS, *MHS;
10954         ISD::CondCode CC;
10955         if (I->Low == I->High) {
10956           // Check Cond == I->Low.
10957           CC = ISD::SETEQ;
10958           LHS = Cond;
10959           RHS=I->Low;
10960           MHS = nullptr;
10961         } else {
10962           // Check I->Low <= Cond <= I->High.
10963           CC = ISD::SETLE;
10964           LHS = I->Low;
10965           MHS = Cond;
10966           RHS = I->High;
10967         }
10968 
10969         // If Fallthrough is unreachable, fold away the comparison.
10970         if (FallthroughUnreachable)
10971           CC = ISD::SETTRUE;
10972 
10973         // The false probability is the sum of all unhandled cases.
10974         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10975                      getCurSDLoc(), I->Prob, UnhandledProbs);
10976 
10977         if (CurMBB == SwitchMBB)
10978           visitSwitchCase(CB, SwitchMBB);
10979         else
10980           SL->SwitchCases.push_back(CB);
10981 
10982         break;
10983       }
10984     }
10985     CurMBB = Fallthrough;
10986   }
10987 }
10988 
10989 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10990                                               CaseClusterIt First,
10991                                               CaseClusterIt Last) {
10992   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10993     if (X.Prob != CC.Prob)
10994       return X.Prob > CC.Prob;
10995 
10996     // Ties are broken by comparing the case value.
10997     return X.Low->getValue().slt(CC.Low->getValue());
10998   });
10999 }
11000 
11001 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11002                                         const SwitchWorkListItem &W,
11003                                         Value *Cond,
11004                                         MachineBasicBlock *SwitchMBB) {
11005   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11006          "Clusters not sorted?");
11007 
11008   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11009 
11010   // Balance the tree based on branch probabilities to create a near-optimal (in
11011   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11012   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11013   CaseClusterIt LastLeft = W.FirstCluster;
11014   CaseClusterIt FirstRight = W.LastCluster;
11015   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11016   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11017 
11018   // Move LastLeft and FirstRight towards each other from opposite directions to
11019   // find a partitioning of the clusters which balances the probability on both
11020   // sides. If LeftProb and RightProb are equal, alternate which side is
11021   // taken to ensure 0-probability nodes are distributed evenly.
11022   unsigned I = 0;
11023   while (LastLeft + 1 < FirstRight) {
11024     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11025       LeftProb += (++LastLeft)->Prob;
11026     else
11027       RightProb += (--FirstRight)->Prob;
11028     I++;
11029   }
11030 
11031   while (true) {
11032     // Our binary search tree differs from a typical BST in that ours can have up
11033     // to three values in each leaf. The pivot selection above doesn't take that
11034     // into account, which means the tree might require more nodes and be less
11035     // efficient. We compensate for this here.
11036 
11037     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11038     unsigned NumRight = W.LastCluster - FirstRight + 1;
11039 
11040     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11041       // If one side has less than 3 clusters, and the other has more than 3,
11042       // consider taking a cluster from the other side.
11043 
11044       if (NumLeft < NumRight) {
11045         // Consider moving the first cluster on the right to the left side.
11046         CaseCluster &CC = *FirstRight;
11047         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11048         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11049         if (LeftSideRank <= RightSideRank) {
11050           // Moving the cluster to the left does not demote it.
11051           ++LastLeft;
11052           ++FirstRight;
11053           continue;
11054         }
11055       } else {
11056         assert(NumRight < NumLeft);
11057         // Consider moving the last element on the left to the right side.
11058         CaseCluster &CC = *LastLeft;
11059         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11060         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11061         if (RightSideRank <= LeftSideRank) {
11062           // Moving the cluster to the right does not demot it.
11063           --LastLeft;
11064           --FirstRight;
11065           continue;
11066         }
11067       }
11068     }
11069     break;
11070   }
11071 
11072   assert(LastLeft + 1 == FirstRight);
11073   assert(LastLeft >= W.FirstCluster);
11074   assert(FirstRight <= W.LastCluster);
11075 
11076   // Use the first element on the right as pivot since we will make less-than
11077   // comparisons against it.
11078   CaseClusterIt PivotCluster = FirstRight;
11079   assert(PivotCluster > W.FirstCluster);
11080   assert(PivotCluster <= W.LastCluster);
11081 
11082   CaseClusterIt FirstLeft = W.FirstCluster;
11083   CaseClusterIt LastRight = W.LastCluster;
11084 
11085   const ConstantInt *Pivot = PivotCluster->Low;
11086 
11087   // New blocks will be inserted immediately after the current one.
11088   MachineFunction::iterator BBI(W.MBB);
11089   ++BBI;
11090 
11091   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11092   // we can branch to its destination directly if it's squeezed exactly in
11093   // between the known lower bound and Pivot - 1.
11094   MachineBasicBlock *LeftMBB;
11095   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11096       FirstLeft->Low == W.GE &&
11097       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11098     LeftMBB = FirstLeft->MBB;
11099   } else {
11100     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11101     FuncInfo.MF->insert(BBI, LeftMBB);
11102     WorkList.push_back(
11103         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11104     // Put Cond in a virtual register to make it available from the new blocks.
11105     ExportFromCurrentBlock(Cond);
11106   }
11107 
11108   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11109   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11110   // directly if RHS.High equals the current upper bound.
11111   MachineBasicBlock *RightMBB;
11112   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11113       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11114     RightMBB = FirstRight->MBB;
11115   } else {
11116     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11117     FuncInfo.MF->insert(BBI, RightMBB);
11118     WorkList.push_back(
11119         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11120     // Put Cond in a virtual register to make it available from the new blocks.
11121     ExportFromCurrentBlock(Cond);
11122   }
11123 
11124   // Create the CaseBlock record that will be used to lower the branch.
11125   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11126                getCurSDLoc(), LeftProb, RightProb);
11127 
11128   if (W.MBB == SwitchMBB)
11129     visitSwitchCase(CB, SwitchMBB);
11130   else
11131     SL->SwitchCases.push_back(CB);
11132 }
11133 
11134 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11135 // from the swith statement.
11136 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11137                                             BranchProbability PeeledCaseProb) {
11138   if (PeeledCaseProb == BranchProbability::getOne())
11139     return BranchProbability::getZero();
11140   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11141 
11142   uint32_t Numerator = CaseProb.getNumerator();
11143   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11144   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11145 }
11146 
11147 // Try to peel the top probability case if it exceeds the threshold.
11148 // Return current MachineBasicBlock for the switch statement if the peeling
11149 // does not occur.
11150 // If the peeling is performed, return the newly created MachineBasicBlock
11151 // for the peeled switch statement. Also update Clusters to remove the peeled
11152 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11153 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11154     const SwitchInst &SI, CaseClusterVector &Clusters,
11155     BranchProbability &PeeledCaseProb) {
11156   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11157   // Don't perform if there is only one cluster or optimizing for size.
11158   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11159       TM.getOptLevel() == CodeGenOpt::None ||
11160       SwitchMBB->getParent()->getFunction().hasMinSize())
11161     return SwitchMBB;
11162 
11163   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11164   unsigned PeeledCaseIndex = 0;
11165   bool SwitchPeeled = false;
11166   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11167     CaseCluster &CC = Clusters[Index];
11168     if (CC.Prob < TopCaseProb)
11169       continue;
11170     TopCaseProb = CC.Prob;
11171     PeeledCaseIndex = Index;
11172     SwitchPeeled = true;
11173   }
11174   if (!SwitchPeeled)
11175     return SwitchMBB;
11176 
11177   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11178                     << TopCaseProb << "\n");
11179 
11180   // Record the MBB for the peeled switch statement.
11181   MachineFunction::iterator BBI(SwitchMBB);
11182   ++BBI;
11183   MachineBasicBlock *PeeledSwitchMBB =
11184       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11185   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11186 
11187   ExportFromCurrentBlock(SI.getCondition());
11188   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11189   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11190                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11191   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11192 
11193   Clusters.erase(PeeledCaseIt);
11194   for (CaseCluster &CC : Clusters) {
11195     LLVM_DEBUG(
11196         dbgs() << "Scale the probablity for one cluster, before scaling: "
11197                << CC.Prob << "\n");
11198     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11199     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11200   }
11201   PeeledCaseProb = TopCaseProb;
11202   return PeeledSwitchMBB;
11203 }
11204 
11205 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11206   // Extract cases from the switch.
11207   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11208   CaseClusterVector Clusters;
11209   Clusters.reserve(SI.getNumCases());
11210   for (auto I : SI.cases()) {
11211     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11212     const ConstantInt *CaseVal = I.getCaseValue();
11213     BranchProbability Prob =
11214         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11215             : BranchProbability(1, SI.getNumCases() + 1);
11216     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11217   }
11218 
11219   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11220 
11221   // Cluster adjacent cases with the same destination. We do this at all
11222   // optimization levels because it's cheap to do and will make codegen faster
11223   // if there are many clusters.
11224   sortAndRangeify(Clusters);
11225 
11226   // The branch probablity of the peeled case.
11227   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11228   MachineBasicBlock *PeeledSwitchMBB =
11229       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11230 
11231   // If there is only the default destination, jump there directly.
11232   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11233   if (Clusters.empty()) {
11234     assert(PeeledSwitchMBB == SwitchMBB);
11235     SwitchMBB->addSuccessor(DefaultMBB);
11236     if (DefaultMBB != NextBlock(SwitchMBB)) {
11237       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11238                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11239     }
11240     return;
11241   }
11242 
11243   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11244   SL->findBitTestClusters(Clusters, &SI);
11245 
11246   LLVM_DEBUG({
11247     dbgs() << "Case clusters: ";
11248     for (const CaseCluster &C : Clusters) {
11249       if (C.Kind == CC_JumpTable)
11250         dbgs() << "JT:";
11251       if (C.Kind == CC_BitTests)
11252         dbgs() << "BT:";
11253 
11254       C.Low->getValue().print(dbgs(), true);
11255       if (C.Low != C.High) {
11256         dbgs() << '-';
11257         C.High->getValue().print(dbgs(), true);
11258       }
11259       dbgs() << ' ';
11260     }
11261     dbgs() << '\n';
11262   });
11263 
11264   assert(!Clusters.empty());
11265   SwitchWorkList WorkList;
11266   CaseClusterIt First = Clusters.begin();
11267   CaseClusterIt Last = Clusters.end() - 1;
11268   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11269   // Scale the branchprobability for DefaultMBB if the peel occurs and
11270   // DefaultMBB is not replaced.
11271   if (PeeledCaseProb != BranchProbability::getZero() &&
11272       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11273     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11274   WorkList.push_back(
11275       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11276 
11277   while (!WorkList.empty()) {
11278     SwitchWorkListItem W = WorkList.pop_back_val();
11279     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11280 
11281     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11282         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11283       // For optimized builds, lower large range as a balanced binary tree.
11284       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11285       continue;
11286     }
11287 
11288     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11289   }
11290 }
11291 
11292 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11293   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11294   auto DL = getCurSDLoc();
11295   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11296   setValue(&I, DAG.getStepVector(DL, ResultVT));
11297 }
11298 
11299 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11301   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11302 
11303   SDLoc DL = getCurSDLoc();
11304   SDValue V = getValue(I.getOperand(0));
11305   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11306 
11307   if (VT.isScalableVector()) {
11308     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11309     return;
11310   }
11311 
11312   // Use VECTOR_SHUFFLE for the fixed-length vector
11313   // to maintain existing behavior.
11314   SmallVector<int, 8> Mask;
11315   unsigned NumElts = VT.getVectorMinNumElements();
11316   for (unsigned i = 0; i != NumElts; ++i)
11317     Mask.push_back(NumElts - 1 - i);
11318 
11319   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11320 }
11321 
11322 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11323   SmallVector<EVT, 4> ValueVTs;
11324   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11325                   ValueVTs);
11326   unsigned NumValues = ValueVTs.size();
11327   if (NumValues == 0) return;
11328 
11329   SmallVector<SDValue, 4> Values(NumValues);
11330   SDValue Op = getValue(I.getOperand(0));
11331 
11332   for (unsigned i = 0; i != NumValues; ++i)
11333     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11334                             SDValue(Op.getNode(), Op.getResNo() + i));
11335 
11336   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11337                            DAG.getVTList(ValueVTs), Values));
11338 }
11339 
11340 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11341   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11342   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11343 
11344   SDLoc DL = getCurSDLoc();
11345   SDValue V1 = getValue(I.getOperand(0));
11346   SDValue V2 = getValue(I.getOperand(1));
11347   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11348 
11349   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11350   if (VT.isScalableVector()) {
11351     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11352     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11353                              DAG.getConstant(Imm, DL, IdxVT)));
11354     return;
11355   }
11356 
11357   unsigned NumElts = VT.getVectorNumElements();
11358 
11359   uint64_t Idx = (NumElts + Imm) % NumElts;
11360 
11361   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11362   SmallVector<int, 8> Mask;
11363   for (unsigned i = 0; i < NumElts; ++i)
11364     Mask.push_back(Idx + i);
11365   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11366 }
11367