xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 9ff2eb1ea596a52ad2b5cfab826548c3af0a1e6e)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/BranchProbabilityInfo.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/EHPersonalities.h"
31 #include "llvm/Analysis/Loads.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/ProfileSummaryInfo.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/Analysis/VectorUtils.h"
37 #include "llvm/CodeGen/Analysis.h"
38 #include "llvm/CodeGen/FunctionLoweringInfo.h"
39 #include "llvm/CodeGen/GCMetadata.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
53 #include "llvm/CodeGen/StackMaps.h"
54 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
55 #include "llvm/CodeGen/TargetFrameLowering.h"
56 #include "llvm/CodeGen/TargetInstrInfo.h"
57 #include "llvm/CodeGen/TargetOpcodes.h"
58 #include "llvm/CodeGen/TargetRegisterInfo.h"
59 #include "llvm/CodeGen/TargetSubtargetInfo.h"
60 #include "llvm/CodeGen/WinEHFuncInfo.h"
61 #include "llvm/IR/Argument.h"
62 #include "llvm/IR/Attributes.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/CFG.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/ConstantRange.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DebugInfoMetadata.h"
71 #include "llvm/IR/DerivedTypes.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsWebAssembly.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/Metadata.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/Operator.h"
85 #include "llvm/IR/PatternMatch.h"
86 #include "llvm/IR/Statepoint.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/IR/User.h"
89 #include "llvm/IR/Value.h"
90 #include "llvm/MC/MCContext.h"
91 #include "llvm/MC/MCSymbol.h"
92 #include "llvm/Support/AtomicOrdering.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/MathExtras.h"
98 #include "llvm/Support/raw_ostream.h"
99 #include "llvm/Target/TargetIntrinsicInfo.h"
100 #include "llvm/Target/TargetMachine.h"
101 #include "llvm/Target/TargetOptions.h"
102 #include "llvm/Transforms/Utils/Local.h"
103 #include <cstddef>
104 #include <cstring>
105 #include <iterator>
106 #include <limits>
107 #include <numeric>
108 #include <tuple>
109 
110 using namespace llvm;
111 using namespace PatternMatch;
112 using namespace SwitchCG;
113 
114 #define DEBUG_TYPE "isel"
115 
116 /// LimitFloatPrecision - Generate low-precision inline sequences for
117 /// some float libcalls (6, 8 or 12 bits).
118 static unsigned LimitFloatPrecision;
119 
120 static cl::opt<bool>
121     InsertAssertAlign("insert-assert-align", cl::init(true),
122                       cl::desc("Insert the experimental `assertalign` node."),
123                       cl::ReallyHidden);
124 
125 static cl::opt<unsigned, true>
126     LimitFPPrecision("limit-float-precision",
127                      cl::desc("Generate low-precision inline sequences "
128                               "for some float libcalls"),
129                      cl::location(LimitFloatPrecision), cl::Hidden,
130                      cl::init(0));
131 
132 static cl::opt<unsigned> SwitchPeelThreshold(
133     "switch-peel-threshold", cl::Hidden, cl::init(66),
134     cl::desc("Set the case probability threshold for peeling the case from a "
135              "switch statement. A value greater than 100 will void this "
136              "optimization"));
137 
138 // Limit the width of DAG chains. This is important in general to prevent
139 // DAG-based analysis from blowing up. For example, alias analysis and
140 // load clustering may not complete in reasonable time. It is difficult to
141 // recognize and avoid this situation within each individual analysis, and
142 // future analyses are likely to have the same behavior. Limiting DAG width is
143 // the safe approach and will be especially important with global DAGs.
144 //
145 // MaxParallelChains default is arbitrarily high to avoid affecting
146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147 // sequence over this should have been converted to llvm.memcpy by the
148 // frontend. It is easy to induce this behavior with .ll code such as:
149 // %buffer = alloca [4096 x i8]
150 // %data = load [4096 x i8]* %argPtr
151 // store [4096 x i8] %data, [4096 x i8]* %buffer
152 static const unsigned MaxParallelChains = 64;
153 
154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
155                                       const SDValue *Parts, unsigned NumParts,
156                                       MVT PartVT, EVT ValueVT, const Value *V,
157                                       Optional<CallingConv::ID> CC);
158 
159 /// getCopyFromParts - Create a value that contains the specified legal parts
160 /// combined into the value they represent.  If the parts combine to a type
161 /// larger than ValueVT then AssertOp can be used to specify whether the extra
162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
163 /// (ISD::AssertSext).
164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
165                                 const SDValue *Parts, unsigned NumParts,
166                                 MVT PartVT, EVT ValueVT, const Value *V,
167                                 Optional<CallingConv::ID> CC = None,
168                                 Optional<ISD::NodeType> AssertOp = None) {
169   // Let the target assemble the parts if it wants to
170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
171   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
172                                                    PartVT, ValueVT, CC))
173     return Val;
174 
175   if (ValueVT.isVector())
176     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
177                                   CC);
178 
179   assert(NumParts > 0 && "No parts to assemble!");
180   SDValue Val = Parts[0];
181 
182   if (NumParts > 1) {
183     // Assemble the value from multiple parts.
184     if (ValueVT.isInteger()) {
185       unsigned PartBits = PartVT.getSizeInBits();
186       unsigned ValueBits = ValueVT.getSizeInBits();
187 
188       // Assemble the power of 2 part.
189       unsigned RoundParts =
190           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
191       unsigned RoundBits = PartBits * RoundParts;
192       EVT RoundVT = RoundBits == ValueBits ?
193         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
194       SDValue Lo, Hi;
195 
196       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
197 
198       if (RoundParts > 2) {
199         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
200                               PartVT, HalfVT, V);
201         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
202                               RoundParts / 2, PartVT, HalfVT, V);
203       } else {
204         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
205         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
206       }
207 
208       if (DAG.getDataLayout().isBigEndian())
209         std::swap(Lo, Hi);
210 
211       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
212 
213       if (RoundParts < NumParts) {
214         // Assemble the trailing non-power-of-2 part.
215         unsigned OddParts = NumParts - RoundParts;
216         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
217         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
218                               OddVT, V, CC);
219 
220         // Combine the round and odd parts.
221         Lo = Val;
222         if (DAG.getDataLayout().isBigEndian())
223           std::swap(Lo, Hi);
224         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
225         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
226         Hi =
227             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
228                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
229                                         TLI.getPointerTy(DAG.getDataLayout())));
230         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
231         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
232       }
233     } else if (PartVT.isFloatingPoint()) {
234       // FP split into multiple FP parts (for ppcf128)
235       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236              "Unexpected split");
237       SDValue Lo, Hi;
238       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
239       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
240       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
241         std::swap(Lo, Hi);
242       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
243     } else {
244       // FP split into integer parts (soft fp)
245       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246              !PartVT.isVector() && "Unexpected split");
247       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
248       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
249     }
250   }
251 
252   // There is now one part, held in Val.  Correct it to match ValueVT.
253   // PartEVT is the type of the register class that holds the value.
254   // ValueVT is the type of the inline asm operation.
255   EVT PartEVT = Val.getValueType();
256 
257   if (PartEVT == ValueVT)
258     return Val;
259 
260   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
261       ValueVT.bitsLT(PartEVT)) {
262     // For an FP value in an integer part, we need to truncate to the right
263     // width first.
264     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
265     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
266   }
267 
268   // Handle types that have the same size.
269   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
270     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
271 
272   // Handle types with different sizes.
273   if (PartEVT.isInteger() && ValueVT.isInteger()) {
274     if (ValueVT.bitsLT(PartEVT)) {
275       // For a truncate, see if we have any information to
276       // indicate whether the truncated bits will always be
277       // zero or sign-extension.
278       if (AssertOp.hasValue())
279         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
280                           DAG.getValueType(ValueVT));
281       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
282     }
283     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
284   }
285 
286   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
287     // FP_ROUND's are always exact here.
288     if (ValueVT.bitsLT(Val.getValueType()))
289       return DAG.getNode(
290           ISD::FP_ROUND, DL, ValueVT, Val,
291           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
292 
293     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
294   }
295 
296   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
297   // then truncating.
298   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
299       ValueVT.bitsLT(PartEVT)) {
300     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
301     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
302   }
303 
304   report_fatal_error("Unknown mismatch in getCopyFromParts!");
305 }
306 
307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
308                                               const Twine &ErrMsg) {
309   const Instruction *I = dyn_cast_or_null<Instruction>(V);
310   if (!V)
311     return Ctx.emitError(ErrMsg);
312 
313   const char *AsmError = ", possible invalid constraint for vector type";
314   if (const CallInst *CI = dyn_cast<CallInst>(I))
315     if (CI->isInlineAsm())
316       return Ctx.emitError(I, ErrMsg + AsmError);
317 
318   return Ctx.emitError(I, ErrMsg);
319 }
320 
321 /// getCopyFromPartsVector - Create a value that contains the specified legal
322 /// parts combined into the value they represent.  If the parts combine to a
323 /// type larger than ValueVT then AssertOp can be used to specify whether the
324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
325 /// ValueVT (ISD::AssertSext).
326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
327                                       const SDValue *Parts, unsigned NumParts,
328                                       MVT PartVT, EVT ValueVT, const Value *V,
329                                       Optional<CallingConv::ID> CallConv) {
330   assert(ValueVT.isVector() && "Not a vector value");
331   assert(NumParts > 0 && "No parts to assemble!");
332   const bool IsABIRegCopy = CallConv.hasValue();
333 
334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
335   SDValue Val = Parts[0];
336 
337   // Handle a multi-element vector.
338   if (NumParts > 1) {
339     EVT IntermediateVT;
340     MVT RegisterVT;
341     unsigned NumIntermediates;
342     unsigned NumRegs;
343 
344     if (IsABIRegCopy) {
345       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
346           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
347           NumIntermediates, RegisterVT);
348     } else {
349       NumRegs =
350           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
351                                      NumIntermediates, RegisterVT);
352     }
353 
354     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
355     NumParts = NumRegs; // Silence a compiler warning.
356     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
357     assert(RegisterVT.getSizeInBits() ==
358            Parts[0].getSimpleValueType().getSizeInBits() &&
359            "Part type sizes don't match!");
360 
361     // Assemble the parts into intermediate operands.
362     SmallVector<SDValue, 8> Ops(NumIntermediates);
363     if (NumIntermediates == NumParts) {
364       // If the register was not expanded, truncate or copy the value,
365       // as appropriate.
366       for (unsigned i = 0; i != NumParts; ++i)
367         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
368                                   PartVT, IntermediateVT, V, CallConv);
369     } else if (NumParts > 0) {
370       // If the intermediate type was expanded, build the intermediate
371       // operands from the parts.
372       assert(NumParts % NumIntermediates == 0 &&
373              "Must expand into a divisible number of parts!");
374       unsigned Factor = NumParts / NumIntermediates;
375       for (unsigned i = 0; i != NumIntermediates; ++i)
376         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
377                                   PartVT, IntermediateVT, V, CallConv);
378     }
379 
380     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
381     // intermediate operands.
382     EVT BuiltVectorTy =
383         IntermediateVT.isVector()
384             ? EVT::getVectorVT(
385                   *DAG.getContext(), IntermediateVT.getScalarType(),
386                   IntermediateVT.getVectorElementCount() * NumParts)
387             : EVT::getVectorVT(*DAG.getContext(),
388                                IntermediateVT.getScalarType(),
389                                NumIntermediates);
390     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
391                                                 : ISD::BUILD_VECTOR,
392                       DL, BuiltVectorTy, Ops);
393   }
394 
395   // There is now one part, held in Val.  Correct it to match ValueVT.
396   EVT PartEVT = Val.getValueType();
397 
398   if (PartEVT == ValueVT)
399     return Val;
400 
401   if (PartEVT.isVector()) {
402     // If the element type of the source/dest vectors are the same, but the
403     // parts vector has more elements than the value vector, then we have a
404     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
405     // elements we want.
406     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
407       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
408               ValueVT.getVectorElementCount().getKnownMinValue()) &&
409              (PartEVT.getVectorElementCount().isScalable() ==
410               ValueVT.getVectorElementCount().isScalable()) &&
411              "Cannot narrow, it would be a lossy transformation");
412       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
413                          DAG.getVectorIdxConstant(0, DL));
414     }
415 
416     // Vector/Vector bitcast.
417     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
418       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419 
420     assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
421       "Cannot handle this kind of promotion");
422     // Promoted vector extract
423     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
424 
425   }
426 
427   // Trivial bitcast if the types are the same size and the destination
428   // vector type is legal.
429   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
430       TLI.isTypeLegal(ValueVT))
431     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
432 
433   if (ValueVT.getVectorNumElements() != 1) {
434      // Certain ABIs require that vectors are passed as integers. For vectors
435      // are the same size, this is an obvious bitcast.
436      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
437        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438      } else if (ValueVT.bitsLT(PartEVT)) {
439        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
440        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
441        // Drop the extra bits.
442        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
443        return DAG.getBitcast(ValueVT, Val);
444      }
445 
446      diagnosePossiblyInvalidConstraint(
447          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
448      return DAG.getUNDEF(ValueVT);
449   }
450 
451   // Handle cases such as i8 -> <1 x i1>
452   EVT ValueSVT = ValueVT.getVectorElementType();
453   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
454     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
455       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
456     else
457       Val = ValueVT.isFloatingPoint()
458                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
459                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
460   }
461 
462   return DAG.getBuildVector(ValueVT, DL, Val);
463 }
464 
465 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
466                                  SDValue Val, SDValue *Parts, unsigned NumParts,
467                                  MVT PartVT, const Value *V,
468                                  Optional<CallingConv::ID> CallConv);
469 
470 /// getCopyToParts - Create a series of nodes that contain the specified value
471 /// split into legal parts.  If the parts contain more bits than Val, then, for
472 /// integers, ExtendKind can be used to specify how to generate the extra bits.
473 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
474                            SDValue *Parts, unsigned NumParts, MVT PartVT,
475                            const Value *V,
476                            Optional<CallingConv::ID> CallConv = None,
477                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
478   // Let the target split the parts if it wants to
479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
480   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
481                                       CallConv))
482     return;
483   EVT ValueVT = Val.getValueType();
484 
485   // Handle the vector case separately.
486   if (ValueVT.isVector())
487     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
488                                 CallConv);
489 
490   unsigned PartBits = PartVT.getSizeInBits();
491   unsigned OrigNumParts = NumParts;
492   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
493          "Copying to an illegal type!");
494 
495   if (NumParts == 0)
496     return;
497 
498   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
499   EVT PartEVT = PartVT;
500   if (PartEVT == ValueVT) {
501     assert(NumParts == 1 && "No-op copy with multiple parts!");
502     Parts[0] = Val;
503     return;
504   }
505 
506   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
507     // If the parts cover more bits than the value has, promote the value.
508     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
509       assert(NumParts == 1 && "Do not know what to promote to!");
510       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
511     } else {
512       if (ValueVT.isFloatingPoint()) {
513         // FP values need to be bitcast, then extended if they are being put
514         // into a larger container.
515         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
516         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
517       }
518       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
519              ValueVT.isInteger() &&
520              "Unknown mismatch!");
521       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
522       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
523       if (PartVT == MVT::x86mmx)
524         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
525     }
526   } else if (PartBits == ValueVT.getSizeInBits()) {
527     // Different types of the same size.
528     assert(NumParts == 1 && PartEVT != ValueVT);
529     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
530   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
531     // If the parts cover less bits than value has, truncate the value.
532     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
533            ValueVT.isInteger() &&
534            "Unknown mismatch!");
535     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
536     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
537     if (PartVT == MVT::x86mmx)
538       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   }
540 
541   // The value may have changed - recompute ValueVT.
542   ValueVT = Val.getValueType();
543   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
544          "Failed to tile the value with PartVT!");
545 
546   if (NumParts == 1) {
547     if (PartEVT != ValueVT) {
548       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
549                                         "scalar-to-vector conversion failed");
550       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
551     }
552 
553     Parts[0] = Val;
554     return;
555   }
556 
557   // Expand the value into multiple parts.
558   if (NumParts & (NumParts - 1)) {
559     // The number of parts is not a power of 2.  Split off and copy the tail.
560     assert(PartVT.isInteger() && ValueVT.isInteger() &&
561            "Do not know what to expand to!");
562     unsigned RoundParts = 1 << Log2_32(NumParts);
563     unsigned RoundBits = RoundParts * PartBits;
564     unsigned OddParts = NumParts - RoundParts;
565     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
566       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
567 
568     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
569                    CallConv);
570 
571     if (DAG.getDataLayout().isBigEndian())
572       // The odd parts were reversed by getCopyToParts - unreverse them.
573       std::reverse(Parts + RoundParts, Parts + NumParts);
574 
575     NumParts = RoundParts;
576     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
577     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
578   }
579 
580   // The number of parts is a power of 2.  Repeatedly bisect the value using
581   // EXTRACT_ELEMENT.
582   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
583                          EVT::getIntegerVT(*DAG.getContext(),
584                                            ValueVT.getSizeInBits()),
585                          Val);
586 
587   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
588     for (unsigned i = 0; i < NumParts; i += StepSize) {
589       unsigned ThisBits = StepSize * PartBits / 2;
590       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
591       SDValue &Part0 = Parts[i];
592       SDValue &Part1 = Parts[i+StepSize/2];
593 
594       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
595                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
596       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
597                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
598 
599       if (ThisBits == PartBits && ThisVT != PartVT) {
600         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
601         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
602       }
603     }
604   }
605 
606   if (DAG.getDataLayout().isBigEndian())
607     std::reverse(Parts, Parts + OrigNumParts);
608 }
609 
610 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
611                                      const SDLoc &DL, EVT PartVT) {
612   if (!PartVT.isVector())
613     return SDValue();
614 
615   EVT ValueVT = Val.getValueType();
616   ElementCount PartNumElts = PartVT.getVectorElementCount();
617   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
618 
619   // We only support widening vectors with equivalent element types and
620   // fixed/scalable properties. If a target needs to widen a fixed-length type
621   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
622   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
623       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
624       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
625     return SDValue();
626 
627   // Widening a scalable vector to another scalable vector is done by inserting
628   // the vector into a larger undef one.
629   if (PartNumElts.isScalable())
630     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
631                        Val, DAG.getVectorIdxConstant(0, DL));
632 
633   EVT ElementVT = PartVT.getVectorElementType();
634   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
635   // undef elements.
636   SmallVector<SDValue, 16> Ops;
637   DAG.ExtractVectorElements(Val, Ops);
638   SDValue EltUndef = DAG.getUNDEF(ElementVT);
639   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
640 
641   // FIXME: Use CONCAT for 2x -> 4x.
642   return DAG.getBuildVector(PartVT, DL, Ops);
643 }
644 
645 /// getCopyToPartsVector - Create a series of nodes that contain the specified
646 /// value split into legal parts.
647 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
648                                  SDValue Val, SDValue *Parts, unsigned NumParts,
649                                  MVT PartVT, const Value *V,
650                                  Optional<CallingConv::ID> CallConv) {
651   EVT ValueVT = Val.getValueType();
652   assert(ValueVT.isVector() && "Not a vector");
653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
654   const bool IsABIRegCopy = CallConv.hasValue();
655 
656   if (NumParts == 1) {
657     EVT PartEVT = PartVT;
658     if (PartEVT == ValueVT) {
659       // Nothing to do.
660     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
661       // Bitconvert vector->vector case.
662       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
663     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
664       Val = Widened;
665     } else if (PartVT.isVector() &&
666                PartEVT.getVectorElementType().bitsGE(
667                    ValueVT.getVectorElementType()) &&
668                PartEVT.getVectorElementCount() ==
669                    ValueVT.getVectorElementCount()) {
670 
671       // Promoted vector extract
672       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
673     } else {
674       if (ValueVT.getVectorElementCount().isScalar()) {
675         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
676                           DAG.getVectorIdxConstant(0, DL));
677       } else {
678         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
679         assert(PartVT.getFixedSizeInBits() > ValueSize &&
680                "lossy conversion of vector to scalar type");
681         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
682         Val = DAG.getBitcast(IntermediateType, Val);
683         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
684       }
685     }
686 
687     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
688     Parts[0] = Val;
689     return;
690   }
691 
692   // Handle a multi-element vector.
693   EVT IntermediateVT;
694   MVT RegisterVT;
695   unsigned NumIntermediates;
696   unsigned NumRegs;
697   if (IsABIRegCopy) {
698     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
699         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
700         NumIntermediates, RegisterVT);
701   } else {
702     NumRegs =
703         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
704                                    NumIntermediates, RegisterVT);
705   }
706 
707   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
708   NumParts = NumRegs; // Silence a compiler warning.
709   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
710 
711   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
712          "Mixing scalable and fixed vectors when copying in parts");
713 
714   Optional<ElementCount> DestEltCnt;
715 
716   if (IntermediateVT.isVector())
717     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
718   else
719     DestEltCnt = ElementCount::getFixed(NumIntermediates);
720 
721   EVT BuiltVectorTy = EVT::getVectorVT(
722       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
723 
724   if (ValueVT == BuiltVectorTy) {
725     // Nothing to do.
726   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
727     // Bitconvert vector->vector case.
728     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
729   } else if (SDValue Widened =
730                  widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
731     Val = Widened;
732   } else if (BuiltVectorTy.getVectorElementType().bitsGE(
733                  ValueVT.getVectorElementType()) &&
734              BuiltVectorTy.getVectorElementCount() ==
735                  ValueVT.getVectorElementCount()) {
736     // Promoted vector extract
737     Val = DAG.getAnyExtOrTrunc(Val, DL, BuiltVectorTy);
738   }
739 
740   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
741 
742   // Split the vector into intermediate operands.
743   SmallVector<SDValue, 8> Ops(NumIntermediates);
744   for (unsigned i = 0; i != NumIntermediates; ++i) {
745     if (IntermediateVT.isVector()) {
746       // This does something sensible for scalable vectors - see the
747       // definition of EXTRACT_SUBVECTOR for further details.
748       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
749       Ops[i] =
750           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
751                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
752     } else {
753       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
754                            DAG.getVectorIdxConstant(i, DL));
755     }
756   }
757 
758   // Split the intermediate operands into legal parts.
759   if (NumParts == NumIntermediates) {
760     // If the register was not expanded, promote or copy the value,
761     // as appropriate.
762     for (unsigned i = 0; i != NumParts; ++i)
763       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
764   } else if (NumParts > 0) {
765     // If the intermediate type was expanded, split each the value into
766     // legal parts.
767     assert(NumIntermediates != 0 && "division by zero");
768     assert(NumParts % NumIntermediates == 0 &&
769            "Must expand into a divisible number of parts!");
770     unsigned Factor = NumParts / NumIntermediates;
771     for (unsigned i = 0; i != NumIntermediates; ++i)
772       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
773                      CallConv);
774   }
775 }
776 
777 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
778                            EVT valuevt, Optional<CallingConv::ID> CC)
779     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
780       RegCount(1, regs.size()), CallConv(CC) {}
781 
782 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
783                            const DataLayout &DL, unsigned Reg, Type *Ty,
784                            Optional<CallingConv::ID> CC) {
785   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
786 
787   CallConv = CC;
788 
789   for (EVT ValueVT : ValueVTs) {
790     unsigned NumRegs =
791         isABIMangled()
792             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
793             : TLI.getNumRegisters(Context, ValueVT);
794     MVT RegisterVT =
795         isABIMangled()
796             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
797             : TLI.getRegisterType(Context, ValueVT);
798     for (unsigned i = 0; i != NumRegs; ++i)
799       Regs.push_back(Reg + i);
800     RegVTs.push_back(RegisterVT);
801     RegCount.push_back(NumRegs);
802     Reg += NumRegs;
803   }
804 }
805 
806 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
807                                       FunctionLoweringInfo &FuncInfo,
808                                       const SDLoc &dl, SDValue &Chain,
809                                       SDValue *Flag, const Value *V) const {
810   // A Value with type {} or [0 x %t] needs no registers.
811   if (ValueVTs.empty())
812     return SDValue();
813 
814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
815 
816   // Assemble the legal parts into the final values.
817   SmallVector<SDValue, 4> Values(ValueVTs.size());
818   SmallVector<SDValue, 8> Parts;
819   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
820     // Copy the legal parts from the registers.
821     EVT ValueVT = ValueVTs[Value];
822     unsigned NumRegs = RegCount[Value];
823     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
824                                           *DAG.getContext(),
825                                           CallConv.getValue(), RegVTs[Value])
826                                     : RegVTs[Value];
827 
828     Parts.resize(NumRegs);
829     for (unsigned i = 0; i != NumRegs; ++i) {
830       SDValue P;
831       if (!Flag) {
832         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
833       } else {
834         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
835         *Flag = P.getValue(2);
836       }
837 
838       Chain = P.getValue(1);
839       Parts[i] = P;
840 
841       // If the source register was virtual and if we know something about it,
842       // add an assert node.
843       if (!Register::isVirtualRegister(Regs[Part + i]) ||
844           !RegisterVT.isInteger())
845         continue;
846 
847       const FunctionLoweringInfo::LiveOutInfo *LOI =
848         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
849       if (!LOI)
850         continue;
851 
852       unsigned RegSize = RegisterVT.getScalarSizeInBits();
853       unsigned NumSignBits = LOI->NumSignBits;
854       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
855 
856       if (NumZeroBits == RegSize) {
857         // The current value is a zero.
858         // Explicitly express that as it would be easier for
859         // optimizations to kick in.
860         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
861         continue;
862       }
863 
864       // FIXME: We capture more information than the dag can represent.  For
865       // now, just use the tightest assertzext/assertsext possible.
866       bool isSExt;
867       EVT FromVT(MVT::Other);
868       if (NumZeroBits) {
869         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
870         isSExt = false;
871       } else if (NumSignBits > 1) {
872         FromVT =
873             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
874         isSExt = true;
875       } else {
876         continue;
877       }
878       // Add an assertion node.
879       assert(FromVT != MVT::Other);
880       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
881                              RegisterVT, P, DAG.getValueType(FromVT));
882     }
883 
884     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
885                                      RegisterVT, ValueVT, V, CallConv);
886     Part += NumRegs;
887     Parts.clear();
888   }
889 
890   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
891 }
892 
893 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
894                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
895                                  const Value *V,
896                                  ISD::NodeType PreferredExtendType) const {
897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
898   ISD::NodeType ExtendKind = PreferredExtendType;
899 
900   // Get the list of the values's legal parts.
901   unsigned NumRegs = Regs.size();
902   SmallVector<SDValue, 8> Parts(NumRegs);
903   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
904     unsigned NumParts = RegCount[Value];
905 
906     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
907                                           *DAG.getContext(),
908                                           CallConv.getValue(), RegVTs[Value])
909                                     : RegVTs[Value];
910 
911     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
912       ExtendKind = ISD::ZERO_EXTEND;
913 
914     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
915                    NumParts, RegisterVT, V, CallConv, ExtendKind);
916     Part += NumParts;
917   }
918 
919   // Copy the parts into the registers.
920   SmallVector<SDValue, 8> Chains(NumRegs);
921   for (unsigned i = 0; i != NumRegs; ++i) {
922     SDValue Part;
923     if (!Flag) {
924       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
925     } else {
926       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
927       *Flag = Part.getValue(1);
928     }
929 
930     Chains[i] = Part.getValue(0);
931   }
932 
933   if (NumRegs == 1 || Flag)
934     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
935     // flagged to it. That is the CopyToReg nodes and the user are considered
936     // a single scheduling unit. If we create a TokenFactor and return it as
937     // chain, then the TokenFactor is both a predecessor (operand) of the
938     // user as well as a successor (the TF operands are flagged to the user).
939     // c1, f1 = CopyToReg
940     // c2, f2 = CopyToReg
941     // c3     = TokenFactor c1, c2
942     // ...
943     //        = op c3, ..., f2
944     Chain = Chains[NumRegs-1];
945   else
946     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
947 }
948 
949 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
950                                         unsigned MatchingIdx, const SDLoc &dl,
951                                         SelectionDAG &DAG,
952                                         std::vector<SDValue> &Ops) const {
953   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
954 
955   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
956   if (HasMatching)
957     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
958   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
959     // Put the register class of the virtual registers in the flag word.  That
960     // way, later passes can recompute register class constraints for inline
961     // assembly as well as normal instructions.
962     // Don't do this for tied operands that can use the regclass information
963     // from the def.
964     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
965     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
966     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
967   }
968 
969   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
970   Ops.push_back(Res);
971 
972   if (Code == InlineAsm::Kind_Clobber) {
973     // Clobbers should always have a 1:1 mapping with registers, and may
974     // reference registers that have illegal (e.g. vector) types. Hence, we
975     // shouldn't try to apply any sort of splitting logic to them.
976     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
977            "No 1:1 mapping from clobbers to regs?");
978     Register SP = TLI.getStackPointerRegisterToSaveRestore();
979     (void)SP;
980     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
981       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
982       assert(
983           (Regs[I] != SP ||
984            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
985           "If we clobbered the stack pointer, MFI should know about it.");
986     }
987     return;
988   }
989 
990   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
991     MVT RegisterVT = RegVTs[Value];
992     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
993                                            RegisterVT);
994     for (unsigned i = 0; i != NumRegs; ++i) {
995       assert(Reg < Regs.size() && "Mismatch in # registers expected");
996       unsigned TheReg = Regs[Reg++];
997       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
998     }
999   }
1000 }
1001 
1002 SmallVector<std::pair<unsigned, TypeSize>, 4>
1003 RegsForValue::getRegsAndSizes() const {
1004   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1005   unsigned I = 0;
1006   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1007     unsigned RegCount = std::get<0>(CountAndVT);
1008     MVT RegisterVT = std::get<1>(CountAndVT);
1009     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1010     for (unsigned E = I + RegCount; I != E; ++I)
1011       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1012   }
1013   return OutVec;
1014 }
1015 
1016 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1017                                const TargetLibraryInfo *li) {
1018   AA = aa;
1019   GFI = gfi;
1020   LibInfo = li;
1021   DL = &DAG.getDataLayout();
1022   Context = DAG.getContext();
1023   LPadToCallSiteMap.clear();
1024   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1025 }
1026 
1027 void SelectionDAGBuilder::clear() {
1028   NodeMap.clear();
1029   UnusedArgNodeMap.clear();
1030   PendingLoads.clear();
1031   PendingExports.clear();
1032   PendingConstrainedFP.clear();
1033   PendingConstrainedFPStrict.clear();
1034   CurInst = nullptr;
1035   HasTailCall = false;
1036   SDNodeOrder = LowestSDNodeOrder;
1037   StatepointLowering.clear();
1038 }
1039 
1040 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1041   DanglingDebugInfoMap.clear();
1042 }
1043 
1044 // Update DAG root to include dependencies on Pending chains.
1045 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1046   SDValue Root = DAG.getRoot();
1047 
1048   if (Pending.empty())
1049     return Root;
1050 
1051   // Add current root to PendingChains, unless we already indirectly
1052   // depend on it.
1053   if (Root.getOpcode() != ISD::EntryToken) {
1054     unsigned i = 0, e = Pending.size();
1055     for (; i != e; ++i) {
1056       assert(Pending[i].getNode()->getNumOperands() > 1);
1057       if (Pending[i].getNode()->getOperand(0) == Root)
1058         break;  // Don't add the root if we already indirectly depend on it.
1059     }
1060 
1061     if (i == e)
1062       Pending.push_back(Root);
1063   }
1064 
1065   if (Pending.size() == 1)
1066     Root = Pending[0];
1067   else
1068     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1069 
1070   DAG.setRoot(Root);
1071   Pending.clear();
1072   return Root;
1073 }
1074 
1075 SDValue SelectionDAGBuilder::getMemoryRoot() {
1076   return updateRoot(PendingLoads);
1077 }
1078 
1079 SDValue SelectionDAGBuilder::getRoot() {
1080   // Chain up all pending constrained intrinsics together with all
1081   // pending loads, by simply appending them to PendingLoads and
1082   // then calling getMemoryRoot().
1083   PendingLoads.reserve(PendingLoads.size() +
1084                        PendingConstrainedFP.size() +
1085                        PendingConstrainedFPStrict.size());
1086   PendingLoads.append(PendingConstrainedFP.begin(),
1087                       PendingConstrainedFP.end());
1088   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1089                       PendingConstrainedFPStrict.end());
1090   PendingConstrainedFP.clear();
1091   PendingConstrainedFPStrict.clear();
1092   return getMemoryRoot();
1093 }
1094 
1095 SDValue SelectionDAGBuilder::getControlRoot() {
1096   // We need to emit pending fpexcept.strict constrained intrinsics,
1097   // so append them to the PendingExports list.
1098   PendingExports.append(PendingConstrainedFPStrict.begin(),
1099                         PendingConstrainedFPStrict.end());
1100   PendingConstrainedFPStrict.clear();
1101   return updateRoot(PendingExports);
1102 }
1103 
1104 void SelectionDAGBuilder::visit(const Instruction &I) {
1105   // Set up outgoing PHI node register values before emitting the terminator.
1106   if (I.isTerminator()) {
1107     HandlePHINodesInSuccessorBlocks(I.getParent());
1108   }
1109 
1110   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1111   if (!isa<DbgInfoIntrinsic>(I))
1112     ++SDNodeOrder;
1113 
1114   CurInst = &I;
1115 
1116   visit(I.getOpcode(), I);
1117 
1118   if (!I.isTerminator() && !HasTailCall &&
1119       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1120     CopyToExportRegsIfNeeded(&I);
1121 
1122   CurInst = nullptr;
1123 }
1124 
1125 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1126   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1127 }
1128 
1129 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1130   // Note: this doesn't use InstVisitor, because it has to work with
1131   // ConstantExpr's in addition to instructions.
1132   switch (Opcode) {
1133   default: llvm_unreachable("Unknown instruction type encountered!");
1134     // Build the switch statement using the Instruction.def file.
1135 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1136     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1137 #include "llvm/IR/Instruction.def"
1138   }
1139 }
1140 
1141 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1142                                                DebugLoc DL, unsigned Order) {
1143   // We treat variadic dbg_values differently at this stage.
1144   if (DI->hasArgList()) {
1145     // For variadic dbg_values we will now insert an undef.
1146     // FIXME: We can potentially recover these!
1147     SmallVector<SDDbgOperand, 2> Locs;
1148     for (const Value *V : DI->getValues()) {
1149       auto Undef = UndefValue::get(V->getType());
1150       Locs.push_back(SDDbgOperand::fromConst(Undef));
1151     }
1152     SDDbgValue *SDV = DAG.getDbgValueList(
1153         DI->getVariable(), DI->getExpression(), Locs, {},
1154         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1155     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1156   } else {
1157     // TODO: Dangling debug info will eventually either be resolved or produce
1158     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1159     // between the original dbg.value location and its resolved DBG_VALUE,
1160     // which we should ideally fill with an extra Undef DBG_VALUE.
1161     assert(DI->getNumVariableLocationOps() == 1 &&
1162            "DbgValueInst without an ArgList should have a single location "
1163            "operand.");
1164     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1165   }
1166 }
1167 
1168 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1169                                                 const DIExpression *Expr) {
1170   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1171     const DbgValueInst *DI = DDI.getDI();
1172     DIVariable *DanglingVariable = DI->getVariable();
1173     DIExpression *DanglingExpr = DI->getExpression();
1174     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1175       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1176       return true;
1177     }
1178     return false;
1179   };
1180 
1181   for (auto &DDIMI : DanglingDebugInfoMap) {
1182     DanglingDebugInfoVector &DDIV = DDIMI.second;
1183 
1184     // If debug info is to be dropped, run it through final checks to see
1185     // whether it can be salvaged.
1186     for (auto &DDI : DDIV)
1187       if (isMatchingDbgValue(DDI))
1188         salvageUnresolvedDbgValue(DDI);
1189 
1190     erase_if(DDIV, isMatchingDbgValue);
1191   }
1192 }
1193 
1194 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1195 // generate the debug data structures now that we've seen its definition.
1196 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1197                                                    SDValue Val) {
1198   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1199   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1200     return;
1201 
1202   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1203   for (auto &DDI : DDIV) {
1204     const DbgValueInst *DI = DDI.getDI();
1205     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1206     assert(DI && "Ill-formed DanglingDebugInfo");
1207     DebugLoc dl = DDI.getdl();
1208     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1209     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1210     DILocalVariable *Variable = DI->getVariable();
1211     DIExpression *Expr = DI->getExpression();
1212     assert(Variable->isValidLocationForIntrinsic(dl) &&
1213            "Expected inlined-at fields to agree");
1214     SDDbgValue *SDV;
1215     if (Val.getNode()) {
1216       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1217       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1218       // we couldn't resolve it directly when examining the DbgValue intrinsic
1219       // in the first place we should not be more successful here). Unless we
1220       // have some test case that prove this to be correct we should avoid
1221       // calling EmitFuncArgumentDbgValue here.
1222       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1223         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1224                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1225         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1226         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1227         // inserted after the definition of Val when emitting the instructions
1228         // after ISel. An alternative could be to teach
1229         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1230         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1231                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1232                    << ValSDNodeOrder << "\n");
1233         SDV = getDbgValue(Val, Variable, Expr, dl,
1234                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1235         DAG.AddDbgValue(SDV, false);
1236       } else
1237         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1238                           << "in EmitFuncArgumentDbgValue\n");
1239     } else {
1240       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1241       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1242       auto SDV =
1243           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1244       DAG.AddDbgValue(SDV, false);
1245     }
1246   }
1247   DDIV.clear();
1248 }
1249 
1250 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1251   // TODO: For the variadic implementation, instead of only checking the fail
1252   // state of `handleDebugValue`, we need know specifically which values were
1253   // invalid, so that we attempt to salvage only those values when processing
1254   // a DIArgList.
1255   assert(!DDI.getDI()->hasArgList() &&
1256          "Not implemented for variadic dbg_values");
1257   Value *V = DDI.getDI()->getValue(0);
1258   DILocalVariable *Var = DDI.getDI()->getVariable();
1259   DIExpression *Expr = DDI.getDI()->getExpression();
1260   DebugLoc DL = DDI.getdl();
1261   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1262   unsigned SDOrder = DDI.getSDNodeOrder();
1263   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1264   // that DW_OP_stack_value is desired.
1265   assert(isa<DbgValueInst>(DDI.getDI()));
1266   bool StackValue = true;
1267 
1268   // Can this Value can be encoded without any further work?
1269   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1270     return;
1271 
1272   // Attempt to salvage back through as many instructions as possible. Bail if
1273   // a non-instruction is seen, such as a constant expression or global
1274   // variable. FIXME: Further work could recover those too.
1275   while (isa<Instruction>(V)) {
1276     Instruction &VAsInst = *cast<Instruction>(V);
1277     // Temporary "0", awaiting real implementation.
1278     SmallVector<Value *, 4> AdditionalValues;
1279     DIExpression *SalvagedExpr =
1280         salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0, AdditionalValues);
1281 
1282     // If we cannot salvage any further, and haven't yet found a suitable debug
1283     // expression, bail out.
1284     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1285     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1286     // here for variadic dbg_values, remove that condition.
1287     if (!SalvagedExpr || !AdditionalValues.empty())
1288       break;
1289 
1290     // New value and expr now represent this debuginfo.
1291     V = VAsInst.getOperand(0);
1292     Expr = SalvagedExpr;
1293 
1294     // Some kind of simplification occurred: check whether the operand of the
1295     // salvaged debug expression can be encoded in this DAG.
1296     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1297                          /*IsVariadic=*/false)) {
1298       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1299                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1300       return;
1301     }
1302   }
1303 
1304   // This was the final opportunity to salvage this debug information, and it
1305   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1306   // any earlier variable location.
1307   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1308   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1309   DAG.AddDbgValue(SDV, false);
1310 
1311   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1312                     << "\n");
1313   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1314                     << "\n");
1315 }
1316 
1317 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1318                                            DILocalVariable *Var,
1319                                            DIExpression *Expr, DebugLoc dl,
1320                                            DebugLoc InstDL, unsigned Order,
1321                                            bool IsVariadic) {
1322   if (Values.empty())
1323     return true;
1324   SmallVector<SDDbgOperand> LocationOps;
1325   SmallVector<SDNode *> Dependencies;
1326   for (const Value *V : Values) {
1327     // Constant value.
1328     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1329         isa<ConstantPointerNull>(V)) {
1330       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1331       continue;
1332     }
1333 
1334     // If the Value is a frame index, we can create a FrameIndex debug value
1335     // without relying on the DAG at all.
1336     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1337       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1338       if (SI != FuncInfo.StaticAllocaMap.end()) {
1339         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1340         continue;
1341       }
1342     }
1343 
1344     // Do not use getValue() in here; we don't want to generate code at
1345     // this point if it hasn't been done yet.
1346     SDValue N = NodeMap[V];
1347     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1348       N = UnusedArgNodeMap[V];
1349     if (N.getNode()) {
1350       // Only emit func arg dbg value for non-variadic dbg.values for now.
1351       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1352         return true;
1353       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1354         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1355         // describe stack slot locations.
1356         //
1357         // Consider "int x = 0; int *px = &x;". There are two kinds of
1358         // interesting debug values here after optimization:
1359         //
1360         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1361         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1362         //
1363         // Both describe the direct values of their associated variables.
1364         Dependencies.push_back(N.getNode());
1365         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1366         continue;
1367       }
1368       LocationOps.emplace_back(
1369           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1370       continue;
1371     }
1372 
1373     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1374     // Special rules apply for the first dbg.values of parameter variables in a
1375     // function. Identify them by the fact they reference Argument Values, that
1376     // they're parameters, and they are parameters of the current function. We
1377     // need to let them dangle until they get an SDNode.
1378     bool IsParamOfFunc =
1379         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1380     if (IsParamOfFunc)
1381       return false;
1382 
1383     // The value is not used in this block yet (or it would have an SDNode).
1384     // We still want the value to appear for the user if possible -- if it has
1385     // an associated VReg, we can refer to that instead.
1386     auto VMI = FuncInfo.ValueMap.find(V);
1387     if (VMI != FuncInfo.ValueMap.end()) {
1388       unsigned Reg = VMI->second;
1389       // If this is a PHI node, it may be split up into several MI PHI nodes
1390       // (in FunctionLoweringInfo::set).
1391       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1392                        V->getType(), None);
1393       if (RFV.occupiesMultipleRegs()) {
1394         // FIXME: We could potentially support variadic dbg_values here.
1395         if (IsVariadic)
1396           return false;
1397         unsigned Offset = 0;
1398         unsigned BitsToDescribe = 0;
1399         if (auto VarSize = Var->getSizeInBits())
1400           BitsToDescribe = *VarSize;
1401         if (auto Fragment = Expr->getFragmentInfo())
1402           BitsToDescribe = Fragment->SizeInBits;
1403         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1404           // Bail out if all bits are described already.
1405           if (Offset >= BitsToDescribe)
1406             break;
1407           // TODO: handle scalable vectors.
1408           unsigned RegisterSize = RegAndSize.second;
1409           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1410                                       ? BitsToDescribe - Offset
1411                                       : RegisterSize;
1412           auto FragmentExpr = DIExpression::createFragmentExpression(
1413               Expr, Offset, FragmentSize);
1414           if (!FragmentExpr)
1415             continue;
1416           SDDbgValue *SDV = DAG.getVRegDbgValue(
1417               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1418           DAG.AddDbgValue(SDV, false);
1419           Offset += RegisterSize;
1420         }
1421         return true;
1422       }
1423       // We can use simple vreg locations for variadic dbg_values as well.
1424       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1425       continue;
1426     }
1427     // We failed to create a SDDbgOperand for V.
1428     return false;
1429   }
1430 
1431   // We have created a SDDbgOperand for each Value in Values.
1432   // Should use Order instead of SDNodeOrder?
1433   assert(!LocationOps.empty());
1434   SDDbgValue *SDV =
1435       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1436                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1437   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1438   return true;
1439 }
1440 
1441 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1442   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1443   for (auto &Pair : DanglingDebugInfoMap)
1444     for (auto &DDI : Pair.second)
1445       salvageUnresolvedDbgValue(DDI);
1446   clearDanglingDebugInfo();
1447 }
1448 
1449 /// getCopyFromRegs - If there was virtual register allocated for the value V
1450 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1451 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1452   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1453   SDValue Result;
1454 
1455   if (It != FuncInfo.ValueMap.end()) {
1456     Register InReg = It->second;
1457 
1458     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1459                      DAG.getDataLayout(), InReg, Ty,
1460                      None); // This is not an ABI copy.
1461     SDValue Chain = DAG.getEntryNode();
1462     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1463                                  V);
1464     resolveDanglingDebugInfo(V, Result);
1465   }
1466 
1467   return Result;
1468 }
1469 
1470 /// getValue - Return an SDValue for the given Value.
1471 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1472   // If we already have an SDValue for this value, use it. It's important
1473   // to do this first, so that we don't create a CopyFromReg if we already
1474   // have a regular SDValue.
1475   SDValue &N = NodeMap[V];
1476   if (N.getNode()) return N;
1477 
1478   // If there's a virtual register allocated and initialized for this
1479   // value, use it.
1480   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1481     return copyFromReg;
1482 
1483   // Otherwise create a new SDValue and remember it.
1484   SDValue Val = getValueImpl(V);
1485   NodeMap[V] = Val;
1486   resolveDanglingDebugInfo(V, Val);
1487   return Val;
1488 }
1489 
1490 /// getNonRegisterValue - Return an SDValue for the given Value, but
1491 /// don't look in FuncInfo.ValueMap for a virtual register.
1492 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1493   // If we already have an SDValue for this value, use it.
1494   SDValue &N = NodeMap[V];
1495   if (N.getNode()) {
1496     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1497       // Remove the debug location from the node as the node is about to be used
1498       // in a location which may differ from the original debug location.  This
1499       // is relevant to Constant and ConstantFP nodes because they can appear
1500       // as constant expressions inside PHI nodes.
1501       N->setDebugLoc(DebugLoc());
1502     }
1503     return N;
1504   }
1505 
1506   // Otherwise create a new SDValue and remember it.
1507   SDValue Val = getValueImpl(V);
1508   NodeMap[V] = Val;
1509   resolveDanglingDebugInfo(V, Val);
1510   return Val;
1511 }
1512 
1513 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1514 /// Create an SDValue for the given value.
1515 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1516   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1517 
1518   if (const Constant *C = dyn_cast<Constant>(V)) {
1519     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1520 
1521     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1522       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1523 
1524     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1525       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1526 
1527     if (isa<ConstantPointerNull>(C)) {
1528       unsigned AS = V->getType()->getPointerAddressSpace();
1529       return DAG.getConstant(0, getCurSDLoc(),
1530                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1531     }
1532 
1533     if (match(C, m_VScale(DAG.getDataLayout())))
1534       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1535 
1536     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1537       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1538 
1539     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1540       return DAG.getUNDEF(VT);
1541 
1542     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1543       visit(CE->getOpcode(), *CE);
1544       SDValue N1 = NodeMap[V];
1545       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1546       return N1;
1547     }
1548 
1549     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1550       SmallVector<SDValue, 4> Constants;
1551       for (const Use &U : C->operands()) {
1552         SDNode *Val = getValue(U).getNode();
1553         // If the operand is an empty aggregate, there are no values.
1554         if (!Val) continue;
1555         // Add each leaf value from the operand to the Constants list
1556         // to form a flattened list of all the values.
1557         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1558           Constants.push_back(SDValue(Val, i));
1559       }
1560 
1561       return DAG.getMergeValues(Constants, getCurSDLoc());
1562     }
1563 
1564     if (const ConstantDataSequential *CDS =
1565           dyn_cast<ConstantDataSequential>(C)) {
1566       SmallVector<SDValue, 4> Ops;
1567       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1568         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1569         // Add each leaf value from the operand to the Constants list
1570         // to form a flattened list of all the values.
1571         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1572           Ops.push_back(SDValue(Val, i));
1573       }
1574 
1575       if (isa<ArrayType>(CDS->getType()))
1576         return DAG.getMergeValues(Ops, getCurSDLoc());
1577       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1578     }
1579 
1580     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1581       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1582              "Unknown struct or array constant!");
1583 
1584       SmallVector<EVT, 4> ValueVTs;
1585       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1586       unsigned NumElts = ValueVTs.size();
1587       if (NumElts == 0)
1588         return SDValue(); // empty struct
1589       SmallVector<SDValue, 4> Constants(NumElts);
1590       for (unsigned i = 0; i != NumElts; ++i) {
1591         EVT EltVT = ValueVTs[i];
1592         if (isa<UndefValue>(C))
1593           Constants[i] = DAG.getUNDEF(EltVT);
1594         else if (EltVT.isFloatingPoint())
1595           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1596         else
1597           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1598       }
1599 
1600       return DAG.getMergeValues(Constants, getCurSDLoc());
1601     }
1602 
1603     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1604       return DAG.getBlockAddress(BA, VT);
1605 
1606     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1607       return getValue(Equiv->getGlobalValue());
1608 
1609     VectorType *VecTy = cast<VectorType>(V->getType());
1610 
1611     // Now that we know the number and type of the elements, get that number of
1612     // elements into the Ops array based on what kind of constant it is.
1613     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1614       SmallVector<SDValue, 16> Ops;
1615       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1616       for (unsigned i = 0; i != NumElements; ++i)
1617         Ops.push_back(getValue(CV->getOperand(i)));
1618 
1619       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1620     } else if (isa<ConstantAggregateZero>(C)) {
1621       EVT EltVT =
1622           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1623 
1624       SDValue Op;
1625       if (EltVT.isFloatingPoint())
1626         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1627       else
1628         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1629 
1630       if (isa<ScalableVectorType>(VecTy))
1631         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1632       else {
1633         SmallVector<SDValue, 16> Ops;
1634         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1635         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1636       }
1637     }
1638     llvm_unreachable("Unknown vector constant");
1639   }
1640 
1641   // If this is a static alloca, generate it as the frameindex instead of
1642   // computation.
1643   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1644     DenseMap<const AllocaInst*, int>::iterator SI =
1645       FuncInfo.StaticAllocaMap.find(AI);
1646     if (SI != FuncInfo.StaticAllocaMap.end())
1647       return DAG.getFrameIndex(SI->second,
1648                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1649   }
1650 
1651   // If this is an instruction which fast-isel has deferred, select it now.
1652   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1653     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1654 
1655     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1656                      Inst->getType(), None);
1657     SDValue Chain = DAG.getEntryNode();
1658     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1659   }
1660 
1661   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1662     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1663   }
1664   llvm_unreachable("Can't get register for value!");
1665 }
1666 
1667 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1668   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1669   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1670   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1671   bool IsSEH = isAsynchronousEHPersonality(Pers);
1672   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1673   if (!IsSEH)
1674     CatchPadMBB->setIsEHScopeEntry();
1675   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1676   if (IsMSVCCXX || IsCoreCLR)
1677     CatchPadMBB->setIsEHFuncletEntry();
1678 }
1679 
1680 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1681   // Update machine-CFG edge.
1682   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1683   FuncInfo.MBB->addSuccessor(TargetMBB);
1684   TargetMBB->setIsEHCatchretTarget(true);
1685   DAG.getMachineFunction().setHasEHCatchret(true);
1686 
1687   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1688   bool IsSEH = isAsynchronousEHPersonality(Pers);
1689   if (IsSEH) {
1690     // If this is not a fall-through branch or optimizations are switched off,
1691     // emit the branch.
1692     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1693         TM.getOptLevel() == CodeGenOpt::None)
1694       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1695                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1696     return;
1697   }
1698 
1699   // Figure out the funclet membership for the catchret's successor.
1700   // This will be used by the FuncletLayout pass to determine how to order the
1701   // BB's.
1702   // A 'catchret' returns to the outer scope's color.
1703   Value *ParentPad = I.getCatchSwitchParentPad();
1704   const BasicBlock *SuccessorColor;
1705   if (isa<ConstantTokenNone>(ParentPad))
1706     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1707   else
1708     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1709   assert(SuccessorColor && "No parent funclet for catchret!");
1710   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1711   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1712 
1713   // Create the terminator node.
1714   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1715                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1716                             DAG.getBasicBlock(SuccessorColorMBB));
1717   DAG.setRoot(Ret);
1718 }
1719 
1720 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1721   // Don't emit any special code for the cleanuppad instruction. It just marks
1722   // the start of an EH scope/funclet.
1723   FuncInfo.MBB->setIsEHScopeEntry();
1724   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1725   if (Pers != EHPersonality::Wasm_CXX) {
1726     FuncInfo.MBB->setIsEHFuncletEntry();
1727     FuncInfo.MBB->setIsCleanupFuncletEntry();
1728   }
1729 }
1730 
1731 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1732 // not match, it is OK to add only the first unwind destination catchpad to the
1733 // successors, because there will be at least one invoke instruction within the
1734 // catch scope that points to the next unwind destination, if one exists, so
1735 // CFGSort cannot mess up with BB sorting order.
1736 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1737 // call within them, and catchpads only consisting of 'catch (...)' have a
1738 // '__cxa_end_catch' call within them, both of which generate invokes in case
1739 // the next unwind destination exists, i.e., the next unwind destination is not
1740 // the caller.)
1741 //
1742 // Having at most one EH pad successor is also simpler and helps later
1743 // transformations.
1744 //
1745 // For example,
1746 // current:
1747 //   invoke void @foo to ... unwind label %catch.dispatch
1748 // catch.dispatch:
1749 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1750 // catch.start:
1751 //   ...
1752 //   ... in this BB or some other child BB dominated by this BB there will be an
1753 //   invoke that points to 'next' BB as an unwind destination
1754 //
1755 // next: ; We don't need to add this to 'current' BB's successor
1756 //   ...
1757 static void findWasmUnwindDestinations(
1758     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1759     BranchProbability Prob,
1760     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1761         &UnwindDests) {
1762   while (EHPadBB) {
1763     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1764     if (isa<CleanupPadInst>(Pad)) {
1765       // Stop on cleanup pads.
1766       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1767       UnwindDests.back().first->setIsEHScopeEntry();
1768       break;
1769     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1770       // Add the catchpad handlers to the possible destinations. We don't
1771       // continue to the unwind destination of the catchswitch for wasm.
1772       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1773         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1774         UnwindDests.back().first->setIsEHScopeEntry();
1775       }
1776       break;
1777     } else {
1778       continue;
1779     }
1780   }
1781 }
1782 
1783 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1784 /// many places it could ultimately go. In the IR, we have a single unwind
1785 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1786 /// This function skips over imaginary basic blocks that hold catchswitch
1787 /// instructions, and finds all the "real" machine
1788 /// basic block destinations. As those destinations may not be successors of
1789 /// EHPadBB, here we also calculate the edge probability to those destinations.
1790 /// The passed-in Prob is the edge probability to EHPadBB.
1791 static void findUnwindDestinations(
1792     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1793     BranchProbability Prob,
1794     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1795         &UnwindDests) {
1796   EHPersonality Personality =
1797     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1798   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1799   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1800   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1801   bool IsSEH = isAsynchronousEHPersonality(Personality);
1802 
1803   if (IsWasmCXX) {
1804     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1805     assert(UnwindDests.size() <= 1 &&
1806            "There should be at most one unwind destination for wasm");
1807     return;
1808   }
1809 
1810   while (EHPadBB) {
1811     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1812     BasicBlock *NewEHPadBB = nullptr;
1813     if (isa<LandingPadInst>(Pad)) {
1814       // Stop on landingpads. They are not funclets.
1815       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1816       break;
1817     } else if (isa<CleanupPadInst>(Pad)) {
1818       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1819       // personalities.
1820       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1821       UnwindDests.back().first->setIsEHScopeEntry();
1822       UnwindDests.back().first->setIsEHFuncletEntry();
1823       break;
1824     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1825       // Add the catchpad handlers to the possible destinations.
1826       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1827         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1828         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1829         if (IsMSVCCXX || IsCoreCLR)
1830           UnwindDests.back().first->setIsEHFuncletEntry();
1831         if (!IsSEH)
1832           UnwindDests.back().first->setIsEHScopeEntry();
1833       }
1834       NewEHPadBB = CatchSwitch->getUnwindDest();
1835     } else {
1836       continue;
1837     }
1838 
1839     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1840     if (BPI && NewEHPadBB)
1841       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1842     EHPadBB = NewEHPadBB;
1843   }
1844 }
1845 
1846 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1847   // Update successor info.
1848   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1849   auto UnwindDest = I.getUnwindDest();
1850   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1851   BranchProbability UnwindDestProb =
1852       (BPI && UnwindDest)
1853           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1854           : BranchProbability::getZero();
1855   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1856   for (auto &UnwindDest : UnwindDests) {
1857     UnwindDest.first->setIsEHPad();
1858     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1859   }
1860   FuncInfo.MBB->normalizeSuccProbs();
1861 
1862   // Create the terminator node.
1863   SDValue Ret =
1864       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1865   DAG.setRoot(Ret);
1866 }
1867 
1868 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1869   report_fatal_error("visitCatchSwitch not yet implemented!");
1870 }
1871 
1872 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1874   auto &DL = DAG.getDataLayout();
1875   SDValue Chain = getControlRoot();
1876   SmallVector<ISD::OutputArg, 8> Outs;
1877   SmallVector<SDValue, 8> OutVals;
1878 
1879   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1880   // lower
1881   //
1882   //   %val = call <ty> @llvm.experimental.deoptimize()
1883   //   ret <ty> %val
1884   //
1885   // differently.
1886   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1887     LowerDeoptimizingReturn();
1888     return;
1889   }
1890 
1891   if (!FuncInfo.CanLowerReturn) {
1892     unsigned DemoteReg = FuncInfo.DemoteRegister;
1893     const Function *F = I.getParent()->getParent();
1894 
1895     // Emit a store of the return value through the virtual register.
1896     // Leave Outs empty so that LowerReturn won't try to load return
1897     // registers the usual way.
1898     SmallVector<EVT, 1> PtrValueVTs;
1899     ComputeValueVTs(TLI, DL,
1900                     F->getReturnType()->getPointerTo(
1901                         DAG.getDataLayout().getAllocaAddrSpace()),
1902                     PtrValueVTs);
1903 
1904     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1905                                         DemoteReg, PtrValueVTs[0]);
1906     SDValue RetOp = getValue(I.getOperand(0));
1907 
1908     SmallVector<EVT, 4> ValueVTs, MemVTs;
1909     SmallVector<uint64_t, 4> Offsets;
1910     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1911                     &Offsets);
1912     unsigned NumValues = ValueVTs.size();
1913 
1914     SmallVector<SDValue, 4> Chains(NumValues);
1915     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1916     for (unsigned i = 0; i != NumValues; ++i) {
1917       // An aggregate return value cannot wrap around the address space, so
1918       // offsets to its parts don't wrap either.
1919       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1920                                            TypeSize::Fixed(Offsets[i]));
1921 
1922       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1923       if (MemVTs[i] != ValueVTs[i])
1924         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1925       Chains[i] = DAG.getStore(
1926           Chain, getCurSDLoc(), Val,
1927           // FIXME: better loc info would be nice.
1928           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1929           commonAlignment(BaseAlign, Offsets[i]));
1930     }
1931 
1932     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1933                         MVT::Other, Chains);
1934   } else if (I.getNumOperands() != 0) {
1935     SmallVector<EVT, 4> ValueVTs;
1936     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1937     unsigned NumValues = ValueVTs.size();
1938     if (NumValues) {
1939       SDValue RetOp = getValue(I.getOperand(0));
1940 
1941       const Function *F = I.getParent()->getParent();
1942 
1943       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1944           I.getOperand(0)->getType(), F->getCallingConv(),
1945           /*IsVarArg*/ false);
1946 
1947       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1948       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1949                                           Attribute::SExt))
1950         ExtendKind = ISD::SIGN_EXTEND;
1951       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1952                                                Attribute::ZExt))
1953         ExtendKind = ISD::ZERO_EXTEND;
1954 
1955       LLVMContext &Context = F->getContext();
1956       bool RetInReg = F->getAttributes().hasAttribute(
1957           AttributeList::ReturnIndex, Attribute::InReg);
1958 
1959       for (unsigned j = 0; j != NumValues; ++j) {
1960         EVT VT = ValueVTs[j];
1961 
1962         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1963           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1964 
1965         CallingConv::ID CC = F->getCallingConv();
1966 
1967         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1968         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1969         SmallVector<SDValue, 4> Parts(NumParts);
1970         getCopyToParts(DAG, getCurSDLoc(),
1971                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1972                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1973 
1974         // 'inreg' on function refers to return value
1975         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1976         if (RetInReg)
1977           Flags.setInReg();
1978 
1979         if (I.getOperand(0)->getType()->isPointerTy()) {
1980           Flags.setPointer();
1981           Flags.setPointerAddrSpace(
1982               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1983         }
1984 
1985         if (NeedsRegBlock) {
1986           Flags.setInConsecutiveRegs();
1987           if (j == NumValues - 1)
1988             Flags.setInConsecutiveRegsLast();
1989         }
1990 
1991         // Propagate extension type if any
1992         if (ExtendKind == ISD::SIGN_EXTEND)
1993           Flags.setSExt();
1994         else if (ExtendKind == ISD::ZERO_EXTEND)
1995           Flags.setZExt();
1996 
1997         for (unsigned i = 0; i < NumParts; ++i) {
1998           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1999                                         VT, /*isfixed=*/true, 0, 0));
2000           OutVals.push_back(Parts[i]);
2001         }
2002       }
2003     }
2004   }
2005 
2006   // Push in swifterror virtual register as the last element of Outs. This makes
2007   // sure swifterror virtual register will be returned in the swifterror
2008   // physical register.
2009   const Function *F = I.getParent()->getParent();
2010   if (TLI.supportSwiftError() &&
2011       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2012     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2013     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2014     Flags.setSwiftError();
2015     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
2016                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
2017                                   true /*isfixed*/, 1 /*origidx*/,
2018                                   0 /*partOffs*/));
2019     // Create SDNode for the swifterror virtual register.
2020     OutVals.push_back(
2021         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2022                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2023                         EVT(TLI.getPointerTy(DL))));
2024   }
2025 
2026   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2027   CallingConv::ID CallConv =
2028     DAG.getMachineFunction().getFunction().getCallingConv();
2029   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2030       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2031 
2032   // Verify that the target's LowerReturn behaved as expected.
2033   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2034          "LowerReturn didn't return a valid chain!");
2035 
2036   // Update the DAG with the new chain value resulting from return lowering.
2037   DAG.setRoot(Chain);
2038 }
2039 
2040 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2041 /// created for it, emit nodes to copy the value into the virtual
2042 /// registers.
2043 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2044   // Skip empty types
2045   if (V->getType()->isEmptyTy())
2046     return;
2047 
2048   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2049   if (VMI != FuncInfo.ValueMap.end()) {
2050     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2051     CopyValueToVirtualRegister(V, VMI->second);
2052   }
2053 }
2054 
2055 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2056 /// the current basic block, add it to ValueMap now so that we'll get a
2057 /// CopyTo/FromReg.
2058 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2059   // No need to export constants.
2060   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2061 
2062   // Already exported?
2063   if (FuncInfo.isExportedInst(V)) return;
2064 
2065   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2066   CopyValueToVirtualRegister(V, Reg);
2067 }
2068 
2069 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2070                                                      const BasicBlock *FromBB) {
2071   // The operands of the setcc have to be in this block.  We don't know
2072   // how to export them from some other block.
2073   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2074     // Can export from current BB.
2075     if (VI->getParent() == FromBB)
2076       return true;
2077 
2078     // Is already exported, noop.
2079     return FuncInfo.isExportedInst(V);
2080   }
2081 
2082   // If this is an argument, we can export it if the BB is the entry block or
2083   // if it is already exported.
2084   if (isa<Argument>(V)) {
2085     if (FromBB->isEntryBlock())
2086       return true;
2087 
2088     // Otherwise, can only export this if it is already exported.
2089     return FuncInfo.isExportedInst(V);
2090   }
2091 
2092   // Otherwise, constants can always be exported.
2093   return true;
2094 }
2095 
2096 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2097 BranchProbability
2098 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2099                                         const MachineBasicBlock *Dst) const {
2100   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2101   const BasicBlock *SrcBB = Src->getBasicBlock();
2102   const BasicBlock *DstBB = Dst->getBasicBlock();
2103   if (!BPI) {
2104     // If BPI is not available, set the default probability as 1 / N, where N is
2105     // the number of successors.
2106     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2107     return BranchProbability(1, SuccSize);
2108   }
2109   return BPI->getEdgeProbability(SrcBB, DstBB);
2110 }
2111 
2112 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2113                                                MachineBasicBlock *Dst,
2114                                                BranchProbability Prob) {
2115   if (!FuncInfo.BPI)
2116     Src->addSuccessorWithoutProb(Dst);
2117   else {
2118     if (Prob.isUnknown())
2119       Prob = getEdgeProbability(Src, Dst);
2120     Src->addSuccessor(Dst, Prob);
2121   }
2122 }
2123 
2124 static bool InBlock(const Value *V, const BasicBlock *BB) {
2125   if (const Instruction *I = dyn_cast<Instruction>(V))
2126     return I->getParent() == BB;
2127   return true;
2128 }
2129 
2130 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2131 /// This function emits a branch and is used at the leaves of an OR or an
2132 /// AND operator tree.
2133 void
2134 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2135                                                   MachineBasicBlock *TBB,
2136                                                   MachineBasicBlock *FBB,
2137                                                   MachineBasicBlock *CurBB,
2138                                                   MachineBasicBlock *SwitchBB,
2139                                                   BranchProbability TProb,
2140                                                   BranchProbability FProb,
2141                                                   bool InvertCond) {
2142   const BasicBlock *BB = CurBB->getBasicBlock();
2143 
2144   // If the leaf of the tree is a comparison, merge the condition into
2145   // the caseblock.
2146   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2147     // The operands of the cmp have to be in this block.  We don't know
2148     // how to export them from some other block.  If this is the first block
2149     // of the sequence, no exporting is needed.
2150     if (CurBB == SwitchBB ||
2151         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2152          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2153       ISD::CondCode Condition;
2154       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2155         ICmpInst::Predicate Pred =
2156             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2157         Condition = getICmpCondCode(Pred);
2158       } else {
2159         const FCmpInst *FC = cast<FCmpInst>(Cond);
2160         FCmpInst::Predicate Pred =
2161             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2162         Condition = getFCmpCondCode(Pred);
2163         if (TM.Options.NoNaNsFPMath)
2164           Condition = getFCmpCodeWithoutNaN(Condition);
2165       }
2166 
2167       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2168                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2169       SL->SwitchCases.push_back(CB);
2170       return;
2171     }
2172   }
2173 
2174   // Create a CaseBlock record representing this branch.
2175   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2176   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2177                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2178   SL->SwitchCases.push_back(CB);
2179 }
2180 
2181 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2182                                                MachineBasicBlock *TBB,
2183                                                MachineBasicBlock *FBB,
2184                                                MachineBasicBlock *CurBB,
2185                                                MachineBasicBlock *SwitchBB,
2186                                                Instruction::BinaryOps Opc,
2187                                                BranchProbability TProb,
2188                                                BranchProbability FProb,
2189                                                bool InvertCond) {
2190   // Skip over not part of the tree and remember to invert op and operands at
2191   // next level.
2192   Value *NotCond;
2193   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2194       InBlock(NotCond, CurBB->getBasicBlock())) {
2195     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2196                          !InvertCond);
2197     return;
2198   }
2199 
2200   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2201   const Value *BOpOp0, *BOpOp1;
2202   // Compute the effective opcode for Cond, taking into account whether it needs
2203   // to be inverted, e.g.
2204   //   and (not (or A, B)), C
2205   // gets lowered as
2206   //   and (and (not A, not B), C)
2207   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2208   if (BOp) {
2209     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2210                ? Instruction::And
2211                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2212                       ? Instruction::Or
2213                       : (Instruction::BinaryOps)0);
2214     if (InvertCond) {
2215       if (BOpc == Instruction::And)
2216         BOpc = Instruction::Or;
2217       else if (BOpc == Instruction::Or)
2218         BOpc = Instruction::And;
2219     }
2220   }
2221 
2222   // If this node is not part of the or/and tree, emit it as a branch.
2223   // Note that all nodes in the tree should have same opcode.
2224   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2225   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2226       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2227       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2228     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2229                                  TProb, FProb, InvertCond);
2230     return;
2231   }
2232 
2233   //  Create TmpBB after CurBB.
2234   MachineFunction::iterator BBI(CurBB);
2235   MachineFunction &MF = DAG.getMachineFunction();
2236   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2237   CurBB->getParent()->insert(++BBI, TmpBB);
2238 
2239   if (Opc == Instruction::Or) {
2240     // Codegen X | Y as:
2241     // BB1:
2242     //   jmp_if_X TBB
2243     //   jmp TmpBB
2244     // TmpBB:
2245     //   jmp_if_Y TBB
2246     //   jmp FBB
2247     //
2248 
2249     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2250     // The requirement is that
2251     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2252     //     = TrueProb for original BB.
2253     // Assuming the original probabilities are A and B, one choice is to set
2254     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2255     // A/(1+B) and 2B/(1+B). This choice assumes that
2256     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2257     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2258     // TmpBB, but the math is more complicated.
2259 
2260     auto NewTrueProb = TProb / 2;
2261     auto NewFalseProb = TProb / 2 + FProb;
2262     // Emit the LHS condition.
2263     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2264                          NewFalseProb, InvertCond);
2265 
2266     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2267     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2268     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2269     // Emit the RHS condition into TmpBB.
2270     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2271                          Probs[1], InvertCond);
2272   } else {
2273     assert(Opc == Instruction::And && "Unknown merge op!");
2274     // Codegen X & Y as:
2275     // BB1:
2276     //   jmp_if_X TmpBB
2277     //   jmp FBB
2278     // TmpBB:
2279     //   jmp_if_Y TBB
2280     //   jmp FBB
2281     //
2282     //  This requires creation of TmpBB after CurBB.
2283 
2284     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2285     // The requirement is that
2286     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2287     //     = FalseProb for original BB.
2288     // Assuming the original probabilities are A and B, one choice is to set
2289     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2290     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2291     // TrueProb for BB1 * FalseProb for TmpBB.
2292 
2293     auto NewTrueProb = TProb + FProb / 2;
2294     auto NewFalseProb = FProb / 2;
2295     // Emit the LHS condition.
2296     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2297                          NewFalseProb, InvertCond);
2298 
2299     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2300     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2301     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2302     // Emit the RHS condition into TmpBB.
2303     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2304                          Probs[1], InvertCond);
2305   }
2306 }
2307 
2308 /// If the set of cases should be emitted as a series of branches, return true.
2309 /// If we should emit this as a bunch of and/or'd together conditions, return
2310 /// false.
2311 bool
2312 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2313   if (Cases.size() != 2) return true;
2314 
2315   // If this is two comparisons of the same values or'd or and'd together, they
2316   // will get folded into a single comparison, so don't emit two blocks.
2317   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2318        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2319       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2320        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2321     return false;
2322   }
2323 
2324   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2325   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2326   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2327       Cases[0].CC == Cases[1].CC &&
2328       isa<Constant>(Cases[0].CmpRHS) &&
2329       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2330     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2331       return false;
2332     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2333       return false;
2334   }
2335 
2336   return true;
2337 }
2338 
2339 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2340   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2341 
2342   // Update machine-CFG edges.
2343   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2344 
2345   if (I.isUnconditional()) {
2346     // Update machine-CFG edges.
2347     BrMBB->addSuccessor(Succ0MBB);
2348 
2349     // If this is not a fall-through branch or optimizations are switched off,
2350     // emit the branch.
2351     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2352       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2353                               MVT::Other, getControlRoot(),
2354                               DAG.getBasicBlock(Succ0MBB)));
2355 
2356     return;
2357   }
2358 
2359   // If this condition is one of the special cases we handle, do special stuff
2360   // now.
2361   const Value *CondVal = I.getCondition();
2362   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2363 
2364   // If this is a series of conditions that are or'd or and'd together, emit
2365   // this as a sequence of branches instead of setcc's with and/or operations.
2366   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2367   // unpredictable branches, and vector extracts because those jumps are likely
2368   // expensive for any target), this should improve performance.
2369   // For example, instead of something like:
2370   //     cmp A, B
2371   //     C = seteq
2372   //     cmp D, E
2373   //     F = setle
2374   //     or C, F
2375   //     jnz foo
2376   // Emit:
2377   //     cmp A, B
2378   //     je foo
2379   //     cmp D, E
2380   //     jle foo
2381   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2382   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2383       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2384     Value *Vec;
2385     const Value *BOp0, *BOp1;
2386     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2387     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2388       Opcode = Instruction::And;
2389     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2390       Opcode = Instruction::Or;
2391 
2392     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2393                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2394       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2395                            getEdgeProbability(BrMBB, Succ0MBB),
2396                            getEdgeProbability(BrMBB, Succ1MBB),
2397                            /*InvertCond=*/false);
2398       // If the compares in later blocks need to use values not currently
2399       // exported from this block, export them now.  This block should always
2400       // be the first entry.
2401       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2402 
2403       // Allow some cases to be rejected.
2404       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2405         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2406           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2407           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2408         }
2409 
2410         // Emit the branch for this block.
2411         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2412         SL->SwitchCases.erase(SL->SwitchCases.begin());
2413         return;
2414       }
2415 
2416       // Okay, we decided not to do this, remove any inserted MBB's and clear
2417       // SwitchCases.
2418       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2419         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2420 
2421       SL->SwitchCases.clear();
2422     }
2423   }
2424 
2425   // Create a CaseBlock record representing this branch.
2426   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2427                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2428 
2429   // Use visitSwitchCase to actually insert the fast branch sequence for this
2430   // cond branch.
2431   visitSwitchCase(CB, BrMBB);
2432 }
2433 
2434 /// visitSwitchCase - Emits the necessary code to represent a single node in
2435 /// the binary search tree resulting from lowering a switch instruction.
2436 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2437                                           MachineBasicBlock *SwitchBB) {
2438   SDValue Cond;
2439   SDValue CondLHS = getValue(CB.CmpLHS);
2440   SDLoc dl = CB.DL;
2441 
2442   if (CB.CC == ISD::SETTRUE) {
2443     // Branch or fall through to TrueBB.
2444     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2445     SwitchBB->normalizeSuccProbs();
2446     if (CB.TrueBB != NextBlock(SwitchBB)) {
2447       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2448                               DAG.getBasicBlock(CB.TrueBB)));
2449     }
2450     return;
2451   }
2452 
2453   auto &TLI = DAG.getTargetLoweringInfo();
2454   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2455 
2456   // Build the setcc now.
2457   if (!CB.CmpMHS) {
2458     // Fold "(X == true)" to X and "(X == false)" to !X to
2459     // handle common cases produced by branch lowering.
2460     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2461         CB.CC == ISD::SETEQ)
2462       Cond = CondLHS;
2463     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2464              CB.CC == ISD::SETEQ) {
2465       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2466       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2467     } else {
2468       SDValue CondRHS = getValue(CB.CmpRHS);
2469 
2470       // If a pointer's DAG type is larger than its memory type then the DAG
2471       // values are zero-extended. This breaks signed comparisons so truncate
2472       // back to the underlying type before doing the compare.
2473       if (CondLHS.getValueType() != MemVT) {
2474         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2475         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2476       }
2477       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2478     }
2479   } else {
2480     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2481 
2482     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2483     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2484 
2485     SDValue CmpOp = getValue(CB.CmpMHS);
2486     EVT VT = CmpOp.getValueType();
2487 
2488     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2489       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2490                           ISD::SETLE);
2491     } else {
2492       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2493                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2494       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2495                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2496     }
2497   }
2498 
2499   // Update successor info
2500   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2501   // TrueBB and FalseBB are always different unless the incoming IR is
2502   // degenerate. This only happens when running llc on weird IR.
2503   if (CB.TrueBB != CB.FalseBB)
2504     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2505   SwitchBB->normalizeSuccProbs();
2506 
2507   // If the lhs block is the next block, invert the condition so that we can
2508   // fall through to the lhs instead of the rhs block.
2509   if (CB.TrueBB == NextBlock(SwitchBB)) {
2510     std::swap(CB.TrueBB, CB.FalseBB);
2511     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2512     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2513   }
2514 
2515   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2516                                MVT::Other, getControlRoot(), Cond,
2517                                DAG.getBasicBlock(CB.TrueBB));
2518 
2519   // Insert the false branch. Do this even if it's a fall through branch,
2520   // this makes it easier to do DAG optimizations which require inverting
2521   // the branch condition.
2522   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2523                        DAG.getBasicBlock(CB.FalseBB));
2524 
2525   DAG.setRoot(BrCond);
2526 }
2527 
2528 /// visitJumpTable - Emit JumpTable node in the current MBB
2529 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2530   // Emit the code for the jump table
2531   assert(JT.Reg != -1U && "Should lower JT Header first!");
2532   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2533   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2534                                      JT.Reg, PTy);
2535   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2536   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2537                                     MVT::Other, Index.getValue(1),
2538                                     Table, Index);
2539   DAG.setRoot(BrJumpTable);
2540 }
2541 
2542 /// visitJumpTableHeader - This function emits necessary code to produce index
2543 /// in the JumpTable from switch case.
2544 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2545                                                JumpTableHeader &JTH,
2546                                                MachineBasicBlock *SwitchBB) {
2547   SDLoc dl = getCurSDLoc();
2548 
2549   // Subtract the lowest switch case value from the value being switched on.
2550   SDValue SwitchOp = getValue(JTH.SValue);
2551   EVT VT = SwitchOp.getValueType();
2552   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2553                             DAG.getConstant(JTH.First, dl, VT));
2554 
2555   // The SDNode we just created, which holds the value being switched on minus
2556   // the smallest case value, needs to be copied to a virtual register so it
2557   // can be used as an index into the jump table in a subsequent basic block.
2558   // This value may be smaller or larger than the target's pointer type, and
2559   // therefore require extension or truncating.
2560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2561   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2562 
2563   unsigned JumpTableReg =
2564       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2565   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2566                                     JumpTableReg, SwitchOp);
2567   JT.Reg = JumpTableReg;
2568 
2569   if (!JTH.OmitRangeCheck) {
2570     // Emit the range check for the jump table, and branch to the default block
2571     // for the switch statement if the value being switched on exceeds the
2572     // largest case in the switch.
2573     SDValue CMP = DAG.getSetCC(
2574         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2575                                    Sub.getValueType()),
2576         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2577 
2578     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2579                                  MVT::Other, CopyTo, CMP,
2580                                  DAG.getBasicBlock(JT.Default));
2581 
2582     // Avoid emitting unnecessary branches to the next block.
2583     if (JT.MBB != NextBlock(SwitchBB))
2584       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2585                            DAG.getBasicBlock(JT.MBB));
2586 
2587     DAG.setRoot(BrCond);
2588   } else {
2589     // Avoid emitting unnecessary branches to the next block.
2590     if (JT.MBB != NextBlock(SwitchBB))
2591       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2592                               DAG.getBasicBlock(JT.MBB)));
2593     else
2594       DAG.setRoot(CopyTo);
2595   }
2596 }
2597 
2598 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2599 /// variable if there exists one.
2600 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2601                                  SDValue &Chain) {
2602   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2603   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2604   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2605   MachineFunction &MF = DAG.getMachineFunction();
2606   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2607   MachineSDNode *Node =
2608       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2609   if (Global) {
2610     MachinePointerInfo MPInfo(Global);
2611     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2612                  MachineMemOperand::MODereferenceable;
2613     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2614         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2615     DAG.setNodeMemRefs(Node, {MemRef});
2616   }
2617   if (PtrTy != PtrMemTy)
2618     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2619   return SDValue(Node, 0);
2620 }
2621 
2622 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2623 /// tail spliced into a stack protector check success bb.
2624 ///
2625 /// For a high level explanation of how this fits into the stack protector
2626 /// generation see the comment on the declaration of class
2627 /// StackProtectorDescriptor.
2628 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2629                                                   MachineBasicBlock *ParentBB) {
2630 
2631   // First create the loads to the guard/stack slot for the comparison.
2632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2633   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2634   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2635 
2636   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2637   int FI = MFI.getStackProtectorIndex();
2638 
2639   SDValue Guard;
2640   SDLoc dl = getCurSDLoc();
2641   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2642   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2643   Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2644 
2645   // Generate code to load the content of the guard slot.
2646   SDValue GuardVal = DAG.getLoad(
2647       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2648       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2649       MachineMemOperand::MOVolatile);
2650 
2651   if (TLI.useStackGuardXorFP())
2652     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2653 
2654   // Retrieve guard check function, nullptr if instrumentation is inlined.
2655   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2656     // The target provides a guard check function to validate the guard value.
2657     // Generate a call to that function with the content of the guard slot as
2658     // argument.
2659     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2660     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2661 
2662     TargetLowering::ArgListTy Args;
2663     TargetLowering::ArgListEntry Entry;
2664     Entry.Node = GuardVal;
2665     Entry.Ty = FnTy->getParamType(0);
2666     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2667       Entry.IsInReg = true;
2668     Args.push_back(Entry);
2669 
2670     TargetLowering::CallLoweringInfo CLI(DAG);
2671     CLI.setDebugLoc(getCurSDLoc())
2672         .setChain(DAG.getEntryNode())
2673         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2674                    getValue(GuardCheckFn), std::move(Args));
2675 
2676     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2677     DAG.setRoot(Result.second);
2678     return;
2679   }
2680 
2681   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2682   // Otherwise, emit a volatile load to retrieve the stack guard value.
2683   SDValue Chain = DAG.getEntryNode();
2684   if (TLI.useLoadStackGuardNode()) {
2685     Guard = getLoadStackGuard(DAG, dl, Chain);
2686   } else {
2687     const Value *IRGuard = TLI.getSDagStackGuard(M);
2688     SDValue GuardPtr = getValue(IRGuard);
2689 
2690     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2691                         MachinePointerInfo(IRGuard, 0), Align,
2692                         MachineMemOperand::MOVolatile);
2693   }
2694 
2695   // Perform the comparison via a getsetcc.
2696   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2697                                                         *DAG.getContext(),
2698                                                         Guard.getValueType()),
2699                              Guard, GuardVal, ISD::SETNE);
2700 
2701   // If the guard/stackslot do not equal, branch to failure MBB.
2702   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2703                                MVT::Other, GuardVal.getOperand(0),
2704                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2705   // Otherwise branch to success MBB.
2706   SDValue Br = DAG.getNode(ISD::BR, dl,
2707                            MVT::Other, BrCond,
2708                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2709 
2710   DAG.setRoot(Br);
2711 }
2712 
2713 /// Codegen the failure basic block for a stack protector check.
2714 ///
2715 /// A failure stack protector machine basic block consists simply of a call to
2716 /// __stack_chk_fail().
2717 ///
2718 /// For a high level explanation of how this fits into the stack protector
2719 /// generation see the comment on the declaration of class
2720 /// StackProtectorDescriptor.
2721 void
2722 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2723   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2724   TargetLowering::MakeLibCallOptions CallOptions;
2725   CallOptions.setDiscardResult(true);
2726   SDValue Chain =
2727       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2728                       None, CallOptions, getCurSDLoc()).second;
2729   // On PS4, the "return address" must still be within the calling function,
2730   // even if it's at the very end, so emit an explicit TRAP here.
2731   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2732   if (TM.getTargetTriple().isPS4CPU())
2733     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2734   // WebAssembly needs an unreachable instruction after a non-returning call,
2735   // because the function return type can be different from __stack_chk_fail's
2736   // return type (void).
2737   if (TM.getTargetTriple().isWasm())
2738     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2739 
2740   DAG.setRoot(Chain);
2741 }
2742 
2743 /// visitBitTestHeader - This function emits necessary code to produce value
2744 /// suitable for "bit tests"
2745 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2746                                              MachineBasicBlock *SwitchBB) {
2747   SDLoc dl = getCurSDLoc();
2748 
2749   // Subtract the minimum value.
2750   SDValue SwitchOp = getValue(B.SValue);
2751   EVT VT = SwitchOp.getValueType();
2752   SDValue RangeSub =
2753       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2754 
2755   // Determine the type of the test operands.
2756   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2757   bool UsePtrType = false;
2758   if (!TLI.isTypeLegal(VT)) {
2759     UsePtrType = true;
2760   } else {
2761     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2762       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2763         // Switch table case range are encoded into series of masks.
2764         // Just use pointer type, it's guaranteed to fit.
2765         UsePtrType = true;
2766         break;
2767       }
2768   }
2769   SDValue Sub = RangeSub;
2770   if (UsePtrType) {
2771     VT = TLI.getPointerTy(DAG.getDataLayout());
2772     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2773   }
2774 
2775   B.RegVT = VT.getSimpleVT();
2776   B.Reg = FuncInfo.CreateReg(B.RegVT);
2777   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2778 
2779   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2780 
2781   if (!B.OmitRangeCheck)
2782     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2783   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2784   SwitchBB->normalizeSuccProbs();
2785 
2786   SDValue Root = CopyTo;
2787   if (!B.OmitRangeCheck) {
2788     // Conditional branch to the default block.
2789     SDValue RangeCmp = DAG.getSetCC(dl,
2790         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2791                                RangeSub.getValueType()),
2792         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2793         ISD::SETUGT);
2794 
2795     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2796                        DAG.getBasicBlock(B.Default));
2797   }
2798 
2799   // Avoid emitting unnecessary branches to the next block.
2800   if (MBB != NextBlock(SwitchBB))
2801     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2802 
2803   DAG.setRoot(Root);
2804 }
2805 
2806 /// visitBitTestCase - this function produces one "bit test"
2807 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2808                                            MachineBasicBlock* NextMBB,
2809                                            BranchProbability BranchProbToNext,
2810                                            unsigned Reg,
2811                                            BitTestCase &B,
2812                                            MachineBasicBlock *SwitchBB) {
2813   SDLoc dl = getCurSDLoc();
2814   MVT VT = BB.RegVT;
2815   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2816   SDValue Cmp;
2817   unsigned PopCount = countPopulation(B.Mask);
2818   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2819   if (PopCount == 1) {
2820     // Testing for a single bit; just compare the shift count with what it
2821     // would need to be to shift a 1 bit in that position.
2822     Cmp = DAG.getSetCC(
2823         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2824         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2825         ISD::SETEQ);
2826   } else if (PopCount == BB.Range) {
2827     // There is only one zero bit in the range, test for it directly.
2828     Cmp = DAG.getSetCC(
2829         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2830         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2831         ISD::SETNE);
2832   } else {
2833     // Make desired shift
2834     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2835                                     DAG.getConstant(1, dl, VT), ShiftOp);
2836 
2837     // Emit bit tests and jumps
2838     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2839                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2840     Cmp = DAG.getSetCC(
2841         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2842         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2843   }
2844 
2845   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2846   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2847   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2848   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2849   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2850   // one as they are relative probabilities (and thus work more like weights),
2851   // and hence we need to normalize them to let the sum of them become one.
2852   SwitchBB->normalizeSuccProbs();
2853 
2854   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2855                               MVT::Other, getControlRoot(),
2856                               Cmp, DAG.getBasicBlock(B.TargetBB));
2857 
2858   // Avoid emitting unnecessary branches to the next block.
2859   if (NextMBB != NextBlock(SwitchBB))
2860     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2861                         DAG.getBasicBlock(NextMBB));
2862 
2863   DAG.setRoot(BrAnd);
2864 }
2865 
2866 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2867   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2868 
2869   // Retrieve successors. Look through artificial IR level blocks like
2870   // catchswitch for successors.
2871   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2872   const BasicBlock *EHPadBB = I.getSuccessor(1);
2873 
2874   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2875   // have to do anything here to lower funclet bundles.
2876   assert(!I.hasOperandBundlesOtherThan(
2877              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2878               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2879               LLVMContext::OB_cfguardtarget,
2880               LLVMContext::OB_clang_arc_attachedcall}) &&
2881          "Cannot lower invokes with arbitrary operand bundles yet!");
2882 
2883   const Value *Callee(I.getCalledOperand());
2884   const Function *Fn = dyn_cast<Function>(Callee);
2885   if (isa<InlineAsm>(Callee))
2886     visitInlineAsm(I, EHPadBB);
2887   else if (Fn && Fn->isIntrinsic()) {
2888     switch (Fn->getIntrinsicID()) {
2889     default:
2890       llvm_unreachable("Cannot invoke this intrinsic");
2891     case Intrinsic::donothing:
2892       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2893     case Intrinsic::seh_try_begin:
2894     case Intrinsic::seh_scope_begin:
2895     case Intrinsic::seh_try_end:
2896     case Intrinsic::seh_scope_end:
2897       break;
2898     case Intrinsic::experimental_patchpoint_void:
2899     case Intrinsic::experimental_patchpoint_i64:
2900       visitPatchpoint(I, EHPadBB);
2901       break;
2902     case Intrinsic::experimental_gc_statepoint:
2903       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2904       break;
2905     case Intrinsic::wasm_rethrow: {
2906       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2907       // special because it can be invoked, so we manually lower it to a DAG
2908       // node here.
2909       SmallVector<SDValue, 8> Ops;
2910       Ops.push_back(getRoot()); // inchain
2911       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2912       Ops.push_back(
2913           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2914                                 TLI.getPointerTy(DAG.getDataLayout())));
2915       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2916       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2917       break;
2918     }
2919     }
2920   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2921     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2922     // Eventually we will support lowering the @llvm.experimental.deoptimize
2923     // intrinsic, and right now there are no plans to support other intrinsics
2924     // with deopt state.
2925     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2926   } else {
2927     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2928   }
2929 
2930   // If the value of the invoke is used outside of its defining block, make it
2931   // available as a virtual register.
2932   // We already took care of the exported value for the statepoint instruction
2933   // during call to the LowerStatepoint.
2934   if (!isa<GCStatepointInst>(I)) {
2935     CopyToExportRegsIfNeeded(&I);
2936   }
2937 
2938   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2939   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2940   BranchProbability EHPadBBProb =
2941       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2942           : BranchProbability::getZero();
2943   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2944 
2945   // Update successor info.
2946   addSuccessorWithProb(InvokeMBB, Return);
2947   for (auto &UnwindDest : UnwindDests) {
2948     UnwindDest.first->setIsEHPad();
2949     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2950   }
2951   InvokeMBB->normalizeSuccProbs();
2952 
2953   // Drop into normal successor.
2954   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2955                           DAG.getBasicBlock(Return)));
2956 }
2957 
2958 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2959   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2960 
2961   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2962   // have to do anything here to lower funclet bundles.
2963   assert(!I.hasOperandBundlesOtherThan(
2964              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2965          "Cannot lower callbrs with arbitrary operand bundles yet!");
2966 
2967   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2968   visitInlineAsm(I);
2969   CopyToExportRegsIfNeeded(&I);
2970 
2971   // Retrieve successors.
2972   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2973 
2974   // Update successor info.
2975   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2976   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2977     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2978     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2979     Target->setIsInlineAsmBrIndirectTarget();
2980   }
2981   CallBrMBB->normalizeSuccProbs();
2982 
2983   // Drop into default successor.
2984   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2985                           MVT::Other, getControlRoot(),
2986                           DAG.getBasicBlock(Return)));
2987 }
2988 
2989 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2990   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2991 }
2992 
2993 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2994   assert(FuncInfo.MBB->isEHPad() &&
2995          "Call to landingpad not in landing pad!");
2996 
2997   // If there aren't registers to copy the values into (e.g., during SjLj
2998   // exceptions), then don't bother to create these DAG nodes.
2999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3000   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3001   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3002       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3003     return;
3004 
3005   // If landingpad's return type is token type, we don't create DAG nodes
3006   // for its exception pointer and selector value. The extraction of exception
3007   // pointer or selector value from token type landingpads is not currently
3008   // supported.
3009   if (LP.getType()->isTokenTy())
3010     return;
3011 
3012   SmallVector<EVT, 2> ValueVTs;
3013   SDLoc dl = getCurSDLoc();
3014   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3015   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3016 
3017   // Get the two live-in registers as SDValues. The physregs have already been
3018   // copied into virtual registers.
3019   SDValue Ops[2];
3020   if (FuncInfo.ExceptionPointerVirtReg) {
3021     Ops[0] = DAG.getZExtOrTrunc(
3022         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3023                            FuncInfo.ExceptionPointerVirtReg,
3024                            TLI.getPointerTy(DAG.getDataLayout())),
3025         dl, ValueVTs[0]);
3026   } else {
3027     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3028   }
3029   Ops[1] = DAG.getZExtOrTrunc(
3030       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3031                          FuncInfo.ExceptionSelectorVirtReg,
3032                          TLI.getPointerTy(DAG.getDataLayout())),
3033       dl, ValueVTs[1]);
3034 
3035   // Merge into one.
3036   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3037                             DAG.getVTList(ValueVTs), Ops);
3038   setValue(&LP, Res);
3039 }
3040 
3041 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3042                                            MachineBasicBlock *Last) {
3043   // Update JTCases.
3044   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
3045     if (SL->JTCases[i].first.HeaderBB == First)
3046       SL->JTCases[i].first.HeaderBB = Last;
3047 
3048   // Update BitTestCases.
3049   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
3050     if (SL->BitTestCases[i].Parent == First)
3051       SL->BitTestCases[i].Parent = Last;
3052 }
3053 
3054 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3055   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3056 
3057   // Update machine-CFG edges with unique successors.
3058   SmallSet<BasicBlock*, 32> Done;
3059   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3060     BasicBlock *BB = I.getSuccessor(i);
3061     bool Inserted = Done.insert(BB).second;
3062     if (!Inserted)
3063         continue;
3064 
3065     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3066     addSuccessorWithProb(IndirectBrMBB, Succ);
3067   }
3068   IndirectBrMBB->normalizeSuccProbs();
3069 
3070   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3071                           MVT::Other, getControlRoot(),
3072                           getValue(I.getAddress())));
3073 }
3074 
3075 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3076   if (!DAG.getTarget().Options.TrapUnreachable)
3077     return;
3078 
3079   // We may be able to ignore unreachable behind a noreturn call.
3080   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3081     const BasicBlock &BB = *I.getParent();
3082     if (&I != &BB.front()) {
3083       BasicBlock::const_iterator PredI =
3084         std::prev(BasicBlock::const_iterator(&I));
3085       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3086         if (Call->doesNotReturn())
3087           return;
3088       }
3089     }
3090   }
3091 
3092   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3093 }
3094 
3095 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3096   SDNodeFlags Flags;
3097 
3098   SDValue Op = getValue(I.getOperand(0));
3099   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3100                                     Op, Flags);
3101   setValue(&I, UnNodeValue);
3102 }
3103 
3104 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3105   SDNodeFlags Flags;
3106   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3107     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3108     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3109   }
3110   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3111     Flags.setExact(ExactOp->isExact());
3112   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3113     Flags.copyFMF(*FPOp);
3114 
3115   SDValue Op1 = getValue(I.getOperand(0));
3116   SDValue Op2 = getValue(I.getOperand(1));
3117   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3118                                      Op1, Op2, Flags);
3119   setValue(&I, BinNodeValue);
3120 }
3121 
3122 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3123   SDValue Op1 = getValue(I.getOperand(0));
3124   SDValue Op2 = getValue(I.getOperand(1));
3125 
3126   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3127       Op1.getValueType(), DAG.getDataLayout());
3128 
3129   // Coerce the shift amount to the right type if we can.
3130   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3131     unsigned ShiftSize = ShiftTy.getSizeInBits();
3132     unsigned Op2Size = Op2.getValueSizeInBits();
3133     SDLoc DL = getCurSDLoc();
3134 
3135     // If the operand is smaller than the shift count type, promote it.
3136     if (ShiftSize > Op2Size)
3137       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3138 
3139     // If the operand is larger than the shift count type but the shift
3140     // count type has enough bits to represent any shift value, truncate
3141     // it now. This is a common case and it exposes the truncate to
3142     // optimization early.
3143     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3144       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3145     // Otherwise we'll need to temporarily settle for some other convenient
3146     // type.  Type legalization will make adjustments once the shiftee is split.
3147     else
3148       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3149   }
3150 
3151   bool nuw = false;
3152   bool nsw = false;
3153   bool exact = false;
3154 
3155   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3156 
3157     if (const OverflowingBinaryOperator *OFBinOp =
3158             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3159       nuw = OFBinOp->hasNoUnsignedWrap();
3160       nsw = OFBinOp->hasNoSignedWrap();
3161     }
3162     if (const PossiblyExactOperator *ExactOp =
3163             dyn_cast<const PossiblyExactOperator>(&I))
3164       exact = ExactOp->isExact();
3165   }
3166   SDNodeFlags Flags;
3167   Flags.setExact(exact);
3168   Flags.setNoSignedWrap(nsw);
3169   Flags.setNoUnsignedWrap(nuw);
3170   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3171                             Flags);
3172   setValue(&I, Res);
3173 }
3174 
3175 void SelectionDAGBuilder::visitSDiv(const User &I) {
3176   SDValue Op1 = getValue(I.getOperand(0));
3177   SDValue Op2 = getValue(I.getOperand(1));
3178 
3179   SDNodeFlags Flags;
3180   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3181                  cast<PossiblyExactOperator>(&I)->isExact());
3182   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3183                            Op2, Flags));
3184 }
3185 
3186 void SelectionDAGBuilder::visitICmp(const User &I) {
3187   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3188   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3189     predicate = IC->getPredicate();
3190   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3191     predicate = ICmpInst::Predicate(IC->getPredicate());
3192   SDValue Op1 = getValue(I.getOperand(0));
3193   SDValue Op2 = getValue(I.getOperand(1));
3194   ISD::CondCode Opcode = getICmpCondCode(predicate);
3195 
3196   auto &TLI = DAG.getTargetLoweringInfo();
3197   EVT MemVT =
3198       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3199 
3200   // If a pointer's DAG type is larger than its memory type then the DAG values
3201   // are zero-extended. This breaks signed comparisons so truncate back to the
3202   // underlying type before doing the compare.
3203   if (Op1.getValueType() != MemVT) {
3204     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3205     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3206   }
3207 
3208   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3209                                                         I.getType());
3210   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3211 }
3212 
3213 void SelectionDAGBuilder::visitFCmp(const User &I) {
3214   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3215   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3216     predicate = FC->getPredicate();
3217   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3218     predicate = FCmpInst::Predicate(FC->getPredicate());
3219   SDValue Op1 = getValue(I.getOperand(0));
3220   SDValue Op2 = getValue(I.getOperand(1));
3221 
3222   ISD::CondCode Condition = getFCmpCondCode(predicate);
3223   auto *FPMO = cast<FPMathOperator>(&I);
3224   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3225     Condition = getFCmpCodeWithoutNaN(Condition);
3226 
3227   SDNodeFlags Flags;
3228   Flags.copyFMF(*FPMO);
3229   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3230 
3231   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3232                                                         I.getType());
3233   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3234 }
3235 
3236 // Check if the condition of the select has one use or two users that are both
3237 // selects with the same condition.
3238 static bool hasOnlySelectUsers(const Value *Cond) {
3239   return llvm::all_of(Cond->users(), [](const Value *V) {
3240     return isa<SelectInst>(V);
3241   });
3242 }
3243 
3244 void SelectionDAGBuilder::visitSelect(const User &I) {
3245   SmallVector<EVT, 4> ValueVTs;
3246   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3247                   ValueVTs);
3248   unsigned NumValues = ValueVTs.size();
3249   if (NumValues == 0) return;
3250 
3251   SmallVector<SDValue, 4> Values(NumValues);
3252   SDValue Cond     = getValue(I.getOperand(0));
3253   SDValue LHSVal   = getValue(I.getOperand(1));
3254   SDValue RHSVal   = getValue(I.getOperand(2));
3255   SmallVector<SDValue, 1> BaseOps(1, Cond);
3256   ISD::NodeType OpCode =
3257       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3258 
3259   bool IsUnaryAbs = false;
3260   bool Negate = false;
3261 
3262   SDNodeFlags Flags;
3263   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3264     Flags.copyFMF(*FPOp);
3265 
3266   // Min/max matching is only viable if all output VTs are the same.
3267   if (is_splat(ValueVTs)) {
3268     EVT VT = ValueVTs[0];
3269     LLVMContext &Ctx = *DAG.getContext();
3270     auto &TLI = DAG.getTargetLoweringInfo();
3271 
3272     // We care about the legality of the operation after it has been type
3273     // legalized.
3274     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3275       VT = TLI.getTypeToTransformTo(Ctx, VT);
3276 
3277     // If the vselect is legal, assume we want to leave this as a vector setcc +
3278     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3279     // min/max is legal on the scalar type.
3280     bool UseScalarMinMax = VT.isVector() &&
3281       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3282 
3283     Value *LHS, *RHS;
3284     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3285     ISD::NodeType Opc = ISD::DELETED_NODE;
3286     switch (SPR.Flavor) {
3287     case SPF_UMAX:    Opc = ISD::UMAX; break;
3288     case SPF_UMIN:    Opc = ISD::UMIN; break;
3289     case SPF_SMAX:    Opc = ISD::SMAX; break;
3290     case SPF_SMIN:    Opc = ISD::SMIN; break;
3291     case SPF_FMINNUM:
3292       switch (SPR.NaNBehavior) {
3293       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3294       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3295       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3296       case SPNB_RETURNS_ANY: {
3297         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3298           Opc = ISD::FMINNUM;
3299         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3300           Opc = ISD::FMINIMUM;
3301         else if (UseScalarMinMax)
3302           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3303             ISD::FMINNUM : ISD::FMINIMUM;
3304         break;
3305       }
3306       }
3307       break;
3308     case SPF_FMAXNUM:
3309       switch (SPR.NaNBehavior) {
3310       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3311       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3312       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3313       case SPNB_RETURNS_ANY:
3314 
3315         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3316           Opc = ISD::FMAXNUM;
3317         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3318           Opc = ISD::FMAXIMUM;
3319         else if (UseScalarMinMax)
3320           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3321             ISD::FMAXNUM : ISD::FMAXIMUM;
3322         break;
3323       }
3324       break;
3325     case SPF_NABS:
3326       Negate = true;
3327       LLVM_FALLTHROUGH;
3328     case SPF_ABS:
3329       IsUnaryAbs = true;
3330       Opc = ISD::ABS;
3331       break;
3332     default: break;
3333     }
3334 
3335     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3336         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3337          (UseScalarMinMax &&
3338           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3339         // If the underlying comparison instruction is used by any other
3340         // instruction, the consumed instructions won't be destroyed, so it is
3341         // not profitable to convert to a min/max.
3342         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3343       OpCode = Opc;
3344       LHSVal = getValue(LHS);
3345       RHSVal = getValue(RHS);
3346       BaseOps.clear();
3347     }
3348 
3349     if (IsUnaryAbs) {
3350       OpCode = Opc;
3351       LHSVal = getValue(LHS);
3352       BaseOps.clear();
3353     }
3354   }
3355 
3356   if (IsUnaryAbs) {
3357     for (unsigned i = 0; i != NumValues; ++i) {
3358       SDLoc dl = getCurSDLoc();
3359       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3360       Values[i] =
3361           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3362       if (Negate)
3363         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3364                                 Values[i]);
3365     }
3366   } else {
3367     for (unsigned i = 0; i != NumValues; ++i) {
3368       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3369       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3370       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3371       Values[i] = DAG.getNode(
3372           OpCode, getCurSDLoc(),
3373           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3374     }
3375   }
3376 
3377   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3378                            DAG.getVTList(ValueVTs), Values));
3379 }
3380 
3381 void SelectionDAGBuilder::visitTrunc(const User &I) {
3382   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3383   SDValue N = getValue(I.getOperand(0));
3384   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3385                                                         I.getType());
3386   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3387 }
3388 
3389 void SelectionDAGBuilder::visitZExt(const User &I) {
3390   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3391   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3392   SDValue N = getValue(I.getOperand(0));
3393   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3394                                                         I.getType());
3395   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3396 }
3397 
3398 void SelectionDAGBuilder::visitSExt(const User &I) {
3399   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3400   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3401   SDValue N = getValue(I.getOperand(0));
3402   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3403                                                         I.getType());
3404   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3405 }
3406 
3407 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3408   // FPTrunc is never a no-op cast, no need to check
3409   SDValue N = getValue(I.getOperand(0));
3410   SDLoc dl = getCurSDLoc();
3411   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3412   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3413   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3414                            DAG.getTargetConstant(
3415                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3416 }
3417 
3418 void SelectionDAGBuilder::visitFPExt(const User &I) {
3419   // FPExt is never a no-op cast, no need to check
3420   SDValue N = getValue(I.getOperand(0));
3421   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3422                                                         I.getType());
3423   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3424 }
3425 
3426 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3427   // FPToUI is never a no-op cast, no need to check
3428   SDValue N = getValue(I.getOperand(0));
3429   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3430                                                         I.getType());
3431   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3432 }
3433 
3434 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3435   // FPToSI is never a no-op cast, no need to check
3436   SDValue N = getValue(I.getOperand(0));
3437   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3438                                                         I.getType());
3439   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3440 }
3441 
3442 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3443   // UIToFP is never a no-op cast, no need to check
3444   SDValue N = getValue(I.getOperand(0));
3445   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3446                                                         I.getType());
3447   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3448 }
3449 
3450 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3451   // SIToFP is never a no-op cast, no need to check
3452   SDValue N = getValue(I.getOperand(0));
3453   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3454                                                         I.getType());
3455   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3456 }
3457 
3458 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3459   // What to do depends on the size of the integer and the size of the pointer.
3460   // We can either truncate, zero extend, or no-op, accordingly.
3461   SDValue N = getValue(I.getOperand(0));
3462   auto &TLI = DAG.getTargetLoweringInfo();
3463   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3464                                                         I.getType());
3465   EVT PtrMemVT =
3466       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3467   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3468   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3469   setValue(&I, N);
3470 }
3471 
3472 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3473   // What to do depends on the size of the integer and the size of the pointer.
3474   // We can either truncate, zero extend, or no-op, accordingly.
3475   SDValue N = getValue(I.getOperand(0));
3476   auto &TLI = DAG.getTargetLoweringInfo();
3477   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3478   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3479   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3480   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3481   setValue(&I, N);
3482 }
3483 
3484 void SelectionDAGBuilder::visitBitCast(const User &I) {
3485   SDValue N = getValue(I.getOperand(0));
3486   SDLoc dl = getCurSDLoc();
3487   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3488                                                         I.getType());
3489 
3490   // BitCast assures us that source and destination are the same size so this is
3491   // either a BITCAST or a no-op.
3492   if (DestVT != N.getValueType())
3493     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3494                              DestVT, N)); // convert types.
3495   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3496   // might fold any kind of constant expression to an integer constant and that
3497   // is not what we are looking for. Only recognize a bitcast of a genuine
3498   // constant integer as an opaque constant.
3499   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3500     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3501                                  /*isOpaque*/true));
3502   else
3503     setValue(&I, N);            // noop cast.
3504 }
3505 
3506 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3508   const Value *SV = I.getOperand(0);
3509   SDValue N = getValue(SV);
3510   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3511 
3512   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3513   unsigned DestAS = I.getType()->getPointerAddressSpace();
3514 
3515   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3516     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3517 
3518   setValue(&I, N);
3519 }
3520 
3521 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3522   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3523   SDValue InVec = getValue(I.getOperand(0));
3524   SDValue InVal = getValue(I.getOperand(1));
3525   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3526                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3527   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3528                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3529                            InVec, InVal, InIdx));
3530 }
3531 
3532 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3533   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3534   SDValue InVec = getValue(I.getOperand(0));
3535   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3536                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3537   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3538                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3539                            InVec, InIdx));
3540 }
3541 
3542 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3543   SDValue Src1 = getValue(I.getOperand(0));
3544   SDValue Src2 = getValue(I.getOperand(1));
3545   ArrayRef<int> Mask;
3546   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3547     Mask = SVI->getShuffleMask();
3548   else
3549     Mask = cast<ConstantExpr>(I).getShuffleMask();
3550   SDLoc DL = getCurSDLoc();
3551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3552   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3553   EVT SrcVT = Src1.getValueType();
3554 
3555   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3556       VT.isScalableVector()) {
3557     // Canonical splat form of first element of first input vector.
3558     SDValue FirstElt =
3559         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3560                     DAG.getVectorIdxConstant(0, DL));
3561     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3562     return;
3563   }
3564 
3565   // For now, we only handle splats for scalable vectors.
3566   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3567   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3568   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3569 
3570   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3571   unsigned MaskNumElts = Mask.size();
3572 
3573   if (SrcNumElts == MaskNumElts) {
3574     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3575     return;
3576   }
3577 
3578   // Normalize the shuffle vector since mask and vector length don't match.
3579   if (SrcNumElts < MaskNumElts) {
3580     // Mask is longer than the source vectors. We can use concatenate vector to
3581     // make the mask and vectors lengths match.
3582 
3583     if (MaskNumElts % SrcNumElts == 0) {
3584       // Mask length is a multiple of the source vector length.
3585       // Check if the shuffle is some kind of concatenation of the input
3586       // vectors.
3587       unsigned NumConcat = MaskNumElts / SrcNumElts;
3588       bool IsConcat = true;
3589       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3590       for (unsigned i = 0; i != MaskNumElts; ++i) {
3591         int Idx = Mask[i];
3592         if (Idx < 0)
3593           continue;
3594         // Ensure the indices in each SrcVT sized piece are sequential and that
3595         // the same source is used for the whole piece.
3596         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3597             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3598              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3599           IsConcat = false;
3600           break;
3601         }
3602         // Remember which source this index came from.
3603         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3604       }
3605 
3606       // The shuffle is concatenating multiple vectors together. Just emit
3607       // a CONCAT_VECTORS operation.
3608       if (IsConcat) {
3609         SmallVector<SDValue, 8> ConcatOps;
3610         for (auto Src : ConcatSrcs) {
3611           if (Src < 0)
3612             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3613           else if (Src == 0)
3614             ConcatOps.push_back(Src1);
3615           else
3616             ConcatOps.push_back(Src2);
3617         }
3618         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3619         return;
3620       }
3621     }
3622 
3623     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3624     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3625     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3626                                     PaddedMaskNumElts);
3627 
3628     // Pad both vectors with undefs to make them the same length as the mask.
3629     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3630 
3631     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3632     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3633     MOps1[0] = Src1;
3634     MOps2[0] = Src2;
3635 
3636     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3637     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3638 
3639     // Readjust mask for new input vector length.
3640     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3641     for (unsigned i = 0; i != MaskNumElts; ++i) {
3642       int Idx = Mask[i];
3643       if (Idx >= (int)SrcNumElts)
3644         Idx -= SrcNumElts - PaddedMaskNumElts;
3645       MappedOps[i] = Idx;
3646     }
3647 
3648     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3649 
3650     // If the concatenated vector was padded, extract a subvector with the
3651     // correct number of elements.
3652     if (MaskNumElts != PaddedMaskNumElts)
3653       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3654                            DAG.getVectorIdxConstant(0, DL));
3655 
3656     setValue(&I, Result);
3657     return;
3658   }
3659 
3660   if (SrcNumElts > MaskNumElts) {
3661     // Analyze the access pattern of the vector to see if we can extract
3662     // two subvectors and do the shuffle.
3663     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3664     bool CanExtract = true;
3665     for (int Idx : Mask) {
3666       unsigned Input = 0;
3667       if (Idx < 0)
3668         continue;
3669 
3670       if (Idx >= (int)SrcNumElts) {
3671         Input = 1;
3672         Idx -= SrcNumElts;
3673       }
3674 
3675       // If all the indices come from the same MaskNumElts sized portion of
3676       // the sources we can use extract. Also make sure the extract wouldn't
3677       // extract past the end of the source.
3678       int NewStartIdx = alignDown(Idx, MaskNumElts);
3679       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3680           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3681         CanExtract = false;
3682       // Make sure we always update StartIdx as we use it to track if all
3683       // elements are undef.
3684       StartIdx[Input] = NewStartIdx;
3685     }
3686 
3687     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3688       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3689       return;
3690     }
3691     if (CanExtract) {
3692       // Extract appropriate subvector and generate a vector shuffle
3693       for (unsigned Input = 0; Input < 2; ++Input) {
3694         SDValue &Src = Input == 0 ? Src1 : Src2;
3695         if (StartIdx[Input] < 0)
3696           Src = DAG.getUNDEF(VT);
3697         else {
3698           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3699                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3700         }
3701       }
3702 
3703       // Calculate new mask.
3704       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3705       for (int &Idx : MappedOps) {
3706         if (Idx >= (int)SrcNumElts)
3707           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3708         else if (Idx >= 0)
3709           Idx -= StartIdx[0];
3710       }
3711 
3712       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3713       return;
3714     }
3715   }
3716 
3717   // We can't use either concat vectors or extract subvectors so fall back to
3718   // replacing the shuffle with extract and build vector.
3719   // to insert and build vector.
3720   EVT EltVT = VT.getVectorElementType();
3721   SmallVector<SDValue,8> Ops;
3722   for (int Idx : Mask) {
3723     SDValue Res;
3724 
3725     if (Idx < 0) {
3726       Res = DAG.getUNDEF(EltVT);
3727     } else {
3728       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3729       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3730 
3731       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3732                         DAG.getVectorIdxConstant(Idx, DL));
3733     }
3734 
3735     Ops.push_back(Res);
3736   }
3737 
3738   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3739 }
3740 
3741 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3742   ArrayRef<unsigned> Indices;
3743   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3744     Indices = IV->getIndices();
3745   else
3746     Indices = cast<ConstantExpr>(&I)->getIndices();
3747 
3748   const Value *Op0 = I.getOperand(0);
3749   const Value *Op1 = I.getOperand(1);
3750   Type *AggTy = I.getType();
3751   Type *ValTy = Op1->getType();
3752   bool IntoUndef = isa<UndefValue>(Op0);
3753   bool FromUndef = isa<UndefValue>(Op1);
3754 
3755   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3756 
3757   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3758   SmallVector<EVT, 4> AggValueVTs;
3759   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3760   SmallVector<EVT, 4> ValValueVTs;
3761   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3762 
3763   unsigned NumAggValues = AggValueVTs.size();
3764   unsigned NumValValues = ValValueVTs.size();
3765   SmallVector<SDValue, 4> Values(NumAggValues);
3766 
3767   // Ignore an insertvalue that produces an empty object
3768   if (!NumAggValues) {
3769     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3770     return;
3771   }
3772 
3773   SDValue Agg = getValue(Op0);
3774   unsigned i = 0;
3775   // Copy the beginning value(s) from the original aggregate.
3776   for (; i != LinearIndex; ++i)
3777     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3778                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3779   // Copy values from the inserted value(s).
3780   if (NumValValues) {
3781     SDValue Val = getValue(Op1);
3782     for (; i != LinearIndex + NumValValues; ++i)
3783       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3784                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3785   }
3786   // Copy remaining value(s) from the original aggregate.
3787   for (; i != NumAggValues; ++i)
3788     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3789                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3790 
3791   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3792                            DAG.getVTList(AggValueVTs), Values));
3793 }
3794 
3795 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3796   ArrayRef<unsigned> Indices;
3797   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3798     Indices = EV->getIndices();
3799   else
3800     Indices = cast<ConstantExpr>(&I)->getIndices();
3801 
3802   const Value *Op0 = I.getOperand(0);
3803   Type *AggTy = Op0->getType();
3804   Type *ValTy = I.getType();
3805   bool OutOfUndef = isa<UndefValue>(Op0);
3806 
3807   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3808 
3809   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3810   SmallVector<EVT, 4> ValValueVTs;
3811   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3812 
3813   unsigned NumValValues = ValValueVTs.size();
3814 
3815   // Ignore a extractvalue that produces an empty object
3816   if (!NumValValues) {
3817     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3818     return;
3819   }
3820 
3821   SmallVector<SDValue, 4> Values(NumValValues);
3822 
3823   SDValue Agg = getValue(Op0);
3824   // Copy out the selected value(s).
3825   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3826     Values[i - LinearIndex] =
3827       OutOfUndef ?
3828         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3829         SDValue(Agg.getNode(), Agg.getResNo() + i);
3830 
3831   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3832                            DAG.getVTList(ValValueVTs), Values));
3833 }
3834 
3835 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3836   Value *Op0 = I.getOperand(0);
3837   // Note that the pointer operand may be a vector of pointers. Take the scalar
3838   // element which holds a pointer.
3839   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3840   SDValue N = getValue(Op0);
3841   SDLoc dl = getCurSDLoc();
3842   auto &TLI = DAG.getTargetLoweringInfo();
3843 
3844   // Normalize Vector GEP - all scalar operands should be converted to the
3845   // splat vector.
3846   bool IsVectorGEP = I.getType()->isVectorTy();
3847   ElementCount VectorElementCount =
3848       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3849                   : ElementCount::getFixed(0);
3850 
3851   if (IsVectorGEP && !N.getValueType().isVector()) {
3852     LLVMContext &Context = *DAG.getContext();
3853     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3854     if (VectorElementCount.isScalable())
3855       N = DAG.getSplatVector(VT, dl, N);
3856     else
3857       N = DAG.getSplatBuildVector(VT, dl, N);
3858   }
3859 
3860   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3861        GTI != E; ++GTI) {
3862     const Value *Idx = GTI.getOperand();
3863     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3864       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3865       if (Field) {
3866         // N = N + Offset
3867         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3868 
3869         // In an inbounds GEP with an offset that is nonnegative even when
3870         // interpreted as signed, assume there is no unsigned overflow.
3871         SDNodeFlags Flags;
3872         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3873           Flags.setNoUnsignedWrap(true);
3874 
3875         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3876                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3877       }
3878     } else {
3879       // IdxSize is the width of the arithmetic according to IR semantics.
3880       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3881       // (and fix up the result later).
3882       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3883       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3884       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3885       // We intentionally mask away the high bits here; ElementSize may not
3886       // fit in IdxTy.
3887       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3888       bool ElementScalable = ElementSize.isScalable();
3889 
3890       // If this is a scalar constant or a splat vector of constants,
3891       // handle it quickly.
3892       const auto *C = dyn_cast<Constant>(Idx);
3893       if (C && isa<VectorType>(C->getType()))
3894         C = C->getSplatValue();
3895 
3896       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3897       if (CI && CI->isZero())
3898         continue;
3899       if (CI && !ElementScalable) {
3900         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3901         LLVMContext &Context = *DAG.getContext();
3902         SDValue OffsVal;
3903         if (IsVectorGEP)
3904           OffsVal = DAG.getConstant(
3905               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3906         else
3907           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3908 
3909         // In an inbounds GEP with an offset that is nonnegative even when
3910         // interpreted as signed, assume there is no unsigned overflow.
3911         SDNodeFlags Flags;
3912         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3913           Flags.setNoUnsignedWrap(true);
3914 
3915         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3916 
3917         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3918         continue;
3919       }
3920 
3921       // N = N + Idx * ElementMul;
3922       SDValue IdxN = getValue(Idx);
3923 
3924       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3925         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3926                                   VectorElementCount);
3927         if (VectorElementCount.isScalable())
3928           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3929         else
3930           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3931       }
3932 
3933       // If the index is smaller or larger than intptr_t, truncate or extend
3934       // it.
3935       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3936 
3937       if (ElementScalable) {
3938         EVT VScaleTy = N.getValueType().getScalarType();
3939         SDValue VScale = DAG.getNode(
3940             ISD::VSCALE, dl, VScaleTy,
3941             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3942         if (IsVectorGEP)
3943           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3944         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3945       } else {
3946         // If this is a multiply by a power of two, turn it into a shl
3947         // immediately.  This is a very common case.
3948         if (ElementMul != 1) {
3949           if (ElementMul.isPowerOf2()) {
3950             unsigned Amt = ElementMul.logBase2();
3951             IdxN = DAG.getNode(ISD::SHL, dl,
3952                                N.getValueType(), IdxN,
3953                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3954           } else {
3955             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3956                                             IdxN.getValueType());
3957             IdxN = DAG.getNode(ISD::MUL, dl,
3958                                N.getValueType(), IdxN, Scale);
3959           }
3960         }
3961       }
3962 
3963       N = DAG.getNode(ISD::ADD, dl,
3964                       N.getValueType(), N, IdxN);
3965     }
3966   }
3967 
3968   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3969   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3970   if (IsVectorGEP) {
3971     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3972     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3973   }
3974 
3975   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3976     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3977 
3978   setValue(&I, N);
3979 }
3980 
3981 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3982   // If this is a fixed sized alloca in the entry block of the function,
3983   // allocate it statically on the stack.
3984   if (FuncInfo.StaticAllocaMap.count(&I))
3985     return;   // getValue will auto-populate this.
3986 
3987   SDLoc dl = getCurSDLoc();
3988   Type *Ty = I.getAllocatedType();
3989   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3990   auto &DL = DAG.getDataLayout();
3991   uint64_t TySize = DL.getTypeAllocSize(Ty);
3992   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3993 
3994   SDValue AllocSize = getValue(I.getArraySize());
3995 
3996   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3997   if (AllocSize.getValueType() != IntPtr)
3998     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3999 
4000   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4001                           AllocSize,
4002                           DAG.getConstant(TySize, dl, IntPtr));
4003 
4004   // Handle alignment.  If the requested alignment is less than or equal to
4005   // the stack alignment, ignore it.  If the size is greater than or equal to
4006   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4007   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4008   if (*Alignment <= StackAlign)
4009     Alignment = None;
4010 
4011   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4012   // Round the size of the allocation up to the stack alignment size
4013   // by add SA-1 to the size. This doesn't overflow because we're computing
4014   // an address inside an alloca.
4015   SDNodeFlags Flags;
4016   Flags.setNoUnsignedWrap(true);
4017   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4018                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4019 
4020   // Mask out the low bits for alignment purposes.
4021   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4022                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4023 
4024   SDValue Ops[] = {
4025       getRoot(), AllocSize,
4026       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4027   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4028   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4029   setValue(&I, DSA);
4030   DAG.setRoot(DSA.getValue(1));
4031 
4032   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4033 }
4034 
4035 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4036   if (I.isAtomic())
4037     return visitAtomicLoad(I);
4038 
4039   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4040   const Value *SV = I.getOperand(0);
4041   if (TLI.supportSwiftError()) {
4042     // Swifterror values can come from either a function parameter with
4043     // swifterror attribute or an alloca with swifterror attribute.
4044     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4045       if (Arg->hasSwiftErrorAttr())
4046         return visitLoadFromSwiftError(I);
4047     }
4048 
4049     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4050       if (Alloca->isSwiftError())
4051         return visitLoadFromSwiftError(I);
4052     }
4053   }
4054 
4055   SDValue Ptr = getValue(SV);
4056 
4057   Type *Ty = I.getType();
4058   Align Alignment = I.getAlign();
4059 
4060   AAMDNodes AAInfo;
4061   I.getAAMetadata(AAInfo);
4062   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4063 
4064   SmallVector<EVT, 4> ValueVTs, MemVTs;
4065   SmallVector<uint64_t, 4> Offsets;
4066   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4067   unsigned NumValues = ValueVTs.size();
4068   if (NumValues == 0)
4069     return;
4070 
4071   bool isVolatile = I.isVolatile();
4072 
4073   SDValue Root;
4074   bool ConstantMemory = false;
4075   if (isVolatile)
4076     // Serialize volatile loads with other side effects.
4077     Root = getRoot();
4078   else if (NumValues > MaxParallelChains)
4079     Root = getMemoryRoot();
4080   else if (AA &&
4081            AA->pointsToConstantMemory(MemoryLocation(
4082                SV,
4083                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4084                AAInfo))) {
4085     // Do not serialize (non-volatile) loads of constant memory with anything.
4086     Root = DAG.getEntryNode();
4087     ConstantMemory = true;
4088   } else {
4089     // Do not serialize non-volatile loads against each other.
4090     Root = DAG.getRoot();
4091   }
4092 
4093   SDLoc dl = getCurSDLoc();
4094 
4095   if (isVolatile)
4096     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4097 
4098   // An aggregate load cannot wrap around the address space, so offsets to its
4099   // parts don't wrap either.
4100   SDNodeFlags Flags;
4101   Flags.setNoUnsignedWrap(true);
4102 
4103   SmallVector<SDValue, 4> Values(NumValues);
4104   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4105   EVT PtrVT = Ptr.getValueType();
4106 
4107   MachineMemOperand::Flags MMOFlags
4108     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4109 
4110   unsigned ChainI = 0;
4111   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4112     // Serializing loads here may result in excessive register pressure, and
4113     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4114     // could recover a bit by hoisting nodes upward in the chain by recognizing
4115     // they are side-effect free or do not alias. The optimizer should really
4116     // avoid this case by converting large object/array copies to llvm.memcpy
4117     // (MaxParallelChains should always remain as failsafe).
4118     if (ChainI == MaxParallelChains) {
4119       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4120       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4121                                   makeArrayRef(Chains.data(), ChainI));
4122       Root = Chain;
4123       ChainI = 0;
4124     }
4125     SDValue A = DAG.getNode(ISD::ADD, dl,
4126                             PtrVT, Ptr,
4127                             DAG.getConstant(Offsets[i], dl, PtrVT),
4128                             Flags);
4129 
4130     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4131                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4132                             MMOFlags, AAInfo, Ranges);
4133     Chains[ChainI] = L.getValue(1);
4134 
4135     if (MemVTs[i] != ValueVTs[i])
4136       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4137 
4138     Values[i] = L;
4139   }
4140 
4141   if (!ConstantMemory) {
4142     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4143                                 makeArrayRef(Chains.data(), ChainI));
4144     if (isVolatile)
4145       DAG.setRoot(Chain);
4146     else
4147       PendingLoads.push_back(Chain);
4148   }
4149 
4150   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4151                            DAG.getVTList(ValueVTs), Values));
4152 }
4153 
4154 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4155   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4156          "call visitStoreToSwiftError when backend supports swifterror");
4157 
4158   SmallVector<EVT, 4> ValueVTs;
4159   SmallVector<uint64_t, 4> Offsets;
4160   const Value *SrcV = I.getOperand(0);
4161   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4162                   SrcV->getType(), ValueVTs, &Offsets);
4163   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4164          "expect a single EVT for swifterror");
4165 
4166   SDValue Src = getValue(SrcV);
4167   // Create a virtual register, then update the virtual register.
4168   Register VReg =
4169       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4170   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4171   // Chain can be getRoot or getControlRoot.
4172   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4173                                       SDValue(Src.getNode(), Src.getResNo()));
4174   DAG.setRoot(CopyNode);
4175 }
4176 
4177 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4178   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4179          "call visitLoadFromSwiftError when backend supports swifterror");
4180 
4181   assert(!I.isVolatile() &&
4182          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4183          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4184          "Support volatile, non temporal, invariant for load_from_swift_error");
4185 
4186   const Value *SV = I.getOperand(0);
4187   Type *Ty = I.getType();
4188   AAMDNodes AAInfo;
4189   I.getAAMetadata(AAInfo);
4190   assert(
4191       (!AA ||
4192        !AA->pointsToConstantMemory(MemoryLocation(
4193            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4194            AAInfo))) &&
4195       "load_from_swift_error should not be constant memory");
4196 
4197   SmallVector<EVT, 4> ValueVTs;
4198   SmallVector<uint64_t, 4> Offsets;
4199   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4200                   ValueVTs, &Offsets);
4201   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4202          "expect a single EVT for swifterror");
4203 
4204   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4205   SDValue L = DAG.getCopyFromReg(
4206       getRoot(), getCurSDLoc(),
4207       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4208 
4209   setValue(&I, L);
4210 }
4211 
4212 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4213   if (I.isAtomic())
4214     return visitAtomicStore(I);
4215 
4216   const Value *SrcV = I.getOperand(0);
4217   const Value *PtrV = I.getOperand(1);
4218 
4219   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4220   if (TLI.supportSwiftError()) {
4221     // Swifterror values can come from either a function parameter with
4222     // swifterror attribute or an alloca with swifterror attribute.
4223     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4224       if (Arg->hasSwiftErrorAttr())
4225         return visitStoreToSwiftError(I);
4226     }
4227 
4228     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4229       if (Alloca->isSwiftError())
4230         return visitStoreToSwiftError(I);
4231     }
4232   }
4233 
4234   SmallVector<EVT, 4> ValueVTs, MemVTs;
4235   SmallVector<uint64_t, 4> Offsets;
4236   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4237                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4238   unsigned NumValues = ValueVTs.size();
4239   if (NumValues == 0)
4240     return;
4241 
4242   // Get the lowered operands. Note that we do this after
4243   // checking if NumResults is zero, because with zero results
4244   // the operands won't have values in the map.
4245   SDValue Src = getValue(SrcV);
4246   SDValue Ptr = getValue(PtrV);
4247 
4248   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4249   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4250   SDLoc dl = getCurSDLoc();
4251   Align Alignment = I.getAlign();
4252   AAMDNodes AAInfo;
4253   I.getAAMetadata(AAInfo);
4254 
4255   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4256 
4257   // An aggregate load cannot wrap around the address space, so offsets to its
4258   // parts don't wrap either.
4259   SDNodeFlags Flags;
4260   Flags.setNoUnsignedWrap(true);
4261 
4262   unsigned ChainI = 0;
4263   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4264     // See visitLoad comments.
4265     if (ChainI == MaxParallelChains) {
4266       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4267                                   makeArrayRef(Chains.data(), ChainI));
4268       Root = Chain;
4269       ChainI = 0;
4270     }
4271     SDValue Add =
4272         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4273     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4274     if (MemVTs[i] != ValueVTs[i])
4275       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4276     SDValue St =
4277         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4278                      Alignment, MMOFlags, AAInfo);
4279     Chains[ChainI] = St;
4280   }
4281 
4282   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4283                                   makeArrayRef(Chains.data(), ChainI));
4284   DAG.setRoot(StoreNode);
4285 }
4286 
4287 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4288                                            bool IsCompressing) {
4289   SDLoc sdl = getCurSDLoc();
4290 
4291   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4292                                MaybeAlign &Alignment) {
4293     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4294     Src0 = I.getArgOperand(0);
4295     Ptr = I.getArgOperand(1);
4296     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4297     Mask = I.getArgOperand(3);
4298   };
4299   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4300                                     MaybeAlign &Alignment) {
4301     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4302     Src0 = I.getArgOperand(0);
4303     Ptr = I.getArgOperand(1);
4304     Mask = I.getArgOperand(2);
4305     Alignment = None;
4306   };
4307 
4308   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4309   MaybeAlign Alignment;
4310   if (IsCompressing)
4311     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4312   else
4313     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4314 
4315   SDValue Ptr = getValue(PtrOperand);
4316   SDValue Src0 = getValue(Src0Operand);
4317   SDValue Mask = getValue(MaskOperand);
4318   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4319 
4320   EVT VT = Src0.getValueType();
4321   if (!Alignment)
4322     Alignment = DAG.getEVTAlign(VT);
4323 
4324   AAMDNodes AAInfo;
4325   I.getAAMetadata(AAInfo);
4326 
4327   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4328       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4329       // TODO: Make MachineMemOperands aware of scalable
4330       // vectors.
4331       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4332   SDValue StoreNode =
4333       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4334                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4335   DAG.setRoot(StoreNode);
4336   setValue(&I, StoreNode);
4337 }
4338 
4339 // Get a uniform base for the Gather/Scatter intrinsic.
4340 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4341 // We try to represent it as a base pointer + vector of indices.
4342 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4343 // The first operand of the GEP may be a single pointer or a vector of pointers
4344 // Example:
4345 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4346 //  or
4347 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4348 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4349 //
4350 // When the first GEP operand is a single pointer - it is the uniform base we
4351 // are looking for. If first operand of the GEP is a splat vector - we
4352 // extract the splat value and use it as a uniform base.
4353 // In all other cases the function returns 'false'.
4354 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4355                            ISD::MemIndexType &IndexType, SDValue &Scale,
4356                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4357   SelectionDAG& DAG = SDB->DAG;
4358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4359   const DataLayout &DL = DAG.getDataLayout();
4360 
4361   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4362 
4363   // Handle splat constant pointer.
4364   if (auto *C = dyn_cast<Constant>(Ptr)) {
4365     C = C->getSplatValue();
4366     if (!C)
4367       return false;
4368 
4369     Base = SDB->getValue(C);
4370 
4371     unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements();
4372     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4373     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4374     IndexType = ISD::SIGNED_SCALED;
4375     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4376     return true;
4377   }
4378 
4379   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4380   if (!GEP || GEP->getParent() != CurBB)
4381     return false;
4382 
4383   if (GEP->getNumOperands() != 2)
4384     return false;
4385 
4386   const Value *BasePtr = GEP->getPointerOperand();
4387   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4388 
4389   // Make sure the base is scalar and the index is a vector.
4390   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4391     return false;
4392 
4393   Base = SDB->getValue(BasePtr);
4394   Index = SDB->getValue(IndexVal);
4395   IndexType = ISD::SIGNED_SCALED;
4396   Scale = DAG.getTargetConstant(
4397               DL.getTypeAllocSize(GEP->getResultElementType()),
4398               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4399   return true;
4400 }
4401 
4402 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4403   SDLoc sdl = getCurSDLoc();
4404 
4405   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4406   const Value *Ptr = I.getArgOperand(1);
4407   SDValue Src0 = getValue(I.getArgOperand(0));
4408   SDValue Mask = getValue(I.getArgOperand(3));
4409   EVT VT = Src0.getValueType();
4410   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4411                         ->getMaybeAlignValue()
4412                         .getValueOr(DAG.getEVTAlign(VT));
4413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4414 
4415   AAMDNodes AAInfo;
4416   I.getAAMetadata(AAInfo);
4417 
4418   SDValue Base;
4419   SDValue Index;
4420   ISD::MemIndexType IndexType;
4421   SDValue Scale;
4422   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4423                                     I.getParent());
4424 
4425   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4426   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4427       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4428       // TODO: Make MachineMemOperands aware of scalable
4429       // vectors.
4430       MemoryLocation::UnknownSize, Alignment, AAInfo);
4431   if (!UniformBase) {
4432     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4433     Index = getValue(Ptr);
4434     IndexType = ISD::SIGNED_UNSCALED;
4435     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4436   }
4437 
4438   EVT IdxVT = Index.getValueType();
4439   EVT EltTy = IdxVT.getVectorElementType();
4440   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4441     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4442     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4443   }
4444 
4445   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4446   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4447                                          Ops, MMO, IndexType, false);
4448   DAG.setRoot(Scatter);
4449   setValue(&I, Scatter);
4450 }
4451 
4452 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4453   SDLoc sdl = getCurSDLoc();
4454 
4455   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4456                               MaybeAlign &Alignment) {
4457     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4458     Ptr = I.getArgOperand(0);
4459     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4460     Mask = I.getArgOperand(2);
4461     Src0 = I.getArgOperand(3);
4462   };
4463   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4464                                  MaybeAlign &Alignment) {
4465     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4466     Ptr = I.getArgOperand(0);
4467     Alignment = None;
4468     Mask = I.getArgOperand(1);
4469     Src0 = I.getArgOperand(2);
4470   };
4471 
4472   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4473   MaybeAlign Alignment;
4474   if (IsExpanding)
4475     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4476   else
4477     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4478 
4479   SDValue Ptr = getValue(PtrOperand);
4480   SDValue Src0 = getValue(Src0Operand);
4481   SDValue Mask = getValue(MaskOperand);
4482   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4483 
4484   EVT VT = Src0.getValueType();
4485   if (!Alignment)
4486     Alignment = DAG.getEVTAlign(VT);
4487 
4488   AAMDNodes AAInfo;
4489   I.getAAMetadata(AAInfo);
4490   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4491 
4492   // Do not serialize masked loads of constant memory with anything.
4493   MemoryLocation ML;
4494   if (VT.isScalableVector())
4495     ML = MemoryLocation::getAfter(PtrOperand);
4496   else
4497     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4498                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4499                            AAInfo);
4500   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4501 
4502   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4503 
4504   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4505       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4506       // TODO: Make MachineMemOperands aware of scalable
4507       // vectors.
4508       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4509 
4510   SDValue Load =
4511       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4512                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4513   if (AddToChain)
4514     PendingLoads.push_back(Load.getValue(1));
4515   setValue(&I, Load);
4516 }
4517 
4518 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4519   SDLoc sdl = getCurSDLoc();
4520 
4521   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4522   const Value *Ptr = I.getArgOperand(0);
4523   SDValue Src0 = getValue(I.getArgOperand(3));
4524   SDValue Mask = getValue(I.getArgOperand(2));
4525 
4526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4527   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4528   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4529                         ->getMaybeAlignValue()
4530                         .getValueOr(DAG.getEVTAlign(VT));
4531 
4532   AAMDNodes AAInfo;
4533   I.getAAMetadata(AAInfo);
4534   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4535 
4536   SDValue Root = DAG.getRoot();
4537   SDValue Base;
4538   SDValue Index;
4539   ISD::MemIndexType IndexType;
4540   SDValue Scale;
4541   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4542                                     I.getParent());
4543   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4544   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4545       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4546       // TODO: Make MachineMemOperands aware of scalable
4547       // vectors.
4548       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4549 
4550   if (!UniformBase) {
4551     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4552     Index = getValue(Ptr);
4553     IndexType = ISD::SIGNED_UNSCALED;
4554     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4555   }
4556 
4557   EVT IdxVT = Index.getValueType();
4558   EVT EltTy = IdxVT.getVectorElementType();
4559   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4560     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4561     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4562   }
4563 
4564   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4565   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4566                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4567 
4568   PendingLoads.push_back(Gather.getValue(1));
4569   setValue(&I, Gather);
4570 }
4571 
4572 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4573   SDLoc dl = getCurSDLoc();
4574   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4575   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4576   SyncScope::ID SSID = I.getSyncScopeID();
4577 
4578   SDValue InChain = getRoot();
4579 
4580   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4581   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4582 
4583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4584   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4585 
4586   MachineFunction &MF = DAG.getMachineFunction();
4587   MachineMemOperand *MMO = MF.getMachineMemOperand(
4588       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4589       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4590       FailureOrdering);
4591 
4592   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4593                                    dl, MemVT, VTs, InChain,
4594                                    getValue(I.getPointerOperand()),
4595                                    getValue(I.getCompareOperand()),
4596                                    getValue(I.getNewValOperand()), MMO);
4597 
4598   SDValue OutChain = L.getValue(2);
4599 
4600   setValue(&I, L);
4601   DAG.setRoot(OutChain);
4602 }
4603 
4604 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4605   SDLoc dl = getCurSDLoc();
4606   ISD::NodeType NT;
4607   switch (I.getOperation()) {
4608   default: llvm_unreachable("Unknown atomicrmw operation");
4609   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4610   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4611   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4612   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4613   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4614   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4615   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4616   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4617   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4618   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4619   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4620   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4621   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4622   }
4623   AtomicOrdering Ordering = I.getOrdering();
4624   SyncScope::ID SSID = I.getSyncScopeID();
4625 
4626   SDValue InChain = getRoot();
4627 
4628   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4629   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4630   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4631 
4632   MachineFunction &MF = DAG.getMachineFunction();
4633   MachineMemOperand *MMO = MF.getMachineMemOperand(
4634       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4635       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4636 
4637   SDValue L =
4638     DAG.getAtomic(NT, dl, MemVT, InChain,
4639                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4640                   MMO);
4641 
4642   SDValue OutChain = L.getValue(1);
4643 
4644   setValue(&I, L);
4645   DAG.setRoot(OutChain);
4646 }
4647 
4648 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4649   SDLoc dl = getCurSDLoc();
4650   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4651   SDValue Ops[3];
4652   Ops[0] = getRoot();
4653   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4654                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4655   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4656                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4657   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4658 }
4659 
4660 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4661   SDLoc dl = getCurSDLoc();
4662   AtomicOrdering Order = I.getOrdering();
4663   SyncScope::ID SSID = I.getSyncScopeID();
4664 
4665   SDValue InChain = getRoot();
4666 
4667   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4668   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4669   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4670 
4671   if (!TLI.supportsUnalignedAtomics() &&
4672       I.getAlignment() < MemVT.getSizeInBits() / 8)
4673     report_fatal_error("Cannot generate unaligned atomic load");
4674 
4675   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4676 
4677   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4678       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4679       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4680 
4681   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4682 
4683   SDValue Ptr = getValue(I.getPointerOperand());
4684 
4685   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4686     // TODO: Once this is better exercised by tests, it should be merged with
4687     // the normal path for loads to prevent future divergence.
4688     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4689     if (MemVT != VT)
4690       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4691 
4692     setValue(&I, L);
4693     SDValue OutChain = L.getValue(1);
4694     if (!I.isUnordered())
4695       DAG.setRoot(OutChain);
4696     else
4697       PendingLoads.push_back(OutChain);
4698     return;
4699   }
4700 
4701   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4702                             Ptr, MMO);
4703 
4704   SDValue OutChain = L.getValue(1);
4705   if (MemVT != VT)
4706     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4707 
4708   setValue(&I, L);
4709   DAG.setRoot(OutChain);
4710 }
4711 
4712 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4713   SDLoc dl = getCurSDLoc();
4714 
4715   AtomicOrdering Ordering = I.getOrdering();
4716   SyncScope::ID SSID = I.getSyncScopeID();
4717 
4718   SDValue InChain = getRoot();
4719 
4720   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4721   EVT MemVT =
4722       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4723 
4724   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4725     report_fatal_error("Cannot generate unaligned atomic store");
4726 
4727   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4728 
4729   MachineFunction &MF = DAG.getMachineFunction();
4730   MachineMemOperand *MMO = MF.getMachineMemOperand(
4731       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4732       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4733 
4734   SDValue Val = getValue(I.getValueOperand());
4735   if (Val.getValueType() != MemVT)
4736     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4737   SDValue Ptr = getValue(I.getPointerOperand());
4738 
4739   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4740     // TODO: Once this is better exercised by tests, it should be merged with
4741     // the normal path for stores to prevent future divergence.
4742     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4743     DAG.setRoot(S);
4744     return;
4745   }
4746   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4747                                    Ptr, Val, MMO);
4748 
4749 
4750   DAG.setRoot(OutChain);
4751 }
4752 
4753 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4754 /// node.
4755 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4756                                                unsigned Intrinsic) {
4757   // Ignore the callsite's attributes. A specific call site may be marked with
4758   // readnone, but the lowering code will expect the chain based on the
4759   // definition.
4760   const Function *F = I.getCalledFunction();
4761   bool HasChain = !F->doesNotAccessMemory();
4762   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4763 
4764   // Build the operand list.
4765   SmallVector<SDValue, 8> Ops;
4766   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4767     if (OnlyLoad) {
4768       // We don't need to serialize loads against other loads.
4769       Ops.push_back(DAG.getRoot());
4770     } else {
4771       Ops.push_back(getRoot());
4772     }
4773   }
4774 
4775   // Info is set by getTgtMemInstrinsic
4776   TargetLowering::IntrinsicInfo Info;
4777   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4778   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4779                                                DAG.getMachineFunction(),
4780                                                Intrinsic);
4781 
4782   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4783   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4784       Info.opc == ISD::INTRINSIC_W_CHAIN)
4785     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4786                                         TLI.getPointerTy(DAG.getDataLayout())));
4787 
4788   // Add all operands of the call to the operand list.
4789   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4790     const Value *Arg = I.getArgOperand(i);
4791     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4792       Ops.push_back(getValue(Arg));
4793       continue;
4794     }
4795 
4796     // Use TargetConstant instead of a regular constant for immarg.
4797     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4798     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4799       assert(CI->getBitWidth() <= 64 &&
4800              "large intrinsic immediates not handled");
4801       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4802     } else {
4803       Ops.push_back(
4804           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4805     }
4806   }
4807 
4808   SmallVector<EVT, 4> ValueVTs;
4809   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4810 
4811   if (HasChain)
4812     ValueVTs.push_back(MVT::Other);
4813 
4814   SDVTList VTs = DAG.getVTList(ValueVTs);
4815 
4816   // Propagate fast-math-flags from IR to node(s).
4817   SDNodeFlags Flags;
4818   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4819     Flags.copyFMF(*FPMO);
4820   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4821 
4822   // Create the node.
4823   SDValue Result;
4824   if (IsTgtIntrinsic) {
4825     // This is target intrinsic that touches memory
4826     AAMDNodes AAInfo;
4827     I.getAAMetadata(AAInfo);
4828     Result =
4829         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4830                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4831                                 Info.align, Info.flags, Info.size, AAInfo);
4832   } else if (!HasChain) {
4833     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4834   } else if (!I.getType()->isVoidTy()) {
4835     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4836   } else {
4837     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4838   }
4839 
4840   if (HasChain) {
4841     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4842     if (OnlyLoad)
4843       PendingLoads.push_back(Chain);
4844     else
4845       DAG.setRoot(Chain);
4846   }
4847 
4848   if (!I.getType()->isVoidTy()) {
4849     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4850       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4851       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4852     } else
4853       Result = lowerRangeToAssertZExt(DAG, I, Result);
4854 
4855     MaybeAlign Alignment = I.getRetAlign();
4856     if (!Alignment)
4857       Alignment = F->getAttributes().getRetAlignment();
4858     // Insert `assertalign` node if there's an alignment.
4859     if (InsertAssertAlign && Alignment) {
4860       Result =
4861           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4862     }
4863 
4864     setValue(&I, Result);
4865   }
4866 }
4867 
4868 /// GetSignificand - Get the significand and build it into a floating-point
4869 /// number with exponent of 1:
4870 ///
4871 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4872 ///
4873 /// where Op is the hexadecimal representation of floating point value.
4874 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4875   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4876                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4877   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4878                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4879   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4880 }
4881 
4882 /// GetExponent - Get the exponent:
4883 ///
4884 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4885 ///
4886 /// where Op is the hexadecimal representation of floating point value.
4887 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4888                            const TargetLowering &TLI, const SDLoc &dl) {
4889   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4890                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4891   SDValue t1 = DAG.getNode(
4892       ISD::SRL, dl, MVT::i32, t0,
4893       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4894   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4895                            DAG.getConstant(127, dl, MVT::i32));
4896   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4897 }
4898 
4899 /// getF32Constant - Get 32-bit floating point constant.
4900 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4901                               const SDLoc &dl) {
4902   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4903                            MVT::f32);
4904 }
4905 
4906 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4907                                        SelectionDAG &DAG) {
4908   // TODO: What fast-math-flags should be set on the floating-point nodes?
4909 
4910   //   IntegerPartOfX = ((int32_t)(t0);
4911   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4912 
4913   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4914   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4915   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4916 
4917   //   IntegerPartOfX <<= 23;
4918   IntegerPartOfX = DAG.getNode(
4919       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4920       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4921                                   DAG.getDataLayout())));
4922 
4923   SDValue TwoToFractionalPartOfX;
4924   if (LimitFloatPrecision <= 6) {
4925     // For floating-point precision of 6:
4926     //
4927     //   TwoToFractionalPartOfX =
4928     //     0.997535578f +
4929     //       (0.735607626f + 0.252464424f * x) * x;
4930     //
4931     // error 0.0144103317, which is 6 bits
4932     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4933                              getF32Constant(DAG, 0x3e814304, dl));
4934     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4935                              getF32Constant(DAG, 0x3f3c50c8, dl));
4936     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4937     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4938                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4939   } else if (LimitFloatPrecision <= 12) {
4940     // For floating-point precision of 12:
4941     //
4942     //   TwoToFractionalPartOfX =
4943     //     0.999892986f +
4944     //       (0.696457318f +
4945     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4946     //
4947     // error 0.000107046256, which is 13 to 14 bits
4948     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4949                              getF32Constant(DAG, 0x3da235e3, dl));
4950     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4951                              getF32Constant(DAG, 0x3e65b8f3, dl));
4952     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4953     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4954                              getF32Constant(DAG, 0x3f324b07, dl));
4955     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4956     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4957                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4958   } else { // LimitFloatPrecision <= 18
4959     // For floating-point precision of 18:
4960     //
4961     //   TwoToFractionalPartOfX =
4962     //     0.999999982f +
4963     //       (0.693148872f +
4964     //         (0.240227044f +
4965     //           (0.554906021e-1f +
4966     //             (0.961591928e-2f +
4967     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4968     // error 2.47208000*10^(-7), which is better than 18 bits
4969     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4970                              getF32Constant(DAG, 0x3924b03e, dl));
4971     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4972                              getF32Constant(DAG, 0x3ab24b87, dl));
4973     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4974     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4975                              getF32Constant(DAG, 0x3c1d8c17, dl));
4976     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4977     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4978                              getF32Constant(DAG, 0x3d634a1d, dl));
4979     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4980     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4981                              getF32Constant(DAG, 0x3e75fe14, dl));
4982     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4983     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4984                               getF32Constant(DAG, 0x3f317234, dl));
4985     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4986     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4987                                          getF32Constant(DAG, 0x3f800000, dl));
4988   }
4989 
4990   // Add the exponent into the result in integer domain.
4991   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4992   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4993                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4994 }
4995 
4996 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4997 /// limited-precision mode.
4998 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4999                          const TargetLowering &TLI, SDNodeFlags Flags) {
5000   if (Op.getValueType() == MVT::f32 &&
5001       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5002 
5003     // Put the exponent in the right bit position for later addition to the
5004     // final result:
5005     //
5006     // t0 = Op * log2(e)
5007 
5008     // TODO: What fast-math-flags should be set here?
5009     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5010                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5011     return getLimitedPrecisionExp2(t0, dl, DAG);
5012   }
5013 
5014   // No special expansion.
5015   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5016 }
5017 
5018 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5019 /// limited-precision mode.
5020 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5021                          const TargetLowering &TLI, SDNodeFlags Flags) {
5022   // TODO: What fast-math-flags should be set on the floating-point nodes?
5023 
5024   if (Op.getValueType() == MVT::f32 &&
5025       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5026     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5027 
5028     // Scale the exponent by log(2).
5029     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5030     SDValue LogOfExponent =
5031         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5032                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5033 
5034     // Get the significand and build it into a floating-point number with
5035     // exponent of 1.
5036     SDValue X = GetSignificand(DAG, Op1, dl);
5037 
5038     SDValue LogOfMantissa;
5039     if (LimitFloatPrecision <= 6) {
5040       // For floating-point precision of 6:
5041       //
5042       //   LogofMantissa =
5043       //     -1.1609546f +
5044       //       (1.4034025f - 0.23903021f * x) * x;
5045       //
5046       // error 0.0034276066, which is better than 8 bits
5047       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5048                                getF32Constant(DAG, 0xbe74c456, dl));
5049       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5050                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5051       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5052       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5053                                   getF32Constant(DAG, 0x3f949a29, dl));
5054     } else if (LimitFloatPrecision <= 12) {
5055       // For floating-point precision of 12:
5056       //
5057       //   LogOfMantissa =
5058       //     -1.7417939f +
5059       //       (2.8212026f +
5060       //         (-1.4699568f +
5061       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5062       //
5063       // error 0.000061011436, which is 14 bits
5064       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5065                                getF32Constant(DAG, 0xbd67b6d6, dl));
5066       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5067                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5068       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5069       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5070                                getF32Constant(DAG, 0x3fbc278b, dl));
5071       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5072       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5073                                getF32Constant(DAG, 0x40348e95, dl));
5074       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5075       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5076                                   getF32Constant(DAG, 0x3fdef31a, dl));
5077     } else { // LimitFloatPrecision <= 18
5078       // For floating-point precision of 18:
5079       //
5080       //   LogOfMantissa =
5081       //     -2.1072184f +
5082       //       (4.2372794f +
5083       //         (-3.7029485f +
5084       //           (2.2781945f +
5085       //             (-0.87823314f +
5086       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5087       //
5088       // error 0.0000023660568, which is better than 18 bits
5089       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5090                                getF32Constant(DAG, 0xbc91e5ac, dl));
5091       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5092                                getF32Constant(DAG, 0x3e4350aa, dl));
5093       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5094       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5095                                getF32Constant(DAG, 0x3f60d3e3, dl));
5096       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5097       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5098                                getF32Constant(DAG, 0x4011cdf0, dl));
5099       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5100       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5101                                getF32Constant(DAG, 0x406cfd1c, dl));
5102       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5103       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5104                                getF32Constant(DAG, 0x408797cb, dl));
5105       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5106       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5107                                   getF32Constant(DAG, 0x4006dcab, dl));
5108     }
5109 
5110     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5111   }
5112 
5113   // No special expansion.
5114   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5115 }
5116 
5117 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5118 /// limited-precision mode.
5119 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5120                           const TargetLowering &TLI, SDNodeFlags Flags) {
5121   // TODO: What fast-math-flags should be set on the floating-point nodes?
5122 
5123   if (Op.getValueType() == MVT::f32 &&
5124       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5125     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5126 
5127     // Get the exponent.
5128     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5129 
5130     // Get the significand and build it into a floating-point number with
5131     // exponent of 1.
5132     SDValue X = GetSignificand(DAG, Op1, dl);
5133 
5134     // Different possible minimax approximations of significand in
5135     // floating-point for various degrees of accuracy over [1,2].
5136     SDValue Log2ofMantissa;
5137     if (LimitFloatPrecision <= 6) {
5138       // For floating-point precision of 6:
5139       //
5140       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5141       //
5142       // error 0.0049451742, which is more than 7 bits
5143       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5144                                getF32Constant(DAG, 0xbeb08fe0, dl));
5145       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5146                                getF32Constant(DAG, 0x40019463, dl));
5147       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5148       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5149                                    getF32Constant(DAG, 0x3fd6633d, dl));
5150     } else if (LimitFloatPrecision <= 12) {
5151       // For floating-point precision of 12:
5152       //
5153       //   Log2ofMantissa =
5154       //     -2.51285454f +
5155       //       (4.07009056f +
5156       //         (-2.12067489f +
5157       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5158       //
5159       // error 0.0000876136000, which is better than 13 bits
5160       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5161                                getF32Constant(DAG, 0xbda7262e, dl));
5162       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5163                                getF32Constant(DAG, 0x3f25280b, dl));
5164       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5165       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5166                                getF32Constant(DAG, 0x4007b923, dl));
5167       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5168       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5169                                getF32Constant(DAG, 0x40823e2f, dl));
5170       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5171       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5172                                    getF32Constant(DAG, 0x4020d29c, dl));
5173     } else { // LimitFloatPrecision <= 18
5174       // For floating-point precision of 18:
5175       //
5176       //   Log2ofMantissa =
5177       //     -3.0400495f +
5178       //       (6.1129976f +
5179       //         (-5.3420409f +
5180       //           (3.2865683f +
5181       //             (-1.2669343f +
5182       //               (0.27515199f -
5183       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5184       //
5185       // error 0.0000018516, which is better than 18 bits
5186       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5187                                getF32Constant(DAG, 0xbcd2769e, dl));
5188       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5189                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5190       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5191       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5192                                getF32Constant(DAG, 0x3fa22ae7, dl));
5193       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5194       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5195                                getF32Constant(DAG, 0x40525723, dl));
5196       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5197       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5198                                getF32Constant(DAG, 0x40aaf200, dl));
5199       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5200       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5201                                getF32Constant(DAG, 0x40c39dad, dl));
5202       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5203       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5204                                    getF32Constant(DAG, 0x4042902c, dl));
5205     }
5206 
5207     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5208   }
5209 
5210   // No special expansion.
5211   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5212 }
5213 
5214 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5215 /// limited-precision mode.
5216 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5217                            const TargetLowering &TLI, SDNodeFlags Flags) {
5218   // TODO: What fast-math-flags should be set on the floating-point nodes?
5219 
5220   if (Op.getValueType() == MVT::f32 &&
5221       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5222     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5223 
5224     // Scale the exponent by log10(2) [0.30102999f].
5225     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5226     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5227                                         getF32Constant(DAG, 0x3e9a209a, dl));
5228 
5229     // Get the significand and build it into a floating-point number with
5230     // exponent of 1.
5231     SDValue X = GetSignificand(DAG, Op1, dl);
5232 
5233     SDValue Log10ofMantissa;
5234     if (LimitFloatPrecision <= 6) {
5235       // For floating-point precision of 6:
5236       //
5237       //   Log10ofMantissa =
5238       //     -0.50419619f +
5239       //       (0.60948995f - 0.10380950f * x) * x;
5240       //
5241       // error 0.0014886165, which is 6 bits
5242       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5243                                getF32Constant(DAG, 0xbdd49a13, dl));
5244       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5245                                getF32Constant(DAG, 0x3f1c0789, dl));
5246       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5247       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5248                                     getF32Constant(DAG, 0x3f011300, dl));
5249     } else if (LimitFloatPrecision <= 12) {
5250       // For floating-point precision of 12:
5251       //
5252       //   Log10ofMantissa =
5253       //     -0.64831180f +
5254       //       (0.91751397f +
5255       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5256       //
5257       // error 0.00019228036, which is better than 12 bits
5258       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5259                                getF32Constant(DAG, 0x3d431f31, dl));
5260       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5261                                getF32Constant(DAG, 0x3ea21fb2, dl));
5262       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5263       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5264                                getF32Constant(DAG, 0x3f6ae232, dl));
5265       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5266       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5267                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5268     } else { // LimitFloatPrecision <= 18
5269       // For floating-point precision of 18:
5270       //
5271       //   Log10ofMantissa =
5272       //     -0.84299375f +
5273       //       (1.5327582f +
5274       //         (-1.0688956f +
5275       //           (0.49102474f +
5276       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5277       //
5278       // error 0.0000037995730, which is better than 18 bits
5279       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5280                                getF32Constant(DAG, 0x3c5d51ce, dl));
5281       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5282                                getF32Constant(DAG, 0x3e00685a, dl));
5283       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5284       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5285                                getF32Constant(DAG, 0x3efb6798, dl));
5286       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5287       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5288                                getF32Constant(DAG, 0x3f88d192, dl));
5289       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5290       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5291                                getF32Constant(DAG, 0x3fc4316c, dl));
5292       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5293       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5294                                     getF32Constant(DAG, 0x3f57ce70, dl));
5295     }
5296 
5297     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5298   }
5299 
5300   // No special expansion.
5301   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5302 }
5303 
5304 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5305 /// limited-precision mode.
5306 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5307                           const TargetLowering &TLI, SDNodeFlags Flags) {
5308   if (Op.getValueType() == MVT::f32 &&
5309       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5310     return getLimitedPrecisionExp2(Op, dl, DAG);
5311 
5312   // No special expansion.
5313   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5314 }
5315 
5316 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5317 /// limited-precision mode with x == 10.0f.
5318 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5319                          SelectionDAG &DAG, const TargetLowering &TLI,
5320                          SDNodeFlags Flags) {
5321   bool IsExp10 = false;
5322   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5323       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5324     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5325       APFloat Ten(10.0f);
5326       IsExp10 = LHSC->isExactlyValue(Ten);
5327     }
5328   }
5329 
5330   // TODO: What fast-math-flags should be set on the FMUL node?
5331   if (IsExp10) {
5332     // Put the exponent in the right bit position for later addition to the
5333     // final result:
5334     //
5335     //   #define LOG2OF10 3.3219281f
5336     //   t0 = Op * LOG2OF10;
5337     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5338                              getF32Constant(DAG, 0x40549a78, dl));
5339     return getLimitedPrecisionExp2(t0, dl, DAG);
5340   }
5341 
5342   // No special expansion.
5343   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5344 }
5345 
5346 /// ExpandPowI - Expand a llvm.powi intrinsic.
5347 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5348                           SelectionDAG &DAG) {
5349   // If RHS is a constant, we can expand this out to a multiplication tree,
5350   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5351   // optimizing for size, we only want to do this if the expansion would produce
5352   // a small number of multiplies, otherwise we do the full expansion.
5353   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5354     // Get the exponent as a positive value.
5355     unsigned Val = RHSC->getSExtValue();
5356     if ((int)Val < 0) Val = -Val;
5357 
5358     // powi(x, 0) -> 1.0
5359     if (Val == 0)
5360       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5361 
5362     bool OptForSize = DAG.shouldOptForSize();
5363     if (!OptForSize ||
5364         // If optimizing for size, don't insert too many multiplies.
5365         // This inserts up to 5 multiplies.
5366         countPopulation(Val) + Log2_32(Val) < 7) {
5367       // We use the simple binary decomposition method to generate the multiply
5368       // sequence.  There are more optimal ways to do this (for example,
5369       // powi(x,15) generates one more multiply than it should), but this has
5370       // the benefit of being both really simple and much better than a libcall.
5371       SDValue Res;  // Logically starts equal to 1.0
5372       SDValue CurSquare = LHS;
5373       // TODO: Intrinsics should have fast-math-flags that propagate to these
5374       // nodes.
5375       while (Val) {
5376         if (Val & 1) {
5377           if (Res.getNode())
5378             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5379           else
5380             Res = CurSquare;  // 1.0*CurSquare.
5381         }
5382 
5383         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5384                                 CurSquare, CurSquare);
5385         Val >>= 1;
5386       }
5387 
5388       // If the original was negative, invert the result, producing 1/(x*x*x).
5389       if (RHSC->getSExtValue() < 0)
5390         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5391                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5392       return Res;
5393     }
5394   }
5395 
5396   // Otherwise, expand to a libcall.
5397   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5398 }
5399 
5400 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5401                             SDValue LHS, SDValue RHS, SDValue Scale,
5402                             SelectionDAG &DAG, const TargetLowering &TLI) {
5403   EVT VT = LHS.getValueType();
5404   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5405   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5406   LLVMContext &Ctx = *DAG.getContext();
5407 
5408   // If the type is legal but the operation isn't, this node might survive all
5409   // the way to operation legalization. If we end up there and we do not have
5410   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5411   // node.
5412 
5413   // Coax the legalizer into expanding the node during type legalization instead
5414   // by bumping the size by one bit. This will force it to Promote, enabling the
5415   // early expansion and avoiding the need to expand later.
5416 
5417   // We don't have to do this if Scale is 0; that can always be expanded, unless
5418   // it's a saturating signed operation. Those can experience true integer
5419   // division overflow, a case which we must avoid.
5420 
5421   // FIXME: We wouldn't have to do this (or any of the early
5422   // expansion/promotion) if it was possible to expand a libcall of an
5423   // illegal type during operation legalization. But it's not, so things
5424   // get a bit hacky.
5425   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5426   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5427       (TLI.isTypeLegal(VT) ||
5428        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5429     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5430         Opcode, VT, ScaleInt);
5431     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5432       EVT PromVT;
5433       if (VT.isScalarInteger())
5434         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5435       else if (VT.isVector()) {
5436         PromVT = VT.getVectorElementType();
5437         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5438         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5439       } else
5440         llvm_unreachable("Wrong VT for DIVFIX?");
5441       if (Signed) {
5442         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5443         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5444       } else {
5445         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5446         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5447       }
5448       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5449       // For saturating operations, we need to shift up the LHS to get the
5450       // proper saturation width, and then shift down again afterwards.
5451       if (Saturating)
5452         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5453                           DAG.getConstant(1, DL, ShiftTy));
5454       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5455       if (Saturating)
5456         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5457                           DAG.getConstant(1, DL, ShiftTy));
5458       return DAG.getZExtOrTrunc(Res, DL, VT);
5459     }
5460   }
5461 
5462   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5463 }
5464 
5465 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5466 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5467 static void
5468 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5469                      const SDValue &N) {
5470   switch (N.getOpcode()) {
5471   case ISD::CopyFromReg: {
5472     SDValue Op = N.getOperand(1);
5473     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5474                       Op.getValueType().getSizeInBits());
5475     return;
5476   }
5477   case ISD::BITCAST:
5478   case ISD::AssertZext:
5479   case ISD::AssertSext:
5480   case ISD::TRUNCATE:
5481     getUnderlyingArgRegs(Regs, N.getOperand(0));
5482     return;
5483   case ISD::BUILD_PAIR:
5484   case ISD::BUILD_VECTOR:
5485   case ISD::CONCAT_VECTORS:
5486     for (SDValue Op : N->op_values())
5487       getUnderlyingArgRegs(Regs, Op);
5488     return;
5489   default:
5490     return;
5491   }
5492 }
5493 
5494 /// If the DbgValueInst is a dbg_value of a function argument, create the
5495 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5496 /// instruction selection, they will be inserted to the entry BB.
5497 /// We don't currently support this for variadic dbg_values, as they shouldn't
5498 /// appear for function arguments or in the prologue.
5499 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5500     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5501     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5502   const Argument *Arg = dyn_cast<Argument>(V);
5503   if (!Arg)
5504     return false;
5505 
5506   if (!IsDbgDeclare) {
5507     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5508     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5509     // the entry block.
5510     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5511     if (!IsInEntryBlock)
5512       return false;
5513 
5514     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5515     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5516     // variable that also is a param.
5517     //
5518     // Although, if we are at the top of the entry block already, we can still
5519     // emit using ArgDbgValue. This might catch some situations when the
5520     // dbg.value refers to an argument that isn't used in the entry block, so
5521     // any CopyToReg node would be optimized out and the only way to express
5522     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5523     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5524     // we should only emit as ArgDbgValue if the Variable is an argument to the
5525     // current function, and the dbg.value intrinsic is found in the entry
5526     // block.
5527     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5528         !DL->getInlinedAt();
5529     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5530     if (!IsInPrologue && !VariableIsFunctionInputArg)
5531       return false;
5532 
5533     // Here we assume that a function argument on IR level only can be used to
5534     // describe one input parameter on source level. If we for example have
5535     // source code like this
5536     //
5537     //    struct A { long x, y; };
5538     //    void foo(struct A a, long b) {
5539     //      ...
5540     //      b = a.x;
5541     //      ...
5542     //    }
5543     //
5544     // and IR like this
5545     //
5546     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5547     //  entry:
5548     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5549     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5550     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5551     //    ...
5552     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5553     //    ...
5554     //
5555     // then the last dbg.value is describing a parameter "b" using a value that
5556     // is an argument. But since we already has used %a1 to describe a parameter
5557     // we should not handle that last dbg.value here (that would result in an
5558     // incorrect hoisting of the DBG_VALUE to the function entry).
5559     // Notice that we allow one dbg.value per IR level argument, to accommodate
5560     // for the situation with fragments above.
5561     if (VariableIsFunctionInputArg) {
5562       unsigned ArgNo = Arg->getArgNo();
5563       if (ArgNo >= FuncInfo.DescribedArgs.size())
5564         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5565       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5566         return false;
5567       FuncInfo.DescribedArgs.set(ArgNo);
5568     }
5569   }
5570 
5571   MachineFunction &MF = DAG.getMachineFunction();
5572   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5573 
5574   bool IsIndirect = false;
5575   Optional<MachineOperand> Op;
5576   // Some arguments' frame index is recorded during argument lowering.
5577   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5578   if (FI != std::numeric_limits<int>::max())
5579     Op = MachineOperand::CreateFI(FI);
5580 
5581   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5582   if (!Op && N.getNode()) {
5583     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5584     Register Reg;
5585     if (ArgRegsAndSizes.size() == 1)
5586       Reg = ArgRegsAndSizes.front().first;
5587 
5588     if (Reg && Reg.isVirtual()) {
5589       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5590       Register PR = RegInfo.getLiveInPhysReg(Reg);
5591       if (PR)
5592         Reg = PR;
5593     }
5594     if (Reg) {
5595       Op = MachineOperand::CreateReg(Reg, false);
5596       IsIndirect = IsDbgDeclare;
5597     }
5598   }
5599 
5600   if (!Op && N.getNode()) {
5601     // Check if frame index is available.
5602     SDValue LCandidate = peekThroughBitcasts(N);
5603     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5604       if (FrameIndexSDNode *FINode =
5605           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5606         Op = MachineOperand::CreateFI(FINode->getIndex());
5607   }
5608 
5609   if (!Op) {
5610     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5611     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5612                                          SplitRegs) {
5613       unsigned Offset = 0;
5614       for (auto RegAndSize : SplitRegs) {
5615         // If the expression is already a fragment, the current register
5616         // offset+size might extend beyond the fragment. In this case, only
5617         // the register bits that are inside the fragment are relevant.
5618         int RegFragmentSizeInBits = RegAndSize.second;
5619         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5620           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5621           // The register is entirely outside the expression fragment,
5622           // so is irrelevant for debug info.
5623           if (Offset >= ExprFragmentSizeInBits)
5624             break;
5625           // The register is partially outside the expression fragment, only
5626           // the low bits within the fragment are relevant for debug info.
5627           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5628             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5629           }
5630         }
5631 
5632         auto FragmentExpr = DIExpression::createFragmentExpression(
5633             Expr, Offset, RegFragmentSizeInBits);
5634         Offset += RegAndSize.second;
5635         // If a valid fragment expression cannot be created, the variable's
5636         // correct value cannot be determined and so it is set as Undef.
5637         if (!FragmentExpr) {
5638           SDDbgValue *SDV = DAG.getConstantDbgValue(
5639               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5640           DAG.AddDbgValue(SDV, false);
5641           continue;
5642         }
5643         FuncInfo.ArgDbgValues.push_back(
5644           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5645                   RegAndSize.first, Variable, *FragmentExpr));
5646       }
5647     };
5648 
5649     // Check if ValueMap has reg number.
5650     DenseMap<const Value *, Register>::const_iterator
5651       VMI = FuncInfo.ValueMap.find(V);
5652     if (VMI != FuncInfo.ValueMap.end()) {
5653       const auto &TLI = DAG.getTargetLoweringInfo();
5654       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5655                        V->getType(), None);
5656       if (RFV.occupiesMultipleRegs()) {
5657         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5658         return true;
5659       }
5660 
5661       Op = MachineOperand::CreateReg(VMI->second, false);
5662       IsIndirect = IsDbgDeclare;
5663     } else if (ArgRegsAndSizes.size() > 1) {
5664       // This was split due to the calling convention, and no virtual register
5665       // mapping exists for the value.
5666       splitMultiRegDbgValue(ArgRegsAndSizes);
5667       return true;
5668     }
5669   }
5670 
5671   if (!Op)
5672     return false;
5673 
5674   assert(Variable->isValidLocationForIntrinsic(DL) &&
5675          "Expected inlined-at fields to agree");
5676   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5677   FuncInfo.ArgDbgValues.push_back(
5678       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5679               *Op, Variable, Expr));
5680 
5681   return true;
5682 }
5683 
5684 /// Return the appropriate SDDbgValue based on N.
5685 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5686                                              DILocalVariable *Variable,
5687                                              DIExpression *Expr,
5688                                              const DebugLoc &dl,
5689                                              unsigned DbgSDNodeOrder) {
5690   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5691     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5692     // stack slot locations.
5693     //
5694     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5695     // debug values here after optimization:
5696     //
5697     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5698     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5699     //
5700     // Both describe the direct values of their associated variables.
5701     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5702                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5703   }
5704   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5705                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5706 }
5707 
5708 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5709   switch (Intrinsic) {
5710   case Intrinsic::smul_fix:
5711     return ISD::SMULFIX;
5712   case Intrinsic::umul_fix:
5713     return ISD::UMULFIX;
5714   case Intrinsic::smul_fix_sat:
5715     return ISD::SMULFIXSAT;
5716   case Intrinsic::umul_fix_sat:
5717     return ISD::UMULFIXSAT;
5718   case Intrinsic::sdiv_fix:
5719     return ISD::SDIVFIX;
5720   case Intrinsic::udiv_fix:
5721     return ISD::UDIVFIX;
5722   case Intrinsic::sdiv_fix_sat:
5723     return ISD::SDIVFIXSAT;
5724   case Intrinsic::udiv_fix_sat:
5725     return ISD::UDIVFIXSAT;
5726   default:
5727     llvm_unreachable("Unhandled fixed point intrinsic");
5728   }
5729 }
5730 
5731 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5732                                            const char *FunctionName) {
5733   assert(FunctionName && "FunctionName must not be nullptr");
5734   SDValue Callee = DAG.getExternalSymbol(
5735       FunctionName,
5736       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5737   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5738 }
5739 
5740 /// Given a @llvm.call.preallocated.setup, return the corresponding
5741 /// preallocated call.
5742 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5743   assert(cast<CallBase>(PreallocatedSetup)
5744                  ->getCalledFunction()
5745                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5746          "expected call_preallocated_setup Value");
5747   for (auto *U : PreallocatedSetup->users()) {
5748     auto *UseCall = cast<CallBase>(U);
5749     const Function *Fn = UseCall->getCalledFunction();
5750     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5751       return UseCall;
5752     }
5753   }
5754   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5755 }
5756 
5757 /// Lower the call to the specified intrinsic function.
5758 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5759                                              unsigned Intrinsic) {
5760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5761   SDLoc sdl = getCurSDLoc();
5762   DebugLoc dl = getCurDebugLoc();
5763   SDValue Res;
5764 
5765   SDNodeFlags Flags;
5766   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5767     Flags.copyFMF(*FPOp);
5768 
5769   switch (Intrinsic) {
5770   default:
5771     // By default, turn this into a target intrinsic node.
5772     visitTargetIntrinsic(I, Intrinsic);
5773     return;
5774   case Intrinsic::vscale: {
5775     match(&I, m_VScale(DAG.getDataLayout()));
5776     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5777     setValue(&I,
5778              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5779     return;
5780   }
5781   case Intrinsic::vastart:  visitVAStart(I); return;
5782   case Intrinsic::vaend:    visitVAEnd(I); return;
5783   case Intrinsic::vacopy:   visitVACopy(I); return;
5784   case Intrinsic::returnaddress:
5785     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5786                              TLI.getPointerTy(DAG.getDataLayout()),
5787                              getValue(I.getArgOperand(0))));
5788     return;
5789   case Intrinsic::addressofreturnaddress:
5790     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5791                              TLI.getPointerTy(DAG.getDataLayout())));
5792     return;
5793   case Intrinsic::sponentry:
5794     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5795                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5796     return;
5797   case Intrinsic::frameaddress:
5798     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5799                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5800                              getValue(I.getArgOperand(0))));
5801     return;
5802   case Intrinsic::read_volatile_register:
5803   case Intrinsic::read_register: {
5804     Value *Reg = I.getArgOperand(0);
5805     SDValue Chain = getRoot();
5806     SDValue RegName =
5807         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5808     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5809     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5810       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5811     setValue(&I, Res);
5812     DAG.setRoot(Res.getValue(1));
5813     return;
5814   }
5815   case Intrinsic::write_register: {
5816     Value *Reg = I.getArgOperand(0);
5817     Value *RegValue = I.getArgOperand(1);
5818     SDValue Chain = getRoot();
5819     SDValue RegName =
5820         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5821     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5822                             RegName, getValue(RegValue)));
5823     return;
5824   }
5825   case Intrinsic::memcpy: {
5826     const auto &MCI = cast<MemCpyInst>(I);
5827     SDValue Op1 = getValue(I.getArgOperand(0));
5828     SDValue Op2 = getValue(I.getArgOperand(1));
5829     SDValue Op3 = getValue(I.getArgOperand(2));
5830     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5831     Align DstAlign = MCI.getDestAlign().valueOrOne();
5832     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5833     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5834     bool isVol = MCI.isVolatile();
5835     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5836     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5837     // node.
5838     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5839     AAMDNodes AAInfo;
5840     I.getAAMetadata(AAInfo);
5841     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5842                                /* AlwaysInline */ false, isTC,
5843                                MachinePointerInfo(I.getArgOperand(0)),
5844                                MachinePointerInfo(I.getArgOperand(1)), AAInfo);
5845     updateDAGForMaybeTailCall(MC);
5846     return;
5847   }
5848   case Intrinsic::memcpy_inline: {
5849     const auto &MCI = cast<MemCpyInlineInst>(I);
5850     SDValue Dst = getValue(I.getArgOperand(0));
5851     SDValue Src = getValue(I.getArgOperand(1));
5852     SDValue Size = getValue(I.getArgOperand(2));
5853     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5854     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5855     Align DstAlign = MCI.getDestAlign().valueOrOne();
5856     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5857     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5858     bool isVol = MCI.isVolatile();
5859     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5860     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5861     // node.
5862     AAMDNodes AAInfo;
5863     I.getAAMetadata(AAInfo);
5864     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5865                                /* AlwaysInline */ true, isTC,
5866                                MachinePointerInfo(I.getArgOperand(0)),
5867                                MachinePointerInfo(I.getArgOperand(1)), AAInfo);
5868     updateDAGForMaybeTailCall(MC);
5869     return;
5870   }
5871   case Intrinsic::memset: {
5872     const auto &MSI = cast<MemSetInst>(I);
5873     SDValue Op1 = getValue(I.getArgOperand(0));
5874     SDValue Op2 = getValue(I.getArgOperand(1));
5875     SDValue Op3 = getValue(I.getArgOperand(2));
5876     // @llvm.memset defines 0 and 1 to both mean no alignment.
5877     Align Alignment = MSI.getDestAlign().valueOrOne();
5878     bool isVol = MSI.isVolatile();
5879     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5880     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5881     AAMDNodes AAInfo;
5882     I.getAAMetadata(AAInfo);
5883     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5884                                MachinePointerInfo(I.getArgOperand(0)), AAInfo);
5885     updateDAGForMaybeTailCall(MS);
5886     return;
5887   }
5888   case Intrinsic::memmove: {
5889     const auto &MMI = cast<MemMoveInst>(I);
5890     SDValue Op1 = getValue(I.getArgOperand(0));
5891     SDValue Op2 = getValue(I.getArgOperand(1));
5892     SDValue Op3 = getValue(I.getArgOperand(2));
5893     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5894     Align DstAlign = MMI.getDestAlign().valueOrOne();
5895     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5896     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5897     bool isVol = MMI.isVolatile();
5898     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5899     // FIXME: Support passing different dest/src alignments to the memmove DAG
5900     // node.
5901     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5902     AAMDNodes AAInfo;
5903     I.getAAMetadata(AAInfo);
5904     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5905                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5906                                 MachinePointerInfo(I.getArgOperand(1)), AAInfo);
5907     updateDAGForMaybeTailCall(MM);
5908     return;
5909   }
5910   case Intrinsic::memcpy_element_unordered_atomic: {
5911     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5912     SDValue Dst = getValue(MI.getRawDest());
5913     SDValue Src = getValue(MI.getRawSource());
5914     SDValue Length = getValue(MI.getLength());
5915 
5916     unsigned DstAlign = MI.getDestAlignment();
5917     unsigned SrcAlign = MI.getSourceAlignment();
5918     Type *LengthTy = MI.getLength()->getType();
5919     unsigned ElemSz = MI.getElementSizeInBytes();
5920     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5921     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5922                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5923                                      MachinePointerInfo(MI.getRawDest()),
5924                                      MachinePointerInfo(MI.getRawSource()));
5925     updateDAGForMaybeTailCall(MC);
5926     return;
5927   }
5928   case Intrinsic::memmove_element_unordered_atomic: {
5929     auto &MI = cast<AtomicMemMoveInst>(I);
5930     SDValue Dst = getValue(MI.getRawDest());
5931     SDValue Src = getValue(MI.getRawSource());
5932     SDValue Length = getValue(MI.getLength());
5933 
5934     unsigned DstAlign = MI.getDestAlignment();
5935     unsigned SrcAlign = MI.getSourceAlignment();
5936     Type *LengthTy = MI.getLength()->getType();
5937     unsigned ElemSz = MI.getElementSizeInBytes();
5938     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5939     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5940                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5941                                       MachinePointerInfo(MI.getRawDest()),
5942                                       MachinePointerInfo(MI.getRawSource()));
5943     updateDAGForMaybeTailCall(MC);
5944     return;
5945   }
5946   case Intrinsic::memset_element_unordered_atomic: {
5947     auto &MI = cast<AtomicMemSetInst>(I);
5948     SDValue Dst = getValue(MI.getRawDest());
5949     SDValue Val = getValue(MI.getValue());
5950     SDValue Length = getValue(MI.getLength());
5951 
5952     unsigned DstAlign = MI.getDestAlignment();
5953     Type *LengthTy = MI.getLength()->getType();
5954     unsigned ElemSz = MI.getElementSizeInBytes();
5955     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5956     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5957                                      LengthTy, ElemSz, isTC,
5958                                      MachinePointerInfo(MI.getRawDest()));
5959     updateDAGForMaybeTailCall(MC);
5960     return;
5961   }
5962   case Intrinsic::call_preallocated_setup: {
5963     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5964     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5965     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5966                               getRoot(), SrcValue);
5967     setValue(&I, Res);
5968     DAG.setRoot(Res);
5969     return;
5970   }
5971   case Intrinsic::call_preallocated_arg: {
5972     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5973     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5974     SDValue Ops[3];
5975     Ops[0] = getRoot();
5976     Ops[1] = SrcValue;
5977     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5978                                    MVT::i32); // arg index
5979     SDValue Res = DAG.getNode(
5980         ISD::PREALLOCATED_ARG, sdl,
5981         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5982     setValue(&I, Res);
5983     DAG.setRoot(Res.getValue(1));
5984     return;
5985   }
5986   case Intrinsic::dbg_addr:
5987   case Intrinsic::dbg_declare: {
5988     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
5989     // they are non-variadic.
5990     const auto &DI = cast<DbgVariableIntrinsic>(I);
5991     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
5992     DILocalVariable *Variable = DI.getVariable();
5993     DIExpression *Expression = DI.getExpression();
5994     dropDanglingDebugInfo(Variable, Expression);
5995     assert(Variable && "Missing variable");
5996     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5997                       << "\n");
5998     // Check if address has undef value.
5999     const Value *Address = DI.getVariableLocationOp(0);
6000     if (!Address || isa<UndefValue>(Address) ||
6001         (Address->use_empty() && !isa<Argument>(Address))) {
6002       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6003                         << " (bad/undef/unused-arg address)\n");
6004       return;
6005     }
6006 
6007     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6008 
6009     // Check if this variable can be described by a frame index, typically
6010     // either as a static alloca or a byval parameter.
6011     int FI = std::numeric_limits<int>::max();
6012     if (const auto *AI =
6013             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6014       if (AI->isStaticAlloca()) {
6015         auto I = FuncInfo.StaticAllocaMap.find(AI);
6016         if (I != FuncInfo.StaticAllocaMap.end())
6017           FI = I->second;
6018       }
6019     } else if (const auto *Arg = dyn_cast<Argument>(
6020                    Address->stripInBoundsConstantOffsets())) {
6021       FI = FuncInfo.getArgumentFrameIndex(Arg);
6022     }
6023 
6024     // llvm.dbg.addr is control dependent and always generates indirect
6025     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6026     // the MachineFunction variable table.
6027     if (FI != std::numeric_limits<int>::max()) {
6028       if (Intrinsic == Intrinsic::dbg_addr) {
6029         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6030             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6031             dl, SDNodeOrder);
6032         DAG.AddDbgValue(SDV, isParameter);
6033       } else {
6034         LLVM_DEBUG(dbgs() << "Skipping " << DI
6035                           << " (variable info stashed in MF side table)\n");
6036       }
6037       return;
6038     }
6039 
6040     SDValue &N = NodeMap[Address];
6041     if (!N.getNode() && isa<Argument>(Address))
6042       // Check unused arguments map.
6043       N = UnusedArgNodeMap[Address];
6044     SDDbgValue *SDV;
6045     if (N.getNode()) {
6046       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6047         Address = BCI->getOperand(0);
6048       // Parameters are handled specially.
6049       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6050       if (isParameter && FINode) {
6051         // Byval parameter. We have a frame index at this point.
6052         SDV =
6053             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6054                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6055       } else if (isa<Argument>(Address)) {
6056         // Address is an argument, so try to emit its dbg value using
6057         // virtual register info from the FuncInfo.ValueMap.
6058         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6059         return;
6060       } else {
6061         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6062                               true, dl, SDNodeOrder);
6063       }
6064       DAG.AddDbgValue(SDV, isParameter);
6065     } else {
6066       // If Address is an argument then try to emit its dbg value using
6067       // virtual register info from the FuncInfo.ValueMap.
6068       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6069                                     N)) {
6070         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6071                           << " (could not emit func-arg dbg_value)\n");
6072       }
6073     }
6074     return;
6075   }
6076   case Intrinsic::dbg_label: {
6077     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6078     DILabel *Label = DI.getLabel();
6079     assert(Label && "Missing label");
6080 
6081     SDDbgLabel *SDV;
6082     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6083     DAG.AddDbgLabel(SDV);
6084     return;
6085   }
6086   case Intrinsic::dbg_value: {
6087     const DbgValueInst &DI = cast<DbgValueInst>(I);
6088     assert(DI.getVariable() && "Missing variable");
6089 
6090     DILocalVariable *Variable = DI.getVariable();
6091     DIExpression *Expression = DI.getExpression();
6092     dropDanglingDebugInfo(Variable, Expression);
6093     SmallVector<Value *, 4> Values(DI.getValues());
6094     if (Values.empty())
6095       return;
6096 
6097     if (std::count(Values.begin(), Values.end(), nullptr))
6098       return;
6099 
6100     bool IsVariadic = DI.hasArgList();
6101     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6102                           SDNodeOrder, IsVariadic))
6103       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6104     return;
6105   }
6106 
6107   case Intrinsic::eh_typeid_for: {
6108     // Find the type id for the given typeinfo.
6109     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6110     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6111     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6112     setValue(&I, Res);
6113     return;
6114   }
6115 
6116   case Intrinsic::eh_return_i32:
6117   case Intrinsic::eh_return_i64:
6118     DAG.getMachineFunction().setCallsEHReturn(true);
6119     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6120                             MVT::Other,
6121                             getControlRoot(),
6122                             getValue(I.getArgOperand(0)),
6123                             getValue(I.getArgOperand(1))));
6124     return;
6125   case Intrinsic::eh_unwind_init:
6126     DAG.getMachineFunction().setCallsUnwindInit(true);
6127     return;
6128   case Intrinsic::eh_dwarf_cfa:
6129     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6130                              TLI.getPointerTy(DAG.getDataLayout()),
6131                              getValue(I.getArgOperand(0))));
6132     return;
6133   case Intrinsic::eh_sjlj_callsite: {
6134     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6135     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6136     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6137     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6138 
6139     MMI.setCurrentCallSite(CI->getZExtValue());
6140     return;
6141   }
6142   case Intrinsic::eh_sjlj_functioncontext: {
6143     // Get and store the index of the function context.
6144     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6145     AllocaInst *FnCtx =
6146       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6147     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6148     MFI.setFunctionContextIndex(FI);
6149     return;
6150   }
6151   case Intrinsic::eh_sjlj_setjmp: {
6152     SDValue Ops[2];
6153     Ops[0] = getRoot();
6154     Ops[1] = getValue(I.getArgOperand(0));
6155     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6156                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6157     setValue(&I, Op.getValue(0));
6158     DAG.setRoot(Op.getValue(1));
6159     return;
6160   }
6161   case Intrinsic::eh_sjlj_longjmp:
6162     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6163                             getRoot(), getValue(I.getArgOperand(0))));
6164     return;
6165   case Intrinsic::eh_sjlj_setup_dispatch:
6166     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6167                             getRoot()));
6168     return;
6169   case Intrinsic::masked_gather:
6170     visitMaskedGather(I);
6171     return;
6172   case Intrinsic::masked_load:
6173     visitMaskedLoad(I);
6174     return;
6175   case Intrinsic::masked_scatter:
6176     visitMaskedScatter(I);
6177     return;
6178   case Intrinsic::masked_store:
6179     visitMaskedStore(I);
6180     return;
6181   case Intrinsic::masked_expandload:
6182     visitMaskedLoad(I, true /* IsExpanding */);
6183     return;
6184   case Intrinsic::masked_compressstore:
6185     visitMaskedStore(I, true /* IsCompressing */);
6186     return;
6187   case Intrinsic::powi:
6188     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6189                             getValue(I.getArgOperand(1)), DAG));
6190     return;
6191   case Intrinsic::log:
6192     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6193     return;
6194   case Intrinsic::log2:
6195     setValue(&I,
6196              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6197     return;
6198   case Intrinsic::log10:
6199     setValue(&I,
6200              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6201     return;
6202   case Intrinsic::exp:
6203     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6204     return;
6205   case Intrinsic::exp2:
6206     setValue(&I,
6207              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6208     return;
6209   case Intrinsic::pow:
6210     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6211                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6212     return;
6213   case Intrinsic::sqrt:
6214   case Intrinsic::fabs:
6215   case Intrinsic::sin:
6216   case Intrinsic::cos:
6217   case Intrinsic::floor:
6218   case Intrinsic::ceil:
6219   case Intrinsic::trunc:
6220   case Intrinsic::rint:
6221   case Intrinsic::nearbyint:
6222   case Intrinsic::round:
6223   case Intrinsic::roundeven:
6224   case Intrinsic::canonicalize: {
6225     unsigned Opcode;
6226     switch (Intrinsic) {
6227     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6228     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6229     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6230     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6231     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6232     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6233     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6234     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6235     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6236     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6237     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6238     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6239     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6240     }
6241 
6242     setValue(&I, DAG.getNode(Opcode, sdl,
6243                              getValue(I.getArgOperand(0)).getValueType(),
6244                              getValue(I.getArgOperand(0)), Flags));
6245     return;
6246   }
6247   case Intrinsic::lround:
6248   case Intrinsic::llround:
6249   case Intrinsic::lrint:
6250   case Intrinsic::llrint: {
6251     unsigned Opcode;
6252     switch (Intrinsic) {
6253     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6254     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6255     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6256     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6257     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6258     }
6259 
6260     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6261     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6262                              getValue(I.getArgOperand(0))));
6263     return;
6264   }
6265   case Intrinsic::minnum:
6266     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6267                              getValue(I.getArgOperand(0)).getValueType(),
6268                              getValue(I.getArgOperand(0)),
6269                              getValue(I.getArgOperand(1)), Flags));
6270     return;
6271   case Intrinsic::maxnum:
6272     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6273                              getValue(I.getArgOperand(0)).getValueType(),
6274                              getValue(I.getArgOperand(0)),
6275                              getValue(I.getArgOperand(1)), Flags));
6276     return;
6277   case Intrinsic::minimum:
6278     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6279                              getValue(I.getArgOperand(0)).getValueType(),
6280                              getValue(I.getArgOperand(0)),
6281                              getValue(I.getArgOperand(1)), Flags));
6282     return;
6283   case Intrinsic::maximum:
6284     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6285                              getValue(I.getArgOperand(0)).getValueType(),
6286                              getValue(I.getArgOperand(0)),
6287                              getValue(I.getArgOperand(1)), Flags));
6288     return;
6289   case Intrinsic::copysign:
6290     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6291                              getValue(I.getArgOperand(0)).getValueType(),
6292                              getValue(I.getArgOperand(0)),
6293                              getValue(I.getArgOperand(1)), Flags));
6294     return;
6295   case Intrinsic::fma:
6296     setValue(&I, DAG.getNode(
6297                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6298                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6299                      getValue(I.getArgOperand(2)), Flags));
6300     return;
6301 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6302   case Intrinsic::INTRINSIC:
6303 #include "llvm/IR/ConstrainedOps.def"
6304     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6305     return;
6306 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6307 #include "llvm/IR/VPIntrinsics.def"
6308     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6309     return;
6310   case Intrinsic::fmuladd: {
6311     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6312     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6313         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6314       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6315                                getValue(I.getArgOperand(0)).getValueType(),
6316                                getValue(I.getArgOperand(0)),
6317                                getValue(I.getArgOperand(1)),
6318                                getValue(I.getArgOperand(2)), Flags));
6319     } else {
6320       // TODO: Intrinsic calls should have fast-math-flags.
6321       SDValue Mul = DAG.getNode(
6322           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6323           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6324       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6325                                 getValue(I.getArgOperand(0)).getValueType(),
6326                                 Mul, getValue(I.getArgOperand(2)), Flags);
6327       setValue(&I, Add);
6328     }
6329     return;
6330   }
6331   case Intrinsic::convert_to_fp16:
6332     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6333                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6334                                          getValue(I.getArgOperand(0)),
6335                                          DAG.getTargetConstant(0, sdl,
6336                                                                MVT::i32))));
6337     return;
6338   case Intrinsic::convert_from_fp16:
6339     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6340                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6341                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6342                                          getValue(I.getArgOperand(0)))));
6343     return;
6344   case Intrinsic::fptosi_sat: {
6345     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6346     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6347                              getValue(I.getArgOperand(0)),
6348                              DAG.getValueType(VT.getScalarType())));
6349     return;
6350   }
6351   case Intrinsic::fptoui_sat: {
6352     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6353     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6354                              getValue(I.getArgOperand(0)),
6355                              DAG.getValueType(VT.getScalarType())));
6356     return;
6357   }
6358   case Intrinsic::set_rounding:
6359     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6360                       {getRoot(), getValue(I.getArgOperand(0))});
6361     setValue(&I, Res);
6362     DAG.setRoot(Res.getValue(0));
6363     return;
6364   case Intrinsic::pcmarker: {
6365     SDValue Tmp = getValue(I.getArgOperand(0));
6366     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6367     return;
6368   }
6369   case Intrinsic::readcyclecounter: {
6370     SDValue Op = getRoot();
6371     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6372                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6373     setValue(&I, Res);
6374     DAG.setRoot(Res.getValue(1));
6375     return;
6376   }
6377   case Intrinsic::bitreverse:
6378     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6379                              getValue(I.getArgOperand(0)).getValueType(),
6380                              getValue(I.getArgOperand(0))));
6381     return;
6382   case Intrinsic::bswap:
6383     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6384                              getValue(I.getArgOperand(0)).getValueType(),
6385                              getValue(I.getArgOperand(0))));
6386     return;
6387   case Intrinsic::cttz: {
6388     SDValue Arg = getValue(I.getArgOperand(0));
6389     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6390     EVT Ty = Arg.getValueType();
6391     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6392                              sdl, Ty, Arg));
6393     return;
6394   }
6395   case Intrinsic::ctlz: {
6396     SDValue Arg = getValue(I.getArgOperand(0));
6397     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6398     EVT Ty = Arg.getValueType();
6399     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6400                              sdl, Ty, Arg));
6401     return;
6402   }
6403   case Intrinsic::ctpop: {
6404     SDValue Arg = getValue(I.getArgOperand(0));
6405     EVT Ty = Arg.getValueType();
6406     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6407     return;
6408   }
6409   case Intrinsic::fshl:
6410   case Intrinsic::fshr: {
6411     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6412     SDValue X = getValue(I.getArgOperand(0));
6413     SDValue Y = getValue(I.getArgOperand(1));
6414     SDValue Z = getValue(I.getArgOperand(2));
6415     EVT VT = X.getValueType();
6416 
6417     if (X == Y) {
6418       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6419       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6420     } else {
6421       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6422       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6423     }
6424     return;
6425   }
6426   case Intrinsic::sadd_sat: {
6427     SDValue Op1 = getValue(I.getArgOperand(0));
6428     SDValue Op2 = getValue(I.getArgOperand(1));
6429     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6430     return;
6431   }
6432   case Intrinsic::uadd_sat: {
6433     SDValue Op1 = getValue(I.getArgOperand(0));
6434     SDValue Op2 = getValue(I.getArgOperand(1));
6435     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6436     return;
6437   }
6438   case Intrinsic::ssub_sat: {
6439     SDValue Op1 = getValue(I.getArgOperand(0));
6440     SDValue Op2 = getValue(I.getArgOperand(1));
6441     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6442     return;
6443   }
6444   case Intrinsic::usub_sat: {
6445     SDValue Op1 = getValue(I.getArgOperand(0));
6446     SDValue Op2 = getValue(I.getArgOperand(1));
6447     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6448     return;
6449   }
6450   case Intrinsic::sshl_sat: {
6451     SDValue Op1 = getValue(I.getArgOperand(0));
6452     SDValue Op2 = getValue(I.getArgOperand(1));
6453     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6454     return;
6455   }
6456   case Intrinsic::ushl_sat: {
6457     SDValue Op1 = getValue(I.getArgOperand(0));
6458     SDValue Op2 = getValue(I.getArgOperand(1));
6459     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6460     return;
6461   }
6462   case Intrinsic::smul_fix:
6463   case Intrinsic::umul_fix:
6464   case Intrinsic::smul_fix_sat:
6465   case Intrinsic::umul_fix_sat: {
6466     SDValue Op1 = getValue(I.getArgOperand(0));
6467     SDValue Op2 = getValue(I.getArgOperand(1));
6468     SDValue Op3 = getValue(I.getArgOperand(2));
6469     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6470                              Op1.getValueType(), Op1, Op2, Op3));
6471     return;
6472   }
6473   case Intrinsic::sdiv_fix:
6474   case Intrinsic::udiv_fix:
6475   case Intrinsic::sdiv_fix_sat:
6476   case Intrinsic::udiv_fix_sat: {
6477     SDValue Op1 = getValue(I.getArgOperand(0));
6478     SDValue Op2 = getValue(I.getArgOperand(1));
6479     SDValue Op3 = getValue(I.getArgOperand(2));
6480     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6481                               Op1, Op2, Op3, DAG, TLI));
6482     return;
6483   }
6484   case Intrinsic::smax: {
6485     SDValue Op1 = getValue(I.getArgOperand(0));
6486     SDValue Op2 = getValue(I.getArgOperand(1));
6487     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6488     return;
6489   }
6490   case Intrinsic::smin: {
6491     SDValue Op1 = getValue(I.getArgOperand(0));
6492     SDValue Op2 = getValue(I.getArgOperand(1));
6493     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6494     return;
6495   }
6496   case Intrinsic::umax: {
6497     SDValue Op1 = getValue(I.getArgOperand(0));
6498     SDValue Op2 = getValue(I.getArgOperand(1));
6499     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6500     return;
6501   }
6502   case Intrinsic::umin: {
6503     SDValue Op1 = getValue(I.getArgOperand(0));
6504     SDValue Op2 = getValue(I.getArgOperand(1));
6505     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6506     return;
6507   }
6508   case Intrinsic::abs: {
6509     // TODO: Preserve "int min is poison" arg in SDAG?
6510     SDValue Op1 = getValue(I.getArgOperand(0));
6511     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6512     return;
6513   }
6514   case Intrinsic::stacksave: {
6515     SDValue Op = getRoot();
6516     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6517     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6518     setValue(&I, Res);
6519     DAG.setRoot(Res.getValue(1));
6520     return;
6521   }
6522   case Intrinsic::stackrestore:
6523     Res = getValue(I.getArgOperand(0));
6524     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6525     return;
6526   case Intrinsic::get_dynamic_area_offset: {
6527     SDValue Op = getRoot();
6528     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6529     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6530     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6531     // target.
6532     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6533       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6534                          " intrinsic!");
6535     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6536                       Op);
6537     DAG.setRoot(Op);
6538     setValue(&I, Res);
6539     return;
6540   }
6541   case Intrinsic::stackguard: {
6542     MachineFunction &MF = DAG.getMachineFunction();
6543     const Module &M = *MF.getFunction().getParent();
6544     SDValue Chain = getRoot();
6545     if (TLI.useLoadStackGuardNode()) {
6546       Res = getLoadStackGuard(DAG, sdl, Chain);
6547     } else {
6548       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6549       const Value *Global = TLI.getSDagStackGuard(M);
6550       Align Align = DL->getPrefTypeAlign(Global->getType());
6551       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6552                         MachinePointerInfo(Global, 0), Align,
6553                         MachineMemOperand::MOVolatile);
6554     }
6555     if (TLI.useStackGuardXorFP())
6556       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6557     DAG.setRoot(Chain);
6558     setValue(&I, Res);
6559     return;
6560   }
6561   case Intrinsic::stackprotector: {
6562     // Emit code into the DAG to store the stack guard onto the stack.
6563     MachineFunction &MF = DAG.getMachineFunction();
6564     MachineFrameInfo &MFI = MF.getFrameInfo();
6565     SDValue Src, Chain = getRoot();
6566 
6567     if (TLI.useLoadStackGuardNode())
6568       Src = getLoadStackGuard(DAG, sdl, Chain);
6569     else
6570       Src = getValue(I.getArgOperand(0));   // The guard's value.
6571 
6572     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6573 
6574     int FI = FuncInfo.StaticAllocaMap[Slot];
6575     MFI.setStackProtectorIndex(FI);
6576     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6577 
6578     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6579 
6580     // Store the stack protector onto the stack.
6581     Res = DAG.getStore(
6582         Chain, sdl, Src, FIN,
6583         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6584         MaybeAlign(), MachineMemOperand::MOVolatile);
6585     setValue(&I, Res);
6586     DAG.setRoot(Res);
6587     return;
6588   }
6589   case Intrinsic::objectsize:
6590     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6591 
6592   case Intrinsic::is_constant:
6593     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6594 
6595   case Intrinsic::annotation:
6596   case Intrinsic::ptr_annotation:
6597   case Intrinsic::launder_invariant_group:
6598   case Intrinsic::strip_invariant_group:
6599     // Drop the intrinsic, but forward the value
6600     setValue(&I, getValue(I.getOperand(0)));
6601     return;
6602 
6603   case Intrinsic::assume:
6604   case Intrinsic::experimental_noalias_scope_decl:
6605   case Intrinsic::var_annotation:
6606   case Intrinsic::sideeffect:
6607     // Discard annotate attributes, noalias scope declarations, assumptions, and
6608     // artificial side-effects.
6609     return;
6610 
6611   case Intrinsic::codeview_annotation: {
6612     // Emit a label associated with this metadata.
6613     MachineFunction &MF = DAG.getMachineFunction();
6614     MCSymbol *Label =
6615         MF.getMMI().getContext().createTempSymbol("annotation", true);
6616     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6617     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6618     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6619     DAG.setRoot(Res);
6620     return;
6621   }
6622 
6623   case Intrinsic::init_trampoline: {
6624     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6625 
6626     SDValue Ops[6];
6627     Ops[0] = getRoot();
6628     Ops[1] = getValue(I.getArgOperand(0));
6629     Ops[2] = getValue(I.getArgOperand(1));
6630     Ops[3] = getValue(I.getArgOperand(2));
6631     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6632     Ops[5] = DAG.getSrcValue(F);
6633 
6634     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6635 
6636     DAG.setRoot(Res);
6637     return;
6638   }
6639   case Intrinsic::adjust_trampoline:
6640     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6641                              TLI.getPointerTy(DAG.getDataLayout()),
6642                              getValue(I.getArgOperand(0))));
6643     return;
6644   case Intrinsic::gcroot: {
6645     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6646            "only valid in functions with gc specified, enforced by Verifier");
6647     assert(GFI && "implied by previous");
6648     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6649     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6650 
6651     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6652     GFI->addStackRoot(FI->getIndex(), TypeMap);
6653     return;
6654   }
6655   case Intrinsic::gcread:
6656   case Intrinsic::gcwrite:
6657     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6658   case Intrinsic::flt_rounds:
6659     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6660     setValue(&I, Res);
6661     DAG.setRoot(Res.getValue(1));
6662     return;
6663 
6664   case Intrinsic::expect:
6665     // Just replace __builtin_expect(exp, c) with EXP.
6666     setValue(&I, getValue(I.getArgOperand(0)));
6667     return;
6668 
6669   case Intrinsic::ubsantrap:
6670   case Intrinsic::debugtrap:
6671   case Intrinsic::trap: {
6672     StringRef TrapFuncName =
6673         I.getAttributes()
6674             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6675             .getValueAsString();
6676     if (TrapFuncName.empty()) {
6677       switch (Intrinsic) {
6678       case Intrinsic::trap:
6679         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6680         break;
6681       case Intrinsic::debugtrap:
6682         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6683         break;
6684       case Intrinsic::ubsantrap:
6685         DAG.setRoot(DAG.getNode(
6686             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6687             DAG.getTargetConstant(
6688                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6689                 MVT::i32)));
6690         break;
6691       default: llvm_unreachable("unknown trap intrinsic");
6692       }
6693       return;
6694     }
6695     TargetLowering::ArgListTy Args;
6696     if (Intrinsic == Intrinsic::ubsantrap) {
6697       Args.push_back(TargetLoweringBase::ArgListEntry());
6698       Args[0].Val = I.getArgOperand(0);
6699       Args[0].Node = getValue(Args[0].Val);
6700       Args[0].Ty = Args[0].Val->getType();
6701     }
6702 
6703     TargetLowering::CallLoweringInfo CLI(DAG);
6704     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6705         CallingConv::C, I.getType(),
6706         DAG.getExternalSymbol(TrapFuncName.data(),
6707                               TLI.getPointerTy(DAG.getDataLayout())),
6708         std::move(Args));
6709 
6710     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6711     DAG.setRoot(Result.second);
6712     return;
6713   }
6714 
6715   case Intrinsic::uadd_with_overflow:
6716   case Intrinsic::sadd_with_overflow:
6717   case Intrinsic::usub_with_overflow:
6718   case Intrinsic::ssub_with_overflow:
6719   case Intrinsic::umul_with_overflow:
6720   case Intrinsic::smul_with_overflow: {
6721     ISD::NodeType Op;
6722     switch (Intrinsic) {
6723     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6724     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6725     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6726     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6727     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6728     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6729     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6730     }
6731     SDValue Op1 = getValue(I.getArgOperand(0));
6732     SDValue Op2 = getValue(I.getArgOperand(1));
6733 
6734     EVT ResultVT = Op1.getValueType();
6735     EVT OverflowVT = MVT::i1;
6736     if (ResultVT.isVector())
6737       OverflowVT = EVT::getVectorVT(
6738           *Context, OverflowVT, ResultVT.getVectorElementCount());
6739 
6740     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6741     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6742     return;
6743   }
6744   case Intrinsic::prefetch: {
6745     SDValue Ops[5];
6746     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6747     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6748     Ops[0] = DAG.getRoot();
6749     Ops[1] = getValue(I.getArgOperand(0));
6750     Ops[2] = getValue(I.getArgOperand(1));
6751     Ops[3] = getValue(I.getArgOperand(2));
6752     Ops[4] = getValue(I.getArgOperand(3));
6753     SDValue Result = DAG.getMemIntrinsicNode(
6754         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6755         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6756         /* align */ None, Flags);
6757 
6758     // Chain the prefetch in parallell with any pending loads, to stay out of
6759     // the way of later optimizations.
6760     PendingLoads.push_back(Result);
6761     Result = getRoot();
6762     DAG.setRoot(Result);
6763     return;
6764   }
6765   case Intrinsic::lifetime_start:
6766   case Intrinsic::lifetime_end: {
6767     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6768     // Stack coloring is not enabled in O0, discard region information.
6769     if (TM.getOptLevel() == CodeGenOpt::None)
6770       return;
6771 
6772     const int64_t ObjectSize =
6773         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6774     Value *const ObjectPtr = I.getArgOperand(1);
6775     SmallVector<const Value *, 4> Allocas;
6776     getUnderlyingObjects(ObjectPtr, Allocas);
6777 
6778     for (const Value *Alloca : Allocas) {
6779       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6780 
6781       // Could not find an Alloca.
6782       if (!LifetimeObject)
6783         continue;
6784 
6785       // First check that the Alloca is static, otherwise it won't have a
6786       // valid frame index.
6787       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6788       if (SI == FuncInfo.StaticAllocaMap.end())
6789         return;
6790 
6791       const int FrameIndex = SI->second;
6792       int64_t Offset;
6793       if (GetPointerBaseWithConstantOffset(
6794               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6795         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6796       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6797                                 Offset);
6798       DAG.setRoot(Res);
6799     }
6800     return;
6801   }
6802   case Intrinsic::pseudoprobe: {
6803     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6804     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6805     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6806     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6807     DAG.setRoot(Res);
6808     return;
6809   }
6810   case Intrinsic::invariant_start:
6811     // Discard region information.
6812     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6813     return;
6814   case Intrinsic::invariant_end:
6815     // Discard region information.
6816     return;
6817   case Intrinsic::clear_cache:
6818     /// FunctionName may be null.
6819     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6820       lowerCallToExternalSymbol(I, FunctionName);
6821     return;
6822   case Intrinsic::donothing:
6823   case Intrinsic::seh_try_begin:
6824   case Intrinsic::seh_scope_begin:
6825   case Intrinsic::seh_try_end:
6826   case Intrinsic::seh_scope_end:
6827     // ignore
6828     return;
6829   case Intrinsic::experimental_stackmap:
6830     visitStackmap(I);
6831     return;
6832   case Intrinsic::experimental_patchpoint_void:
6833   case Intrinsic::experimental_patchpoint_i64:
6834     visitPatchpoint(I);
6835     return;
6836   case Intrinsic::experimental_gc_statepoint:
6837     LowerStatepoint(cast<GCStatepointInst>(I));
6838     return;
6839   case Intrinsic::experimental_gc_result:
6840     visitGCResult(cast<GCResultInst>(I));
6841     return;
6842   case Intrinsic::experimental_gc_relocate:
6843     visitGCRelocate(cast<GCRelocateInst>(I));
6844     return;
6845   case Intrinsic::instrprof_increment:
6846     llvm_unreachable("instrprof failed to lower an increment");
6847   case Intrinsic::instrprof_value_profile:
6848     llvm_unreachable("instrprof failed to lower a value profiling call");
6849   case Intrinsic::localescape: {
6850     MachineFunction &MF = DAG.getMachineFunction();
6851     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6852 
6853     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6854     // is the same on all targets.
6855     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6856       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6857       if (isa<ConstantPointerNull>(Arg))
6858         continue; // Skip null pointers. They represent a hole in index space.
6859       AllocaInst *Slot = cast<AllocaInst>(Arg);
6860       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6861              "can only escape static allocas");
6862       int FI = FuncInfo.StaticAllocaMap[Slot];
6863       MCSymbol *FrameAllocSym =
6864           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6865               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6866       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6867               TII->get(TargetOpcode::LOCAL_ESCAPE))
6868           .addSym(FrameAllocSym)
6869           .addFrameIndex(FI);
6870     }
6871 
6872     return;
6873   }
6874 
6875   case Intrinsic::localrecover: {
6876     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6877     MachineFunction &MF = DAG.getMachineFunction();
6878 
6879     // Get the symbol that defines the frame offset.
6880     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6881     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6882     unsigned IdxVal =
6883         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6884     MCSymbol *FrameAllocSym =
6885         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6886             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6887 
6888     Value *FP = I.getArgOperand(1);
6889     SDValue FPVal = getValue(FP);
6890     EVT PtrVT = FPVal.getValueType();
6891 
6892     // Create a MCSymbol for the label to avoid any target lowering
6893     // that would make this PC relative.
6894     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6895     SDValue OffsetVal =
6896         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6897 
6898     // Add the offset to the FP.
6899     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6900     setValue(&I, Add);
6901 
6902     return;
6903   }
6904 
6905   case Intrinsic::eh_exceptionpointer:
6906   case Intrinsic::eh_exceptioncode: {
6907     // Get the exception pointer vreg, copy from it, and resize it to fit.
6908     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6909     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6910     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6911     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6912     SDValue N =
6913         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6914     if (Intrinsic == Intrinsic::eh_exceptioncode)
6915       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6916     setValue(&I, N);
6917     return;
6918   }
6919   case Intrinsic::xray_customevent: {
6920     // Here we want to make sure that the intrinsic behaves as if it has a
6921     // specific calling convention, and only for x86_64.
6922     // FIXME: Support other platforms later.
6923     const auto &Triple = DAG.getTarget().getTargetTriple();
6924     if (Triple.getArch() != Triple::x86_64)
6925       return;
6926 
6927     SDLoc DL = getCurSDLoc();
6928     SmallVector<SDValue, 8> Ops;
6929 
6930     // We want to say that we always want the arguments in registers.
6931     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6932     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6933     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6934     SDValue Chain = getRoot();
6935     Ops.push_back(LogEntryVal);
6936     Ops.push_back(StrSizeVal);
6937     Ops.push_back(Chain);
6938 
6939     // We need to enforce the calling convention for the callsite, so that
6940     // argument ordering is enforced correctly, and that register allocation can
6941     // see that some registers may be assumed clobbered and have to preserve
6942     // them across calls to the intrinsic.
6943     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6944                                            DL, NodeTys, Ops);
6945     SDValue patchableNode = SDValue(MN, 0);
6946     DAG.setRoot(patchableNode);
6947     setValue(&I, patchableNode);
6948     return;
6949   }
6950   case Intrinsic::xray_typedevent: {
6951     // Here we want to make sure that the intrinsic behaves as if it has a
6952     // specific calling convention, and only for x86_64.
6953     // FIXME: Support other platforms later.
6954     const auto &Triple = DAG.getTarget().getTargetTriple();
6955     if (Triple.getArch() != Triple::x86_64)
6956       return;
6957 
6958     SDLoc DL = getCurSDLoc();
6959     SmallVector<SDValue, 8> Ops;
6960 
6961     // We want to say that we always want the arguments in registers.
6962     // It's unclear to me how manipulating the selection DAG here forces callers
6963     // to provide arguments in registers instead of on the stack.
6964     SDValue LogTypeId = getValue(I.getArgOperand(0));
6965     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6966     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6967     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6968     SDValue Chain = getRoot();
6969     Ops.push_back(LogTypeId);
6970     Ops.push_back(LogEntryVal);
6971     Ops.push_back(StrSizeVal);
6972     Ops.push_back(Chain);
6973 
6974     // We need to enforce the calling convention for the callsite, so that
6975     // argument ordering is enforced correctly, and that register allocation can
6976     // see that some registers may be assumed clobbered and have to preserve
6977     // them across calls to the intrinsic.
6978     MachineSDNode *MN = DAG.getMachineNode(
6979         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6980     SDValue patchableNode = SDValue(MN, 0);
6981     DAG.setRoot(patchableNode);
6982     setValue(&I, patchableNode);
6983     return;
6984   }
6985   case Intrinsic::experimental_deoptimize:
6986     LowerDeoptimizeCall(&I);
6987     return;
6988   case Intrinsic::experimental_stepvector:
6989     visitStepVector(I);
6990     return;
6991   case Intrinsic::vector_reduce_fadd:
6992   case Intrinsic::vector_reduce_fmul:
6993   case Intrinsic::vector_reduce_add:
6994   case Intrinsic::vector_reduce_mul:
6995   case Intrinsic::vector_reduce_and:
6996   case Intrinsic::vector_reduce_or:
6997   case Intrinsic::vector_reduce_xor:
6998   case Intrinsic::vector_reduce_smax:
6999   case Intrinsic::vector_reduce_smin:
7000   case Intrinsic::vector_reduce_umax:
7001   case Intrinsic::vector_reduce_umin:
7002   case Intrinsic::vector_reduce_fmax:
7003   case Intrinsic::vector_reduce_fmin:
7004     visitVectorReduce(I, Intrinsic);
7005     return;
7006 
7007   case Intrinsic::icall_branch_funnel: {
7008     SmallVector<SDValue, 16> Ops;
7009     Ops.push_back(getValue(I.getArgOperand(0)));
7010 
7011     int64_t Offset;
7012     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7013         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7014     if (!Base)
7015       report_fatal_error(
7016           "llvm.icall.branch.funnel operand must be a GlobalValue");
7017     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
7018 
7019     struct BranchFunnelTarget {
7020       int64_t Offset;
7021       SDValue Target;
7022     };
7023     SmallVector<BranchFunnelTarget, 8> Targets;
7024 
7025     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
7026       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7027           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7028       if (ElemBase != Base)
7029         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7030                            "to the same GlobalValue");
7031 
7032       SDValue Val = getValue(I.getArgOperand(Op + 1));
7033       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7034       if (!GA)
7035         report_fatal_error(
7036             "llvm.icall.branch.funnel operand must be a GlobalValue");
7037       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7038                                      GA->getGlobal(), getCurSDLoc(),
7039                                      Val.getValueType(), GA->getOffset())});
7040     }
7041     llvm::sort(Targets,
7042                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7043                  return T1.Offset < T2.Offset;
7044                });
7045 
7046     for (auto &T : Targets) {
7047       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
7048       Ops.push_back(T.Target);
7049     }
7050 
7051     Ops.push_back(DAG.getRoot()); // Chain
7052     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
7053                                  getCurSDLoc(), MVT::Other, Ops),
7054               0);
7055     DAG.setRoot(N);
7056     setValue(&I, N);
7057     HasTailCall = true;
7058     return;
7059   }
7060 
7061   case Intrinsic::wasm_landingpad_index:
7062     // Information this intrinsic contained has been transferred to
7063     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7064     // delete it now.
7065     return;
7066 
7067   case Intrinsic::aarch64_settag:
7068   case Intrinsic::aarch64_settag_zero: {
7069     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7070     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7071     SDValue Val = TSI.EmitTargetCodeForSetTag(
7072         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
7073         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7074         ZeroMemory);
7075     DAG.setRoot(Val);
7076     setValue(&I, Val);
7077     return;
7078   }
7079   case Intrinsic::ptrmask: {
7080     SDValue Ptr = getValue(I.getOperand(0));
7081     SDValue Const = getValue(I.getOperand(1));
7082 
7083     EVT PtrVT = Ptr.getValueType();
7084     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
7085                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
7086     return;
7087   }
7088   case Intrinsic::get_active_lane_mask: {
7089     auto DL = getCurSDLoc();
7090     SDValue Index = getValue(I.getOperand(0));
7091     SDValue TripCount = getValue(I.getOperand(1));
7092     Type *ElementTy = I.getOperand(0)->getType();
7093     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7094     unsigned VecWidth = VT.getVectorNumElements();
7095 
7096     SmallVector<SDValue, 16> OpsTripCount;
7097     SmallVector<SDValue, 16> OpsIndex;
7098     SmallVector<SDValue, 16> OpsStepConstants;
7099     for (unsigned i = 0; i < VecWidth; i++) {
7100       OpsTripCount.push_back(TripCount);
7101       OpsIndex.push_back(Index);
7102       OpsStepConstants.push_back(
7103           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
7104     }
7105 
7106     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
7107 
7108     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
7109     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
7110     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
7111     SDValue VectorInduction = DAG.getNode(
7112        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
7113     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
7114     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
7115                                  VectorTripCount, ISD::CondCode::SETULT);
7116     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
7117                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
7118                              SetCC));
7119     return;
7120   }
7121   case Intrinsic::experimental_vector_insert: {
7122     auto DL = getCurSDLoc();
7123 
7124     SDValue Vec = getValue(I.getOperand(0));
7125     SDValue SubVec = getValue(I.getOperand(1));
7126     SDValue Index = getValue(I.getOperand(2));
7127 
7128     // The intrinsic's index type is i64, but the SDNode requires an index type
7129     // suitable for the target. Convert the index as required.
7130     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7131     if (Index.getValueType() != VectorIdxTy)
7132       Index = DAG.getVectorIdxConstant(
7133           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7134 
7135     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7136     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
7137                              Index));
7138     return;
7139   }
7140   case Intrinsic::experimental_vector_extract: {
7141     auto DL = getCurSDLoc();
7142 
7143     SDValue Vec = getValue(I.getOperand(0));
7144     SDValue Index = getValue(I.getOperand(1));
7145     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7146 
7147     // The intrinsic's index type is i64, but the SDNode requires an index type
7148     // suitable for the target. Convert the index as required.
7149     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7150     if (Index.getValueType() != VectorIdxTy)
7151       Index = DAG.getVectorIdxConstant(
7152           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7153 
7154     setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
7155     return;
7156   }
7157   case Intrinsic::experimental_vector_reverse:
7158     visitVectorReverse(I);
7159     return;
7160   case Intrinsic::experimental_vector_splice:
7161     visitVectorSplice(I);
7162     return;
7163   }
7164 }
7165 
7166 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7167     const ConstrainedFPIntrinsic &FPI) {
7168   SDLoc sdl = getCurSDLoc();
7169 
7170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7171   SmallVector<EVT, 4> ValueVTs;
7172   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7173   ValueVTs.push_back(MVT::Other); // Out chain
7174 
7175   // We do not need to serialize constrained FP intrinsics against
7176   // each other or against (nonvolatile) loads, so they can be
7177   // chained like loads.
7178   SDValue Chain = DAG.getRoot();
7179   SmallVector<SDValue, 4> Opers;
7180   Opers.push_back(Chain);
7181   if (FPI.isUnaryOp()) {
7182     Opers.push_back(getValue(FPI.getArgOperand(0)));
7183   } else if (FPI.isTernaryOp()) {
7184     Opers.push_back(getValue(FPI.getArgOperand(0)));
7185     Opers.push_back(getValue(FPI.getArgOperand(1)));
7186     Opers.push_back(getValue(FPI.getArgOperand(2)));
7187   } else {
7188     Opers.push_back(getValue(FPI.getArgOperand(0)));
7189     Opers.push_back(getValue(FPI.getArgOperand(1)));
7190   }
7191 
7192   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7193     assert(Result.getNode()->getNumValues() == 2);
7194 
7195     // Push node to the appropriate list so that future instructions can be
7196     // chained up correctly.
7197     SDValue OutChain = Result.getValue(1);
7198     switch (EB) {
7199     case fp::ExceptionBehavior::ebIgnore:
7200       // The only reason why ebIgnore nodes still need to be chained is that
7201       // they might depend on the current rounding mode, and therefore must
7202       // not be moved across instruction that may change that mode.
7203       LLVM_FALLTHROUGH;
7204     case fp::ExceptionBehavior::ebMayTrap:
7205       // These must not be moved across calls or instructions that may change
7206       // floating-point exception masks.
7207       PendingConstrainedFP.push_back(OutChain);
7208       break;
7209     case fp::ExceptionBehavior::ebStrict:
7210       // These must not be moved across calls or instructions that may change
7211       // floating-point exception masks or read floating-point exception flags.
7212       // In addition, they cannot be optimized out even if unused.
7213       PendingConstrainedFPStrict.push_back(OutChain);
7214       break;
7215     }
7216   };
7217 
7218   SDVTList VTs = DAG.getVTList(ValueVTs);
7219   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7220 
7221   SDNodeFlags Flags;
7222   if (EB == fp::ExceptionBehavior::ebIgnore)
7223     Flags.setNoFPExcept(true);
7224 
7225   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7226     Flags.copyFMF(*FPOp);
7227 
7228   unsigned Opcode;
7229   switch (FPI.getIntrinsicID()) {
7230   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7231 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7232   case Intrinsic::INTRINSIC:                                                   \
7233     Opcode = ISD::STRICT_##DAGN;                                               \
7234     break;
7235 #include "llvm/IR/ConstrainedOps.def"
7236   case Intrinsic::experimental_constrained_fmuladd: {
7237     Opcode = ISD::STRICT_FMA;
7238     // Break fmuladd into fmul and fadd.
7239     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7240         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7241                                         ValueVTs[0])) {
7242       Opers.pop_back();
7243       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7244       pushOutChain(Mul, EB);
7245       Opcode = ISD::STRICT_FADD;
7246       Opers.clear();
7247       Opers.push_back(Mul.getValue(1));
7248       Opers.push_back(Mul.getValue(0));
7249       Opers.push_back(getValue(FPI.getArgOperand(2)));
7250     }
7251     break;
7252   }
7253   }
7254 
7255   // A few strict DAG nodes carry additional operands that are not
7256   // set up by the default code above.
7257   switch (Opcode) {
7258   default: break;
7259   case ISD::STRICT_FP_ROUND:
7260     Opers.push_back(
7261         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7262     break;
7263   case ISD::STRICT_FSETCC:
7264   case ISD::STRICT_FSETCCS: {
7265     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7266     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7267     if (TM.Options.NoNaNsFPMath)
7268       Condition = getFCmpCodeWithoutNaN(Condition);
7269     Opers.push_back(DAG.getCondCode(Condition));
7270     break;
7271   }
7272   }
7273 
7274   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7275   pushOutChain(Result, EB);
7276 
7277   SDValue FPResult = Result.getValue(0);
7278   setValue(&FPI, FPResult);
7279 }
7280 
7281 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7282   Optional<unsigned> ResOPC;
7283   switch (VPIntrin.getIntrinsicID()) {
7284 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
7285 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
7286 #define END_REGISTER_VP_INTRINSIC(...) break;
7287 #include "llvm/IR/VPIntrinsics.def"
7288   }
7289 
7290   if (!ResOPC.hasValue())
7291     llvm_unreachable(
7292         "Inconsistency: no SDNode available for this VPIntrinsic!");
7293 
7294   return ResOPC.getValue();
7295 }
7296 
7297 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7298     const VPIntrinsic &VPIntrin) {
7299   SDLoc DL = getCurSDLoc();
7300   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7301 
7302   SmallVector<EVT, 4> ValueVTs;
7303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7304   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7305   SDVTList VTs = DAG.getVTList(ValueVTs);
7306 
7307   auto EVLParamPos =
7308       VPIntrinsic::GetVectorLengthParamPos(VPIntrin.getIntrinsicID());
7309 
7310   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7311   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7312          "Unexpected target EVL type");
7313 
7314   // Request operands.
7315   SmallVector<SDValue, 7> OpValues;
7316   for (int I = 0; I < (int)VPIntrin.getNumArgOperands(); ++I) {
7317     auto Op = getValue(VPIntrin.getArgOperand(I));
7318     if (I == EVLParamPos)
7319       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7320     OpValues.push_back(Op);
7321   }
7322 
7323   SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7324   setValue(&VPIntrin, Result);
7325 }
7326 
7327 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7328                                           const BasicBlock *EHPadBB,
7329                                           MCSymbol *&BeginLabel) {
7330   MachineFunction &MF = DAG.getMachineFunction();
7331   MachineModuleInfo &MMI = MF.getMMI();
7332 
7333   // Insert a label before the invoke call to mark the try range.  This can be
7334   // used to detect deletion of the invoke via the MachineModuleInfo.
7335   BeginLabel = MMI.getContext().createTempSymbol();
7336 
7337   // For SjLj, keep track of which landing pads go with which invokes
7338   // so as to maintain the ordering of pads in the LSDA.
7339   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7340   if (CallSiteIndex) {
7341     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7342     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7343 
7344     // Now that the call site is handled, stop tracking it.
7345     MMI.setCurrentCallSite(0);
7346   }
7347 
7348   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7349 }
7350 
7351 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7352                                         const BasicBlock *EHPadBB,
7353                                         MCSymbol *BeginLabel) {
7354   assert(BeginLabel && "BeginLabel should've been set");
7355 
7356   MachineFunction &MF = DAG.getMachineFunction();
7357   MachineModuleInfo &MMI = MF.getMMI();
7358 
7359   // Insert a label at the end of the invoke call to mark the try range.  This
7360   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7361   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7362   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7363 
7364   // Inform MachineModuleInfo of range.
7365   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7366   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7367   // actually use outlined funclets and their LSDA info style.
7368   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7369     assert(II && "II should've been set");
7370     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7371     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7372   } else if (!isScopedEHPersonality(Pers)) {
7373     assert(EHPadBB);
7374     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7375   }
7376 
7377   return Chain;
7378 }
7379 
7380 std::pair<SDValue, SDValue>
7381 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7382                                     const BasicBlock *EHPadBB) {
7383   MCSymbol *BeginLabel = nullptr;
7384 
7385   if (EHPadBB) {
7386     // Both PendingLoads and PendingExports must be flushed here;
7387     // this call might not return.
7388     (void)getRoot();
7389     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7390     CLI.setChain(getRoot());
7391   }
7392 
7393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7394   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7395 
7396   assert((CLI.IsTailCall || Result.second.getNode()) &&
7397          "Non-null chain expected with non-tail call!");
7398   assert((Result.second.getNode() || !Result.first.getNode()) &&
7399          "Null value expected with tail call!");
7400 
7401   if (!Result.second.getNode()) {
7402     // As a special case, a null chain means that a tail call has been emitted
7403     // and the DAG root is already updated.
7404     HasTailCall = true;
7405 
7406     // Since there's no actual continuation from this block, nothing can be
7407     // relying on us setting vregs for them.
7408     PendingExports.clear();
7409   } else {
7410     DAG.setRoot(Result.second);
7411   }
7412 
7413   if (EHPadBB) {
7414     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7415                            BeginLabel));
7416   }
7417 
7418   return Result;
7419 }
7420 
7421 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7422                                       bool isTailCall,
7423                                       bool isMustTailCall,
7424                                       const BasicBlock *EHPadBB) {
7425   auto &DL = DAG.getDataLayout();
7426   FunctionType *FTy = CB.getFunctionType();
7427   Type *RetTy = CB.getType();
7428 
7429   TargetLowering::ArgListTy Args;
7430   Args.reserve(CB.arg_size());
7431 
7432   const Value *SwiftErrorVal = nullptr;
7433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7434 
7435   if (isTailCall) {
7436     // Avoid emitting tail calls in functions with the disable-tail-calls
7437     // attribute.
7438     auto *Caller = CB.getParent()->getParent();
7439     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7440         "true" && !isMustTailCall)
7441       isTailCall = false;
7442 
7443     // We can't tail call inside a function with a swifterror argument. Lowering
7444     // does not support this yet. It would have to move into the swifterror
7445     // register before the call.
7446     if (TLI.supportSwiftError() &&
7447         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7448       isTailCall = false;
7449   }
7450 
7451   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7452     TargetLowering::ArgListEntry Entry;
7453     const Value *V = *I;
7454 
7455     // Skip empty types
7456     if (V->getType()->isEmptyTy())
7457       continue;
7458 
7459     SDValue ArgNode = getValue(V);
7460     Entry.Node = ArgNode; Entry.Ty = V->getType();
7461 
7462     Entry.setAttributes(&CB, I - CB.arg_begin());
7463 
7464     // Use swifterror virtual register as input to the call.
7465     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7466       SwiftErrorVal = V;
7467       // We find the virtual register for the actual swifterror argument.
7468       // Instead of using the Value, we use the virtual register instead.
7469       Entry.Node =
7470           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7471                           EVT(TLI.getPointerTy(DL)));
7472     }
7473 
7474     Args.push_back(Entry);
7475 
7476     // If we have an explicit sret argument that is an Instruction, (i.e., it
7477     // might point to function-local memory), we can't meaningfully tail-call.
7478     if (Entry.IsSRet && isa<Instruction>(V))
7479       isTailCall = false;
7480   }
7481 
7482   // If call site has a cfguardtarget operand bundle, create and add an
7483   // additional ArgListEntry.
7484   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7485     TargetLowering::ArgListEntry Entry;
7486     Value *V = Bundle->Inputs[0];
7487     SDValue ArgNode = getValue(V);
7488     Entry.Node = ArgNode;
7489     Entry.Ty = V->getType();
7490     Entry.IsCFGuardTarget = true;
7491     Args.push_back(Entry);
7492   }
7493 
7494   // Check if target-independent constraints permit a tail call here.
7495   // Target-dependent constraints are checked within TLI->LowerCallTo.
7496   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7497     isTailCall = false;
7498 
7499   // Disable tail calls if there is an swifterror argument. Targets have not
7500   // been updated to support tail calls.
7501   if (TLI.supportSwiftError() && SwiftErrorVal)
7502     isTailCall = false;
7503 
7504   TargetLowering::CallLoweringInfo CLI(DAG);
7505   CLI.setDebugLoc(getCurSDLoc())
7506       .setChain(getRoot())
7507       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7508       .setTailCall(isTailCall)
7509       .setConvergent(CB.isConvergent())
7510       .setIsPreallocated(
7511           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7512   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7513 
7514   if (Result.first.getNode()) {
7515     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7516     setValue(&CB, Result.first);
7517   }
7518 
7519   // The last element of CLI.InVals has the SDValue for swifterror return.
7520   // Here we copy it to a virtual register and update SwiftErrorMap for
7521   // book-keeping.
7522   if (SwiftErrorVal && TLI.supportSwiftError()) {
7523     // Get the last element of InVals.
7524     SDValue Src = CLI.InVals.back();
7525     Register VReg =
7526         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7527     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7528     DAG.setRoot(CopyNode);
7529   }
7530 }
7531 
7532 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7533                              SelectionDAGBuilder &Builder) {
7534   // Check to see if this load can be trivially constant folded, e.g. if the
7535   // input is from a string literal.
7536   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7537     // Cast pointer to the type we really want to load.
7538     Type *LoadTy =
7539         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7540     if (LoadVT.isVector())
7541       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7542 
7543     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7544                                          PointerType::getUnqual(LoadTy));
7545 
7546     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7547             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7548       return Builder.getValue(LoadCst);
7549   }
7550 
7551   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7552   // still constant memory, the input chain can be the entry node.
7553   SDValue Root;
7554   bool ConstantMemory = false;
7555 
7556   // Do not serialize (non-volatile) loads of constant memory with anything.
7557   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7558     Root = Builder.DAG.getEntryNode();
7559     ConstantMemory = true;
7560   } else {
7561     // Do not serialize non-volatile loads against each other.
7562     Root = Builder.DAG.getRoot();
7563   }
7564 
7565   SDValue Ptr = Builder.getValue(PtrVal);
7566   SDValue LoadVal =
7567       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7568                           MachinePointerInfo(PtrVal), Align(1));
7569 
7570   if (!ConstantMemory)
7571     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7572   return LoadVal;
7573 }
7574 
7575 /// Record the value for an instruction that produces an integer result,
7576 /// converting the type where necessary.
7577 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7578                                                   SDValue Value,
7579                                                   bool IsSigned) {
7580   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7581                                                     I.getType(), true);
7582   if (IsSigned)
7583     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7584   else
7585     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7586   setValue(&I, Value);
7587 }
7588 
7589 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7590 /// true and lower it. Otherwise return false, and it will be lowered like a
7591 /// normal call.
7592 /// The caller already checked that \p I calls the appropriate LibFunc with a
7593 /// correct prototype.
7594 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7595   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7596   const Value *Size = I.getArgOperand(2);
7597   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7598   if (CSize && CSize->getZExtValue() == 0) {
7599     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7600                                                           I.getType(), true);
7601     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7602     return true;
7603   }
7604 
7605   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7606   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7607       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7608       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7609   if (Res.first.getNode()) {
7610     processIntegerCallValue(I, Res.first, true);
7611     PendingLoads.push_back(Res.second);
7612     return true;
7613   }
7614 
7615   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7616   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7617   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7618     return false;
7619 
7620   // If the target has a fast compare for the given size, it will return a
7621   // preferred load type for that size. Require that the load VT is legal and
7622   // that the target supports unaligned loads of that type. Otherwise, return
7623   // INVALID.
7624   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7625     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7626     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7627     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7628       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7629       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7630       // TODO: Check alignment of src and dest ptrs.
7631       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7632       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7633       if (!TLI.isTypeLegal(LVT) ||
7634           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7635           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7636         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7637     }
7638 
7639     return LVT;
7640   };
7641 
7642   // This turns into unaligned loads. We only do this if the target natively
7643   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7644   // we'll only produce a small number of byte loads.
7645   MVT LoadVT;
7646   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7647   switch (NumBitsToCompare) {
7648   default:
7649     return false;
7650   case 16:
7651     LoadVT = MVT::i16;
7652     break;
7653   case 32:
7654     LoadVT = MVT::i32;
7655     break;
7656   case 64:
7657   case 128:
7658   case 256:
7659     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7660     break;
7661   }
7662 
7663   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7664     return false;
7665 
7666   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7667   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7668 
7669   // Bitcast to a wide integer type if the loads are vectors.
7670   if (LoadVT.isVector()) {
7671     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7672     LoadL = DAG.getBitcast(CmpVT, LoadL);
7673     LoadR = DAG.getBitcast(CmpVT, LoadR);
7674   }
7675 
7676   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7677   processIntegerCallValue(I, Cmp, false);
7678   return true;
7679 }
7680 
7681 /// See if we can lower a memchr call into an optimized form. If so, return
7682 /// true and lower it. Otherwise return false, and it will be lowered like a
7683 /// normal call.
7684 /// The caller already checked that \p I calls the appropriate LibFunc with a
7685 /// correct prototype.
7686 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7687   const Value *Src = I.getArgOperand(0);
7688   const Value *Char = I.getArgOperand(1);
7689   const Value *Length = I.getArgOperand(2);
7690 
7691   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7692   std::pair<SDValue, SDValue> Res =
7693     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7694                                 getValue(Src), getValue(Char), getValue(Length),
7695                                 MachinePointerInfo(Src));
7696   if (Res.first.getNode()) {
7697     setValue(&I, Res.first);
7698     PendingLoads.push_back(Res.second);
7699     return true;
7700   }
7701 
7702   return false;
7703 }
7704 
7705 /// See if we can lower a mempcpy call into an optimized form. If so, return
7706 /// true and lower it. Otherwise return false, and it will be lowered like a
7707 /// normal call.
7708 /// The caller already checked that \p I calls the appropriate LibFunc with a
7709 /// correct prototype.
7710 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7711   SDValue Dst = getValue(I.getArgOperand(0));
7712   SDValue Src = getValue(I.getArgOperand(1));
7713   SDValue Size = getValue(I.getArgOperand(2));
7714 
7715   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7716   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7717   // DAG::getMemcpy needs Alignment to be defined.
7718   Align Alignment = std::min(DstAlign, SrcAlign);
7719 
7720   bool isVol = false;
7721   SDLoc sdl = getCurSDLoc();
7722 
7723   // In the mempcpy context we need to pass in a false value for isTailCall
7724   // because the return pointer needs to be adjusted by the size of
7725   // the copied memory.
7726   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7727   AAMDNodes AAInfo;
7728   I.getAAMetadata(AAInfo);
7729   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7730                              /*isTailCall=*/false,
7731                              MachinePointerInfo(I.getArgOperand(0)),
7732                              MachinePointerInfo(I.getArgOperand(1)), AAInfo);
7733   assert(MC.getNode() != nullptr &&
7734          "** memcpy should not be lowered as TailCall in mempcpy context **");
7735   DAG.setRoot(MC);
7736 
7737   // Check if Size needs to be truncated or extended.
7738   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7739 
7740   // Adjust return pointer to point just past the last dst byte.
7741   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7742                                     Dst, Size);
7743   setValue(&I, DstPlusSize);
7744   return true;
7745 }
7746 
7747 /// See if we can lower a strcpy call into an optimized form.  If so, return
7748 /// true and lower it, otherwise return false and it will be lowered like a
7749 /// normal call.
7750 /// The caller already checked that \p I calls the appropriate LibFunc with a
7751 /// correct prototype.
7752 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7753   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7754 
7755   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7756   std::pair<SDValue, SDValue> Res =
7757     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7758                                 getValue(Arg0), getValue(Arg1),
7759                                 MachinePointerInfo(Arg0),
7760                                 MachinePointerInfo(Arg1), isStpcpy);
7761   if (Res.first.getNode()) {
7762     setValue(&I, Res.first);
7763     DAG.setRoot(Res.second);
7764     return true;
7765   }
7766 
7767   return false;
7768 }
7769 
7770 /// See if we can lower a strcmp call into an optimized form.  If so, return
7771 /// true and lower it, otherwise return false and it will be lowered like a
7772 /// normal call.
7773 /// The caller already checked that \p I calls the appropriate LibFunc with a
7774 /// correct prototype.
7775 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7776   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7777 
7778   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7779   std::pair<SDValue, SDValue> Res =
7780     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7781                                 getValue(Arg0), getValue(Arg1),
7782                                 MachinePointerInfo(Arg0),
7783                                 MachinePointerInfo(Arg1));
7784   if (Res.first.getNode()) {
7785     processIntegerCallValue(I, Res.first, true);
7786     PendingLoads.push_back(Res.second);
7787     return true;
7788   }
7789 
7790   return false;
7791 }
7792 
7793 /// See if we can lower a strlen call into an optimized form.  If so, return
7794 /// true and lower it, otherwise return false and it will be lowered like a
7795 /// normal call.
7796 /// The caller already checked that \p I calls the appropriate LibFunc with a
7797 /// correct prototype.
7798 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7799   const Value *Arg0 = I.getArgOperand(0);
7800 
7801   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7802   std::pair<SDValue, SDValue> Res =
7803     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7804                                 getValue(Arg0), MachinePointerInfo(Arg0));
7805   if (Res.first.getNode()) {
7806     processIntegerCallValue(I, Res.first, false);
7807     PendingLoads.push_back(Res.second);
7808     return true;
7809   }
7810 
7811   return false;
7812 }
7813 
7814 /// See if we can lower a strnlen call into an optimized form.  If so, return
7815 /// true and lower it, otherwise return false and it will be lowered like a
7816 /// normal call.
7817 /// The caller already checked that \p I calls the appropriate LibFunc with a
7818 /// correct prototype.
7819 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7820   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7821 
7822   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7823   std::pair<SDValue, SDValue> Res =
7824     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7825                                  getValue(Arg0), getValue(Arg1),
7826                                  MachinePointerInfo(Arg0));
7827   if (Res.first.getNode()) {
7828     processIntegerCallValue(I, Res.first, false);
7829     PendingLoads.push_back(Res.second);
7830     return true;
7831   }
7832 
7833   return false;
7834 }
7835 
7836 /// See if we can lower a unary floating-point operation into an SDNode with
7837 /// the specified Opcode.  If so, return true and lower it, otherwise return
7838 /// false and it will be lowered like a normal call.
7839 /// The caller already checked that \p I calls the appropriate LibFunc with a
7840 /// correct prototype.
7841 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7842                                               unsigned Opcode) {
7843   // We already checked this call's prototype; verify it doesn't modify errno.
7844   if (!I.onlyReadsMemory())
7845     return false;
7846 
7847   SDNodeFlags Flags;
7848   Flags.copyFMF(cast<FPMathOperator>(I));
7849 
7850   SDValue Tmp = getValue(I.getArgOperand(0));
7851   setValue(&I,
7852            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
7853   return true;
7854 }
7855 
7856 /// See if we can lower a binary floating-point operation into an SDNode with
7857 /// the specified Opcode. If so, return true and lower it. Otherwise return
7858 /// false, and it will be lowered like a normal call.
7859 /// The caller already checked that \p I calls the appropriate LibFunc with a
7860 /// correct prototype.
7861 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7862                                                unsigned Opcode) {
7863   // We already checked this call's prototype; verify it doesn't modify errno.
7864   if (!I.onlyReadsMemory())
7865     return false;
7866 
7867   SDNodeFlags Flags;
7868   Flags.copyFMF(cast<FPMathOperator>(I));
7869 
7870   SDValue Tmp0 = getValue(I.getArgOperand(0));
7871   SDValue Tmp1 = getValue(I.getArgOperand(1));
7872   EVT VT = Tmp0.getValueType();
7873   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
7874   return true;
7875 }
7876 
7877 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7878   // Handle inline assembly differently.
7879   if (I.isInlineAsm()) {
7880     visitInlineAsm(I);
7881     return;
7882   }
7883 
7884   if (Function *F = I.getCalledFunction()) {
7885     if (F->isDeclaration()) {
7886       // Is this an LLVM intrinsic or a target-specific intrinsic?
7887       unsigned IID = F->getIntrinsicID();
7888       if (!IID)
7889         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7890           IID = II->getIntrinsicID(F);
7891 
7892       if (IID) {
7893         visitIntrinsicCall(I, IID);
7894         return;
7895       }
7896     }
7897 
7898     // Check for well-known libc/libm calls.  If the function is internal, it
7899     // can't be a library call.  Don't do the check if marked as nobuiltin for
7900     // some reason or the call site requires strict floating point semantics.
7901     LibFunc Func;
7902     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7903         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7904         LibInfo->hasOptimizedCodeGen(Func)) {
7905       switch (Func) {
7906       default: break;
7907       case LibFunc_bcmp:
7908         if (visitMemCmpBCmpCall(I))
7909           return;
7910         break;
7911       case LibFunc_copysign:
7912       case LibFunc_copysignf:
7913       case LibFunc_copysignl:
7914         // We already checked this call's prototype; verify it doesn't modify
7915         // errno.
7916         if (I.onlyReadsMemory()) {
7917           SDValue LHS = getValue(I.getArgOperand(0));
7918           SDValue RHS = getValue(I.getArgOperand(1));
7919           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7920                                    LHS.getValueType(), LHS, RHS));
7921           return;
7922         }
7923         break;
7924       case LibFunc_fabs:
7925       case LibFunc_fabsf:
7926       case LibFunc_fabsl:
7927         if (visitUnaryFloatCall(I, ISD::FABS))
7928           return;
7929         break;
7930       case LibFunc_fmin:
7931       case LibFunc_fminf:
7932       case LibFunc_fminl:
7933         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7934           return;
7935         break;
7936       case LibFunc_fmax:
7937       case LibFunc_fmaxf:
7938       case LibFunc_fmaxl:
7939         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7940           return;
7941         break;
7942       case LibFunc_sin:
7943       case LibFunc_sinf:
7944       case LibFunc_sinl:
7945         if (visitUnaryFloatCall(I, ISD::FSIN))
7946           return;
7947         break;
7948       case LibFunc_cos:
7949       case LibFunc_cosf:
7950       case LibFunc_cosl:
7951         if (visitUnaryFloatCall(I, ISD::FCOS))
7952           return;
7953         break;
7954       case LibFunc_sqrt:
7955       case LibFunc_sqrtf:
7956       case LibFunc_sqrtl:
7957       case LibFunc_sqrt_finite:
7958       case LibFunc_sqrtf_finite:
7959       case LibFunc_sqrtl_finite:
7960         if (visitUnaryFloatCall(I, ISD::FSQRT))
7961           return;
7962         break;
7963       case LibFunc_floor:
7964       case LibFunc_floorf:
7965       case LibFunc_floorl:
7966         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7967           return;
7968         break;
7969       case LibFunc_nearbyint:
7970       case LibFunc_nearbyintf:
7971       case LibFunc_nearbyintl:
7972         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7973           return;
7974         break;
7975       case LibFunc_ceil:
7976       case LibFunc_ceilf:
7977       case LibFunc_ceill:
7978         if (visitUnaryFloatCall(I, ISD::FCEIL))
7979           return;
7980         break;
7981       case LibFunc_rint:
7982       case LibFunc_rintf:
7983       case LibFunc_rintl:
7984         if (visitUnaryFloatCall(I, ISD::FRINT))
7985           return;
7986         break;
7987       case LibFunc_round:
7988       case LibFunc_roundf:
7989       case LibFunc_roundl:
7990         if (visitUnaryFloatCall(I, ISD::FROUND))
7991           return;
7992         break;
7993       case LibFunc_trunc:
7994       case LibFunc_truncf:
7995       case LibFunc_truncl:
7996         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7997           return;
7998         break;
7999       case LibFunc_log2:
8000       case LibFunc_log2f:
8001       case LibFunc_log2l:
8002         if (visitUnaryFloatCall(I, ISD::FLOG2))
8003           return;
8004         break;
8005       case LibFunc_exp2:
8006       case LibFunc_exp2f:
8007       case LibFunc_exp2l:
8008         if (visitUnaryFloatCall(I, ISD::FEXP2))
8009           return;
8010         break;
8011       case LibFunc_memcmp:
8012         if (visitMemCmpBCmpCall(I))
8013           return;
8014         break;
8015       case LibFunc_mempcpy:
8016         if (visitMemPCpyCall(I))
8017           return;
8018         break;
8019       case LibFunc_memchr:
8020         if (visitMemChrCall(I))
8021           return;
8022         break;
8023       case LibFunc_strcpy:
8024         if (visitStrCpyCall(I, false))
8025           return;
8026         break;
8027       case LibFunc_stpcpy:
8028         if (visitStrCpyCall(I, true))
8029           return;
8030         break;
8031       case LibFunc_strcmp:
8032         if (visitStrCmpCall(I))
8033           return;
8034         break;
8035       case LibFunc_strlen:
8036         if (visitStrLenCall(I))
8037           return;
8038         break;
8039       case LibFunc_strnlen:
8040         if (visitStrNLenCall(I))
8041           return;
8042         break;
8043       }
8044     }
8045   }
8046 
8047   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8048   // have to do anything here to lower funclet bundles.
8049   // CFGuardTarget bundles are lowered in LowerCallTo.
8050   assert(!I.hasOperandBundlesOtherThan(
8051              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8052               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8053               LLVMContext::OB_clang_arc_attachedcall}) &&
8054          "Cannot lower calls with arbitrary operand bundles!");
8055 
8056   SDValue Callee = getValue(I.getCalledOperand());
8057 
8058   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8059     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8060   else
8061     // Check if we can potentially perform a tail call. More detailed checking
8062     // is be done within LowerCallTo, after more information about the call is
8063     // known.
8064     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8065 }
8066 
8067 namespace {
8068 
8069 /// AsmOperandInfo - This contains information for each constraint that we are
8070 /// lowering.
8071 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8072 public:
8073   /// CallOperand - If this is the result output operand or a clobber
8074   /// this is null, otherwise it is the incoming operand to the CallInst.
8075   /// This gets modified as the asm is processed.
8076   SDValue CallOperand;
8077 
8078   /// AssignedRegs - If this is a register or register class operand, this
8079   /// contains the set of register corresponding to the operand.
8080   RegsForValue AssignedRegs;
8081 
8082   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8083     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8084   }
8085 
8086   /// Whether or not this operand accesses memory
8087   bool hasMemory(const TargetLowering &TLI) const {
8088     // Indirect operand accesses access memory.
8089     if (isIndirect)
8090       return true;
8091 
8092     for (const auto &Code : Codes)
8093       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8094         return true;
8095 
8096     return false;
8097   }
8098 
8099   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8100   /// corresponds to.  If there is no Value* for this operand, it returns
8101   /// MVT::Other.
8102   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8103                            const DataLayout &DL) const {
8104     if (!CallOperandVal) return MVT::Other;
8105 
8106     if (isa<BasicBlock>(CallOperandVal))
8107       return TLI.getProgramPointerTy(DL);
8108 
8109     llvm::Type *OpTy = CallOperandVal->getType();
8110 
8111     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8112     // If this is an indirect operand, the operand is a pointer to the
8113     // accessed type.
8114     if (isIndirect) {
8115       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
8116       if (!PtrTy)
8117         report_fatal_error("Indirect operand for inline asm not a pointer!");
8118       OpTy = PtrTy->getElementType();
8119     }
8120 
8121     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8122     if (StructType *STy = dyn_cast<StructType>(OpTy))
8123       if (STy->getNumElements() == 1)
8124         OpTy = STy->getElementType(0);
8125 
8126     // If OpTy is not a single value, it may be a struct/union that we
8127     // can tile with integers.
8128     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8129       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8130       switch (BitSize) {
8131       default: break;
8132       case 1:
8133       case 8:
8134       case 16:
8135       case 32:
8136       case 64:
8137       case 128:
8138         OpTy = IntegerType::get(Context, BitSize);
8139         break;
8140       }
8141     }
8142 
8143     return TLI.getValueType(DL, OpTy, true);
8144   }
8145 };
8146 
8147 
8148 } // end anonymous namespace
8149 
8150 /// Make sure that the output operand \p OpInfo and its corresponding input
8151 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8152 /// out).
8153 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8154                                SDISelAsmOperandInfo &MatchingOpInfo,
8155                                SelectionDAG &DAG) {
8156   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8157     return;
8158 
8159   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8160   const auto &TLI = DAG.getTargetLoweringInfo();
8161 
8162   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8163       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8164                                        OpInfo.ConstraintVT);
8165   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8166       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8167                                        MatchingOpInfo.ConstraintVT);
8168   if ((OpInfo.ConstraintVT.isInteger() !=
8169        MatchingOpInfo.ConstraintVT.isInteger()) ||
8170       (MatchRC.second != InputRC.second)) {
8171     // FIXME: error out in a more elegant fashion
8172     report_fatal_error("Unsupported asm: input constraint"
8173                        " with a matching output constraint of"
8174                        " incompatible type!");
8175   }
8176   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8177 }
8178 
8179 /// Get a direct memory input to behave well as an indirect operand.
8180 /// This may introduce stores, hence the need for a \p Chain.
8181 /// \return The (possibly updated) chain.
8182 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8183                                         SDISelAsmOperandInfo &OpInfo,
8184                                         SelectionDAG &DAG) {
8185   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8186 
8187   // If we don't have an indirect input, put it in the constpool if we can,
8188   // otherwise spill it to a stack slot.
8189   // TODO: This isn't quite right. We need to handle these according to
8190   // the addressing mode that the constraint wants. Also, this may take
8191   // an additional register for the computation and we don't want that
8192   // either.
8193 
8194   // If the operand is a float, integer, or vector constant, spill to a
8195   // constant pool entry to get its address.
8196   const Value *OpVal = OpInfo.CallOperandVal;
8197   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8198       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8199     OpInfo.CallOperand = DAG.getConstantPool(
8200         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8201     return Chain;
8202   }
8203 
8204   // Otherwise, create a stack slot and emit a store to it before the asm.
8205   Type *Ty = OpVal->getType();
8206   auto &DL = DAG.getDataLayout();
8207   uint64_t TySize = DL.getTypeAllocSize(Ty);
8208   MachineFunction &MF = DAG.getMachineFunction();
8209   int SSFI = MF.getFrameInfo().CreateStackObject(
8210       TySize, DL.getPrefTypeAlign(Ty), false);
8211   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8212   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8213                             MachinePointerInfo::getFixedStack(MF, SSFI),
8214                             TLI.getMemValueType(DL, Ty));
8215   OpInfo.CallOperand = StackSlot;
8216 
8217   return Chain;
8218 }
8219 
8220 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8221 /// specified operand.  We prefer to assign virtual registers, to allow the
8222 /// register allocator to handle the assignment process.  However, if the asm
8223 /// uses features that we can't model on machineinstrs, we have SDISel do the
8224 /// allocation.  This produces generally horrible, but correct, code.
8225 ///
8226 ///   OpInfo describes the operand
8227 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8228 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8229                                  SDISelAsmOperandInfo &OpInfo,
8230                                  SDISelAsmOperandInfo &RefOpInfo) {
8231   LLVMContext &Context = *DAG.getContext();
8232   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8233 
8234   MachineFunction &MF = DAG.getMachineFunction();
8235   SmallVector<unsigned, 4> Regs;
8236   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8237 
8238   // No work to do for memory operations.
8239   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8240     return;
8241 
8242   // If this is a constraint for a single physreg, or a constraint for a
8243   // register class, find it.
8244   unsigned AssignedReg;
8245   const TargetRegisterClass *RC;
8246   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8247       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8248   // RC is unset only on failure. Return immediately.
8249   if (!RC)
8250     return;
8251 
8252   // Get the actual register value type.  This is important, because the user
8253   // may have asked for (e.g.) the AX register in i32 type.  We need to
8254   // remember that AX is actually i16 to get the right extension.
8255   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8256 
8257   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8258     // If this is an FP operand in an integer register (or visa versa), or more
8259     // generally if the operand value disagrees with the register class we plan
8260     // to stick it in, fix the operand type.
8261     //
8262     // If this is an input value, the bitcast to the new type is done now.
8263     // Bitcast for output value is done at the end of visitInlineAsm().
8264     if ((OpInfo.Type == InlineAsm::isOutput ||
8265          OpInfo.Type == InlineAsm::isInput) &&
8266         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8267       // Try to convert to the first EVT that the reg class contains.  If the
8268       // types are identical size, use a bitcast to convert (e.g. two differing
8269       // vector types).  Note: output bitcast is done at the end of
8270       // visitInlineAsm().
8271       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8272         // Exclude indirect inputs while they are unsupported because the code
8273         // to perform the load is missing and thus OpInfo.CallOperand still
8274         // refers to the input address rather than the pointed-to value.
8275         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8276           OpInfo.CallOperand =
8277               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8278         OpInfo.ConstraintVT = RegVT;
8279         // If the operand is an FP value and we want it in integer registers,
8280         // use the corresponding integer type. This turns an f64 value into
8281         // i64, which can be passed with two i32 values on a 32-bit machine.
8282       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8283         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8284         if (OpInfo.Type == InlineAsm::isInput)
8285           OpInfo.CallOperand =
8286               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8287         OpInfo.ConstraintVT = VT;
8288       }
8289     }
8290   }
8291 
8292   // No need to allocate a matching input constraint since the constraint it's
8293   // matching to has already been allocated.
8294   if (OpInfo.isMatchingInputConstraint())
8295     return;
8296 
8297   EVT ValueVT = OpInfo.ConstraintVT;
8298   if (OpInfo.ConstraintVT == MVT::Other)
8299     ValueVT = RegVT;
8300 
8301   // Initialize NumRegs.
8302   unsigned NumRegs = 1;
8303   if (OpInfo.ConstraintVT != MVT::Other)
8304     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8305 
8306   // If this is a constraint for a specific physical register, like {r17},
8307   // assign it now.
8308 
8309   // If this associated to a specific register, initialize iterator to correct
8310   // place. If virtual, make sure we have enough registers
8311 
8312   // Initialize iterator if necessary
8313   TargetRegisterClass::iterator I = RC->begin();
8314   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8315 
8316   // Do not check for single registers.
8317   if (AssignedReg) {
8318       for (; *I != AssignedReg; ++I)
8319         assert(I != RC->end() && "AssignedReg should be member of RC");
8320   }
8321 
8322   for (; NumRegs; --NumRegs, ++I) {
8323     assert(I != RC->end() && "Ran out of registers to allocate!");
8324     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8325     Regs.push_back(R);
8326   }
8327 
8328   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8329 }
8330 
8331 static unsigned
8332 findMatchingInlineAsmOperand(unsigned OperandNo,
8333                              const std::vector<SDValue> &AsmNodeOperands) {
8334   // Scan until we find the definition we already emitted of this operand.
8335   unsigned CurOp = InlineAsm::Op_FirstOperand;
8336   for (; OperandNo; --OperandNo) {
8337     // Advance to the next operand.
8338     unsigned OpFlag =
8339         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8340     assert((InlineAsm::isRegDefKind(OpFlag) ||
8341             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8342             InlineAsm::isMemKind(OpFlag)) &&
8343            "Skipped past definitions?");
8344     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8345   }
8346   return CurOp;
8347 }
8348 
8349 namespace {
8350 
8351 class ExtraFlags {
8352   unsigned Flags = 0;
8353 
8354 public:
8355   explicit ExtraFlags(const CallBase &Call) {
8356     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8357     if (IA->hasSideEffects())
8358       Flags |= InlineAsm::Extra_HasSideEffects;
8359     if (IA->isAlignStack())
8360       Flags |= InlineAsm::Extra_IsAlignStack;
8361     if (Call.isConvergent())
8362       Flags |= InlineAsm::Extra_IsConvergent;
8363     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8364   }
8365 
8366   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8367     // Ideally, we would only check against memory constraints.  However, the
8368     // meaning of an Other constraint can be target-specific and we can't easily
8369     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8370     // for Other constraints as well.
8371     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8372         OpInfo.ConstraintType == TargetLowering::C_Other) {
8373       if (OpInfo.Type == InlineAsm::isInput)
8374         Flags |= InlineAsm::Extra_MayLoad;
8375       else if (OpInfo.Type == InlineAsm::isOutput)
8376         Flags |= InlineAsm::Extra_MayStore;
8377       else if (OpInfo.Type == InlineAsm::isClobber)
8378         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8379     }
8380   }
8381 
8382   unsigned get() const { return Flags; }
8383 };
8384 
8385 } // end anonymous namespace
8386 
8387 /// visitInlineAsm - Handle a call to an InlineAsm object.
8388 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8389                                          const BasicBlock *EHPadBB) {
8390   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8391 
8392   /// ConstraintOperands - Information about all of the constraints.
8393   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8394 
8395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8396   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8397       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8398 
8399   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8400   // AsmDialect, MayLoad, MayStore).
8401   bool HasSideEffect = IA->hasSideEffects();
8402   ExtraFlags ExtraInfo(Call);
8403 
8404   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8405   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8406   unsigned NumMatchingOps = 0;
8407   for (auto &T : TargetConstraints) {
8408     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8409     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8410 
8411     // Compute the value type for each operand.
8412     if (OpInfo.Type == InlineAsm::isInput ||
8413         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8414       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8415 
8416       // Process the call argument. BasicBlocks are labels, currently appearing
8417       // only in asm's.
8418       if (isa<CallBrInst>(Call) &&
8419           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8420                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8421                         NumMatchingOps) &&
8422           (NumMatchingOps == 0 ||
8423            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8424                         NumMatchingOps))) {
8425         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8426         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8427         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8428       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8429         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8430       } else {
8431         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8432       }
8433 
8434       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8435                                            DAG.getDataLayout());
8436       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8437     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8438       // The return value of the call is this value.  As such, there is no
8439       // corresponding argument.
8440       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8441       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8442         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8443             DAG.getDataLayout(), STy->getElementType(ResNo));
8444       } else {
8445         assert(ResNo == 0 && "Asm only has one result!");
8446         OpInfo.ConstraintVT =
8447             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8448       }
8449       ++ResNo;
8450     } else {
8451       OpInfo.ConstraintVT = MVT::Other;
8452     }
8453 
8454     if (OpInfo.hasMatchingInput())
8455       ++NumMatchingOps;
8456 
8457     if (!HasSideEffect)
8458       HasSideEffect = OpInfo.hasMemory(TLI);
8459 
8460     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8461     // FIXME: Could we compute this on OpInfo rather than T?
8462 
8463     // Compute the constraint code and ConstraintType to use.
8464     TLI.ComputeConstraintToUse(T, SDValue());
8465 
8466     if (T.ConstraintType == TargetLowering::C_Immediate &&
8467         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8468       // We've delayed emitting a diagnostic like the "n" constraint because
8469       // inlining could cause an integer showing up.
8470       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8471                                           "' expects an integer constant "
8472                                           "expression");
8473 
8474     ExtraInfo.update(T);
8475   }
8476 
8477   // We won't need to flush pending loads if this asm doesn't touch
8478   // memory and is nonvolatile.
8479   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8480 
8481   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8482   if (EmitEHLabels) {
8483     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8484   }
8485   bool IsCallBr = isa<CallBrInst>(Call);
8486 
8487   if (IsCallBr || EmitEHLabels) {
8488     // If this is a callbr or invoke we need to flush pending exports since
8489     // inlineasm_br and invoke are terminators.
8490     // We need to do this before nodes are glued to the inlineasm_br node.
8491     Chain = getControlRoot();
8492   }
8493 
8494   MCSymbol *BeginLabel = nullptr;
8495   if (EmitEHLabels) {
8496     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8497   }
8498 
8499   // Second pass over the constraints: compute which constraint option to use.
8500   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8501     // If this is an output operand with a matching input operand, look up the
8502     // matching input. If their types mismatch, e.g. one is an integer, the
8503     // other is floating point, or their sizes are different, flag it as an
8504     // error.
8505     if (OpInfo.hasMatchingInput()) {
8506       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8507       patchMatchingInput(OpInfo, Input, DAG);
8508     }
8509 
8510     // Compute the constraint code and ConstraintType to use.
8511     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8512 
8513     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8514         OpInfo.Type == InlineAsm::isClobber)
8515       continue;
8516 
8517     // If this is a memory input, and if the operand is not indirect, do what we
8518     // need to provide an address for the memory input.
8519     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8520         !OpInfo.isIndirect) {
8521       assert((OpInfo.isMultipleAlternative ||
8522               (OpInfo.Type == InlineAsm::isInput)) &&
8523              "Can only indirectify direct input operands!");
8524 
8525       // Memory operands really want the address of the value.
8526       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8527 
8528       // There is no longer a Value* corresponding to this operand.
8529       OpInfo.CallOperandVal = nullptr;
8530 
8531       // It is now an indirect operand.
8532       OpInfo.isIndirect = true;
8533     }
8534 
8535   }
8536 
8537   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8538   std::vector<SDValue> AsmNodeOperands;
8539   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8540   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8541       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8542 
8543   // If we have a !srcloc metadata node associated with it, we want to attach
8544   // this to the ultimately generated inline asm machineinstr.  To do this, we
8545   // pass in the third operand as this (potentially null) inline asm MDNode.
8546   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8547   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8548 
8549   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8550   // bits as operand 3.
8551   AsmNodeOperands.push_back(DAG.getTargetConstant(
8552       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8553 
8554   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8555   // this, assign virtual and physical registers for inputs and otput.
8556   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8557     // Assign Registers.
8558     SDISelAsmOperandInfo &RefOpInfo =
8559         OpInfo.isMatchingInputConstraint()
8560             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8561             : OpInfo;
8562     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8563 
8564     auto DetectWriteToReservedRegister = [&]() {
8565       const MachineFunction &MF = DAG.getMachineFunction();
8566       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8567       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8568         if (Register::isPhysicalRegister(Reg) &&
8569             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8570           const char *RegName = TRI.getName(Reg);
8571           emitInlineAsmError(Call, "write to reserved register '" +
8572                                        Twine(RegName) + "'");
8573           return true;
8574         }
8575       }
8576       return false;
8577     };
8578 
8579     switch (OpInfo.Type) {
8580     case InlineAsm::isOutput:
8581       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8582         unsigned ConstraintID =
8583             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8584         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8585                "Failed to convert memory constraint code to constraint id.");
8586 
8587         // Add information to the INLINEASM node to know about this output.
8588         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8589         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8590         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8591                                                         MVT::i32));
8592         AsmNodeOperands.push_back(OpInfo.CallOperand);
8593       } else {
8594         // Otherwise, this outputs to a register (directly for C_Register /
8595         // C_RegisterClass, and a target-defined fashion for
8596         // C_Immediate/C_Other). Find a register that we can use.
8597         if (OpInfo.AssignedRegs.Regs.empty()) {
8598           emitInlineAsmError(
8599               Call, "couldn't allocate output register for constraint '" +
8600                         Twine(OpInfo.ConstraintCode) + "'");
8601           return;
8602         }
8603 
8604         if (DetectWriteToReservedRegister())
8605           return;
8606 
8607         // Add information to the INLINEASM node to know that this register is
8608         // set.
8609         OpInfo.AssignedRegs.AddInlineAsmOperands(
8610             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8611                                   : InlineAsm::Kind_RegDef,
8612             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8613       }
8614       break;
8615 
8616     case InlineAsm::isInput: {
8617       SDValue InOperandVal = OpInfo.CallOperand;
8618 
8619       if (OpInfo.isMatchingInputConstraint()) {
8620         // If this is required to match an output register we have already set,
8621         // just use its register.
8622         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8623                                                   AsmNodeOperands);
8624         unsigned OpFlag =
8625           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8626         if (InlineAsm::isRegDefKind(OpFlag) ||
8627             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8628           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8629           if (OpInfo.isIndirect) {
8630             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8631             emitInlineAsmError(Call, "inline asm not supported yet: "
8632                                      "don't know how to handle tied "
8633                                      "indirect register inputs");
8634             return;
8635           }
8636 
8637           SmallVector<unsigned, 4> Regs;
8638           MachineFunction &MF = DAG.getMachineFunction();
8639           MachineRegisterInfo &MRI = MF.getRegInfo();
8640           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8641           RegisterSDNode *R = dyn_cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8642           Register TiedReg = R->getReg();
8643           MVT RegVT = R->getSimpleValueType(0);
8644           const TargetRegisterClass *RC = TiedReg.isVirtual() ?
8645             MRI.getRegClass(TiedReg) : TRI.getMinimalPhysRegClass(TiedReg);
8646           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8647           for (unsigned i = 0; i != NumRegs; ++i)
8648             Regs.push_back(MRI.createVirtualRegister(RC));
8649 
8650           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8651 
8652           SDLoc dl = getCurSDLoc();
8653           // Use the produced MatchedRegs object to
8654           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8655           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8656                                            true, OpInfo.getMatchedOperand(), dl,
8657                                            DAG, AsmNodeOperands);
8658           break;
8659         }
8660 
8661         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8662         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8663                "Unexpected number of operands");
8664         // Add information to the INLINEASM node to know about this input.
8665         // See InlineAsm.h isUseOperandTiedToDef.
8666         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8667         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8668                                                     OpInfo.getMatchedOperand());
8669         AsmNodeOperands.push_back(DAG.getTargetConstant(
8670             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8671         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8672         break;
8673       }
8674 
8675       // Treat indirect 'X' constraint as memory.
8676       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8677           OpInfo.isIndirect)
8678         OpInfo.ConstraintType = TargetLowering::C_Memory;
8679 
8680       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8681           OpInfo.ConstraintType == TargetLowering::C_Other) {
8682         std::vector<SDValue> Ops;
8683         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8684                                           Ops, DAG);
8685         if (Ops.empty()) {
8686           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8687             if (isa<ConstantSDNode>(InOperandVal)) {
8688               emitInlineAsmError(Call, "value out of range for constraint '" +
8689                                            Twine(OpInfo.ConstraintCode) + "'");
8690               return;
8691             }
8692 
8693           emitInlineAsmError(Call,
8694                              "invalid operand for inline asm constraint '" +
8695                                  Twine(OpInfo.ConstraintCode) + "'");
8696           return;
8697         }
8698 
8699         // Add information to the INLINEASM node to know about this input.
8700         unsigned ResOpType =
8701           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8702         AsmNodeOperands.push_back(DAG.getTargetConstant(
8703             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8704         llvm::append_range(AsmNodeOperands, Ops);
8705         break;
8706       }
8707 
8708       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8709         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8710         assert(InOperandVal.getValueType() ==
8711                    TLI.getPointerTy(DAG.getDataLayout()) &&
8712                "Memory operands expect pointer values");
8713 
8714         unsigned ConstraintID =
8715             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8716         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8717                "Failed to convert memory constraint code to constraint id.");
8718 
8719         // Add information to the INLINEASM node to know about this input.
8720         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8721         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8722         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8723                                                         getCurSDLoc(),
8724                                                         MVT::i32));
8725         AsmNodeOperands.push_back(InOperandVal);
8726         break;
8727       }
8728 
8729       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8730               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8731              "Unknown constraint type!");
8732 
8733       // TODO: Support this.
8734       if (OpInfo.isIndirect) {
8735         emitInlineAsmError(
8736             Call, "Don't know how to handle indirect register inputs yet "
8737                   "for constraint '" +
8738                       Twine(OpInfo.ConstraintCode) + "'");
8739         return;
8740       }
8741 
8742       // Copy the input into the appropriate registers.
8743       if (OpInfo.AssignedRegs.Regs.empty()) {
8744         emitInlineAsmError(Call,
8745                            "couldn't allocate input reg for constraint '" +
8746                                Twine(OpInfo.ConstraintCode) + "'");
8747         return;
8748       }
8749 
8750       if (DetectWriteToReservedRegister())
8751         return;
8752 
8753       SDLoc dl = getCurSDLoc();
8754 
8755       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8756                                         &Call);
8757 
8758       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8759                                                dl, DAG, AsmNodeOperands);
8760       break;
8761     }
8762     case InlineAsm::isClobber:
8763       // Add the clobbered value to the operand list, so that the register
8764       // allocator is aware that the physreg got clobbered.
8765       if (!OpInfo.AssignedRegs.Regs.empty())
8766         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8767                                                  false, 0, getCurSDLoc(), DAG,
8768                                                  AsmNodeOperands);
8769       break;
8770     }
8771   }
8772 
8773   // Finish up input operands.  Set the input chain and add the flag last.
8774   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8775   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8776 
8777   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8778   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8779                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8780   Flag = Chain.getValue(1);
8781 
8782   // Do additional work to generate outputs.
8783 
8784   SmallVector<EVT, 1> ResultVTs;
8785   SmallVector<SDValue, 1> ResultValues;
8786   SmallVector<SDValue, 8> OutChains;
8787 
8788   llvm::Type *CallResultType = Call.getType();
8789   ArrayRef<Type *> ResultTypes;
8790   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8791     ResultTypes = StructResult->elements();
8792   else if (!CallResultType->isVoidTy())
8793     ResultTypes = makeArrayRef(CallResultType);
8794 
8795   auto CurResultType = ResultTypes.begin();
8796   auto handleRegAssign = [&](SDValue V) {
8797     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8798     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8799     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8800     ++CurResultType;
8801     // If the type of the inline asm call site return value is different but has
8802     // same size as the type of the asm output bitcast it.  One example of this
8803     // is for vectors with different width / number of elements.  This can
8804     // happen for register classes that can contain multiple different value
8805     // types.  The preg or vreg allocated may not have the same VT as was
8806     // expected.
8807     //
8808     // This can also happen for a return value that disagrees with the register
8809     // class it is put in, eg. a double in a general-purpose register on a
8810     // 32-bit machine.
8811     if (ResultVT != V.getValueType() &&
8812         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8813       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8814     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8815              V.getValueType().isInteger()) {
8816       // If a result value was tied to an input value, the computed result
8817       // may have a wider width than the expected result.  Extract the
8818       // relevant portion.
8819       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8820     }
8821     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8822     ResultVTs.push_back(ResultVT);
8823     ResultValues.push_back(V);
8824   };
8825 
8826   // Deal with output operands.
8827   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8828     if (OpInfo.Type == InlineAsm::isOutput) {
8829       SDValue Val;
8830       // Skip trivial output operands.
8831       if (OpInfo.AssignedRegs.Regs.empty())
8832         continue;
8833 
8834       switch (OpInfo.ConstraintType) {
8835       case TargetLowering::C_Register:
8836       case TargetLowering::C_RegisterClass:
8837         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8838                                                   Chain, &Flag, &Call);
8839         break;
8840       case TargetLowering::C_Immediate:
8841       case TargetLowering::C_Other:
8842         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8843                                               OpInfo, DAG);
8844         break;
8845       case TargetLowering::C_Memory:
8846         break; // Already handled.
8847       case TargetLowering::C_Unknown:
8848         assert(false && "Unexpected unknown constraint");
8849       }
8850 
8851       // Indirect output manifest as stores. Record output chains.
8852       if (OpInfo.isIndirect) {
8853         const Value *Ptr = OpInfo.CallOperandVal;
8854         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8855         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8856                                      MachinePointerInfo(Ptr));
8857         OutChains.push_back(Store);
8858       } else {
8859         // generate CopyFromRegs to associated registers.
8860         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8861         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8862           for (const SDValue &V : Val->op_values())
8863             handleRegAssign(V);
8864         } else
8865           handleRegAssign(Val);
8866       }
8867     }
8868   }
8869 
8870   // Set results.
8871   if (!ResultValues.empty()) {
8872     assert(CurResultType == ResultTypes.end() &&
8873            "Mismatch in number of ResultTypes");
8874     assert(ResultValues.size() == ResultTypes.size() &&
8875            "Mismatch in number of output operands in asm result");
8876 
8877     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8878                             DAG.getVTList(ResultVTs), ResultValues);
8879     setValue(&Call, V);
8880   }
8881 
8882   // Collect store chains.
8883   if (!OutChains.empty())
8884     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8885 
8886   if (EmitEHLabels) {
8887     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
8888   }
8889 
8890   // Only Update Root if inline assembly has a memory effect.
8891   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
8892       EmitEHLabels)
8893     DAG.setRoot(Chain);
8894 }
8895 
8896 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8897                                              const Twine &Message) {
8898   LLVMContext &Ctx = *DAG.getContext();
8899   Ctx.emitError(&Call, Message);
8900 
8901   // Make sure we leave the DAG in a valid state
8902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8903   SmallVector<EVT, 1> ValueVTs;
8904   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8905 
8906   if (ValueVTs.empty())
8907     return;
8908 
8909   SmallVector<SDValue, 1> Ops;
8910   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8911     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8912 
8913   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8914 }
8915 
8916 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8917   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8918                           MVT::Other, getRoot(),
8919                           getValue(I.getArgOperand(0)),
8920                           DAG.getSrcValue(I.getArgOperand(0))));
8921 }
8922 
8923 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8924   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8925   const DataLayout &DL = DAG.getDataLayout();
8926   SDValue V = DAG.getVAArg(
8927       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8928       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8929       DL.getABITypeAlign(I.getType()).value());
8930   DAG.setRoot(V.getValue(1));
8931 
8932   if (I.getType()->isPointerTy())
8933     V = DAG.getPtrExtOrTrunc(
8934         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8935   setValue(&I, V);
8936 }
8937 
8938 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8939   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8940                           MVT::Other, getRoot(),
8941                           getValue(I.getArgOperand(0)),
8942                           DAG.getSrcValue(I.getArgOperand(0))));
8943 }
8944 
8945 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8946   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8947                           MVT::Other, getRoot(),
8948                           getValue(I.getArgOperand(0)),
8949                           getValue(I.getArgOperand(1)),
8950                           DAG.getSrcValue(I.getArgOperand(0)),
8951                           DAG.getSrcValue(I.getArgOperand(1))));
8952 }
8953 
8954 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8955                                                     const Instruction &I,
8956                                                     SDValue Op) {
8957   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8958   if (!Range)
8959     return Op;
8960 
8961   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8962   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8963     return Op;
8964 
8965   APInt Lo = CR.getUnsignedMin();
8966   if (!Lo.isMinValue())
8967     return Op;
8968 
8969   APInt Hi = CR.getUnsignedMax();
8970   unsigned Bits = std::max(Hi.getActiveBits(),
8971                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8972 
8973   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8974 
8975   SDLoc SL = getCurSDLoc();
8976 
8977   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8978                              DAG.getValueType(SmallVT));
8979   unsigned NumVals = Op.getNode()->getNumValues();
8980   if (NumVals == 1)
8981     return ZExt;
8982 
8983   SmallVector<SDValue, 4> Ops;
8984 
8985   Ops.push_back(ZExt);
8986   for (unsigned I = 1; I != NumVals; ++I)
8987     Ops.push_back(Op.getValue(I));
8988 
8989   return DAG.getMergeValues(Ops, SL);
8990 }
8991 
8992 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8993 /// the call being lowered.
8994 ///
8995 /// This is a helper for lowering intrinsics that follow a target calling
8996 /// convention or require stack pointer adjustment. Only a subset of the
8997 /// intrinsic's operands need to participate in the calling convention.
8998 void SelectionDAGBuilder::populateCallLoweringInfo(
8999     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9000     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9001     bool IsPatchPoint) {
9002   TargetLowering::ArgListTy Args;
9003   Args.reserve(NumArgs);
9004 
9005   // Populate the argument list.
9006   // Attributes for args start at offset 1, after the return attribute.
9007   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9008        ArgI != ArgE; ++ArgI) {
9009     const Value *V = Call->getOperand(ArgI);
9010 
9011     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9012 
9013     TargetLowering::ArgListEntry Entry;
9014     Entry.Node = getValue(V);
9015     Entry.Ty = V->getType();
9016     Entry.setAttributes(Call, ArgI);
9017     Args.push_back(Entry);
9018   }
9019 
9020   CLI.setDebugLoc(getCurSDLoc())
9021       .setChain(getRoot())
9022       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9023       .setDiscardResult(Call->use_empty())
9024       .setIsPatchPoint(IsPatchPoint)
9025       .setIsPreallocated(
9026           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9027 }
9028 
9029 /// Add a stack map intrinsic call's live variable operands to a stackmap
9030 /// or patchpoint target node's operand list.
9031 ///
9032 /// Constants are converted to TargetConstants purely as an optimization to
9033 /// avoid constant materialization and register allocation.
9034 ///
9035 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9036 /// generate addess computation nodes, and so FinalizeISel can convert the
9037 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9038 /// address materialization and register allocation, but may also be required
9039 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9040 /// alloca in the entry block, then the runtime may assume that the alloca's
9041 /// StackMap location can be read immediately after compilation and that the
9042 /// location is valid at any point during execution (this is similar to the
9043 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9044 /// only available in a register, then the runtime would need to trap when
9045 /// execution reaches the StackMap in order to read the alloca's location.
9046 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9047                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9048                                 SelectionDAGBuilder &Builder) {
9049   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
9050     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
9051     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
9052       Ops.push_back(
9053         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
9054       Ops.push_back(
9055         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
9056     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
9057       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
9058       Ops.push_back(Builder.DAG.getTargetFrameIndex(
9059           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
9060     } else
9061       Ops.push_back(OpVal);
9062   }
9063 }
9064 
9065 /// Lower llvm.experimental.stackmap directly to its target opcode.
9066 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9067   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
9068   //                                  [live variables...])
9069 
9070   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9071 
9072   SDValue Chain, InFlag, Callee, NullPtr;
9073   SmallVector<SDValue, 32> Ops;
9074 
9075   SDLoc DL = getCurSDLoc();
9076   Callee = getValue(CI.getCalledOperand());
9077   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9078 
9079   // The stackmap intrinsic only records the live variables (the arguments
9080   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9081   // intrinsic, this won't be lowered to a function call. This means we don't
9082   // have to worry about calling conventions and target specific lowering code.
9083   // Instead we perform the call lowering right here.
9084   //
9085   // chain, flag = CALLSEQ_START(chain, 0, 0)
9086   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9087   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9088   //
9089   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9090   InFlag = Chain.getValue(1);
9091 
9092   // Add the <id> and <numBytes> constants.
9093   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9094   Ops.push_back(DAG.getTargetConstant(
9095                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9096   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9097   Ops.push_back(DAG.getTargetConstant(
9098                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9099                   MVT::i32));
9100 
9101   // Push live variables for the stack map.
9102   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9103 
9104   // We are not pushing any register mask info here on the operands list,
9105   // because the stackmap doesn't clobber anything.
9106 
9107   // Push the chain and the glue flag.
9108   Ops.push_back(Chain);
9109   Ops.push_back(InFlag);
9110 
9111   // Create the STACKMAP node.
9112   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9113   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9114   Chain = SDValue(SM, 0);
9115   InFlag = Chain.getValue(1);
9116 
9117   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9118 
9119   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9120 
9121   // Set the root to the target-lowered call chain.
9122   DAG.setRoot(Chain);
9123 
9124   // Inform the Frame Information that we have a stackmap in this function.
9125   FuncInfo.MF->getFrameInfo().setHasStackMap();
9126 }
9127 
9128 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9129 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9130                                           const BasicBlock *EHPadBB) {
9131   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9132   //                                                 i32 <numBytes>,
9133   //                                                 i8* <target>,
9134   //                                                 i32 <numArgs>,
9135   //                                                 [Args...],
9136   //                                                 [live variables...])
9137 
9138   CallingConv::ID CC = CB.getCallingConv();
9139   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9140   bool HasDef = !CB.getType()->isVoidTy();
9141   SDLoc dl = getCurSDLoc();
9142   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9143 
9144   // Handle immediate and symbolic callees.
9145   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9146     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9147                                    /*isTarget=*/true);
9148   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9149     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9150                                          SDLoc(SymbolicCallee),
9151                                          SymbolicCallee->getValueType(0));
9152 
9153   // Get the real number of arguments participating in the call <numArgs>
9154   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9155   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9156 
9157   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9158   // Intrinsics include all meta-operands up to but not including CC.
9159   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9160   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9161          "Not enough arguments provided to the patchpoint intrinsic");
9162 
9163   // For AnyRegCC the arguments are lowered later on manually.
9164   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9165   Type *ReturnTy =
9166       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9167 
9168   TargetLowering::CallLoweringInfo CLI(DAG);
9169   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9170                            ReturnTy, true);
9171   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9172 
9173   SDNode *CallEnd = Result.second.getNode();
9174   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9175     CallEnd = CallEnd->getOperand(0).getNode();
9176 
9177   /// Get a call instruction from the call sequence chain.
9178   /// Tail calls are not allowed.
9179   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9180          "Expected a callseq node.");
9181   SDNode *Call = CallEnd->getOperand(0).getNode();
9182   bool HasGlue = Call->getGluedNode();
9183 
9184   // Replace the target specific call node with the patchable intrinsic.
9185   SmallVector<SDValue, 8> Ops;
9186 
9187   // Add the <id> and <numBytes> constants.
9188   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9189   Ops.push_back(DAG.getTargetConstant(
9190                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9191   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9192   Ops.push_back(DAG.getTargetConstant(
9193                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9194                   MVT::i32));
9195 
9196   // Add the callee.
9197   Ops.push_back(Callee);
9198 
9199   // Adjust <numArgs> to account for any arguments that have been passed on the
9200   // stack instead.
9201   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9202   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9203   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9204   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9205 
9206   // Add the calling convention
9207   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9208 
9209   // Add the arguments we omitted previously. The register allocator should
9210   // place these in any free register.
9211   if (IsAnyRegCC)
9212     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9213       Ops.push_back(getValue(CB.getArgOperand(i)));
9214 
9215   // Push the arguments from the call instruction up to the register mask.
9216   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9217   Ops.append(Call->op_begin() + 2, e);
9218 
9219   // Push live variables for the stack map.
9220   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9221 
9222   // Push the register mask info.
9223   if (HasGlue)
9224     Ops.push_back(*(Call->op_end()-2));
9225   else
9226     Ops.push_back(*(Call->op_end()-1));
9227 
9228   // Push the chain (this is originally the first operand of the call, but
9229   // becomes now the last or second to last operand).
9230   Ops.push_back(*(Call->op_begin()));
9231 
9232   // Push the glue flag (last operand).
9233   if (HasGlue)
9234     Ops.push_back(*(Call->op_end()-1));
9235 
9236   SDVTList NodeTys;
9237   if (IsAnyRegCC && HasDef) {
9238     // Create the return types based on the intrinsic definition
9239     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9240     SmallVector<EVT, 3> ValueVTs;
9241     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9242     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9243 
9244     // There is always a chain and a glue type at the end
9245     ValueVTs.push_back(MVT::Other);
9246     ValueVTs.push_back(MVT::Glue);
9247     NodeTys = DAG.getVTList(ValueVTs);
9248   } else
9249     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9250 
9251   // Replace the target specific call node with a PATCHPOINT node.
9252   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9253                                          dl, NodeTys, Ops);
9254 
9255   // Update the NodeMap.
9256   if (HasDef) {
9257     if (IsAnyRegCC)
9258       setValue(&CB, SDValue(MN, 0));
9259     else
9260       setValue(&CB, Result.first);
9261   }
9262 
9263   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9264   // call sequence. Furthermore the location of the chain and glue can change
9265   // when the AnyReg calling convention is used and the intrinsic returns a
9266   // value.
9267   if (IsAnyRegCC && HasDef) {
9268     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9269     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9270     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9271   } else
9272     DAG.ReplaceAllUsesWith(Call, MN);
9273   DAG.DeleteNode(Call);
9274 
9275   // Inform the Frame Information that we have a patchpoint in this function.
9276   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9277 }
9278 
9279 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9280                                             unsigned Intrinsic) {
9281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9282   SDValue Op1 = getValue(I.getArgOperand(0));
9283   SDValue Op2;
9284   if (I.getNumArgOperands() > 1)
9285     Op2 = getValue(I.getArgOperand(1));
9286   SDLoc dl = getCurSDLoc();
9287   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9288   SDValue Res;
9289   SDNodeFlags SDFlags;
9290   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9291     SDFlags.copyFMF(*FPMO);
9292 
9293   switch (Intrinsic) {
9294   case Intrinsic::vector_reduce_fadd:
9295     if (SDFlags.hasAllowReassociation())
9296       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9297                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9298                         SDFlags);
9299     else
9300       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9301     break;
9302   case Intrinsic::vector_reduce_fmul:
9303     if (SDFlags.hasAllowReassociation())
9304       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9305                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9306                         SDFlags);
9307     else
9308       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9309     break;
9310   case Intrinsic::vector_reduce_add:
9311     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9312     break;
9313   case Intrinsic::vector_reduce_mul:
9314     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9315     break;
9316   case Intrinsic::vector_reduce_and:
9317     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9318     break;
9319   case Intrinsic::vector_reduce_or:
9320     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9321     break;
9322   case Intrinsic::vector_reduce_xor:
9323     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9324     break;
9325   case Intrinsic::vector_reduce_smax:
9326     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9327     break;
9328   case Intrinsic::vector_reduce_smin:
9329     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9330     break;
9331   case Intrinsic::vector_reduce_umax:
9332     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9333     break;
9334   case Intrinsic::vector_reduce_umin:
9335     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9336     break;
9337   case Intrinsic::vector_reduce_fmax:
9338     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9339     break;
9340   case Intrinsic::vector_reduce_fmin:
9341     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9342     break;
9343   default:
9344     llvm_unreachable("Unhandled vector reduce intrinsic");
9345   }
9346   setValue(&I, Res);
9347 }
9348 
9349 /// Returns an AttributeList representing the attributes applied to the return
9350 /// value of the given call.
9351 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9352   SmallVector<Attribute::AttrKind, 2> Attrs;
9353   if (CLI.RetSExt)
9354     Attrs.push_back(Attribute::SExt);
9355   if (CLI.RetZExt)
9356     Attrs.push_back(Attribute::ZExt);
9357   if (CLI.IsInReg)
9358     Attrs.push_back(Attribute::InReg);
9359 
9360   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9361                             Attrs);
9362 }
9363 
9364 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9365 /// implementation, which just calls LowerCall.
9366 /// FIXME: When all targets are
9367 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9368 std::pair<SDValue, SDValue>
9369 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9370   // Handle the incoming return values from the call.
9371   CLI.Ins.clear();
9372   Type *OrigRetTy = CLI.RetTy;
9373   SmallVector<EVT, 4> RetTys;
9374   SmallVector<uint64_t, 4> Offsets;
9375   auto &DL = CLI.DAG.getDataLayout();
9376   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9377 
9378   if (CLI.IsPostTypeLegalization) {
9379     // If we are lowering a libcall after legalization, split the return type.
9380     SmallVector<EVT, 4> OldRetTys;
9381     SmallVector<uint64_t, 4> OldOffsets;
9382     RetTys.swap(OldRetTys);
9383     Offsets.swap(OldOffsets);
9384 
9385     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9386       EVT RetVT = OldRetTys[i];
9387       uint64_t Offset = OldOffsets[i];
9388       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9389       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9390       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9391       RetTys.append(NumRegs, RegisterVT);
9392       for (unsigned j = 0; j != NumRegs; ++j)
9393         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9394     }
9395   }
9396 
9397   SmallVector<ISD::OutputArg, 4> Outs;
9398   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9399 
9400   bool CanLowerReturn =
9401       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9402                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9403 
9404   SDValue DemoteStackSlot;
9405   int DemoteStackIdx = -100;
9406   if (!CanLowerReturn) {
9407     // FIXME: equivalent assert?
9408     // assert(!CS.hasInAllocaArgument() &&
9409     //        "sret demotion is incompatible with inalloca");
9410     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9411     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9412     MachineFunction &MF = CLI.DAG.getMachineFunction();
9413     DemoteStackIdx =
9414         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9415     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9416                                               DL.getAllocaAddrSpace());
9417 
9418     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9419     ArgListEntry Entry;
9420     Entry.Node = DemoteStackSlot;
9421     Entry.Ty = StackSlotPtrType;
9422     Entry.IsSExt = false;
9423     Entry.IsZExt = false;
9424     Entry.IsInReg = false;
9425     Entry.IsSRet = true;
9426     Entry.IsNest = false;
9427     Entry.IsByVal = false;
9428     Entry.IsByRef = false;
9429     Entry.IsReturned = false;
9430     Entry.IsSwiftSelf = false;
9431     Entry.IsSwiftAsync = false;
9432     Entry.IsSwiftError = false;
9433     Entry.IsCFGuardTarget = false;
9434     Entry.Alignment = Alignment;
9435     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9436     CLI.NumFixedArgs += 1;
9437     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9438 
9439     // sret demotion isn't compatible with tail-calls, since the sret argument
9440     // points into the callers stack frame.
9441     CLI.IsTailCall = false;
9442   } else {
9443     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9444         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9445     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9446       ISD::ArgFlagsTy Flags;
9447       if (NeedsRegBlock) {
9448         Flags.setInConsecutiveRegs();
9449         if (I == RetTys.size() - 1)
9450           Flags.setInConsecutiveRegsLast();
9451       }
9452       EVT VT = RetTys[I];
9453       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9454                                                      CLI.CallConv, VT);
9455       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9456                                                        CLI.CallConv, VT);
9457       for (unsigned i = 0; i != NumRegs; ++i) {
9458         ISD::InputArg MyFlags;
9459         MyFlags.Flags = Flags;
9460         MyFlags.VT = RegisterVT;
9461         MyFlags.ArgVT = VT;
9462         MyFlags.Used = CLI.IsReturnValueUsed;
9463         if (CLI.RetTy->isPointerTy()) {
9464           MyFlags.Flags.setPointer();
9465           MyFlags.Flags.setPointerAddrSpace(
9466               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9467         }
9468         if (CLI.RetSExt)
9469           MyFlags.Flags.setSExt();
9470         if (CLI.RetZExt)
9471           MyFlags.Flags.setZExt();
9472         if (CLI.IsInReg)
9473           MyFlags.Flags.setInReg();
9474         CLI.Ins.push_back(MyFlags);
9475       }
9476     }
9477   }
9478 
9479   // We push in swifterror return as the last element of CLI.Ins.
9480   ArgListTy &Args = CLI.getArgs();
9481   if (supportSwiftError()) {
9482     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9483       if (Args[i].IsSwiftError) {
9484         ISD::InputArg MyFlags;
9485         MyFlags.VT = getPointerTy(DL);
9486         MyFlags.ArgVT = EVT(getPointerTy(DL));
9487         MyFlags.Flags.setSwiftError();
9488         CLI.Ins.push_back(MyFlags);
9489       }
9490     }
9491   }
9492 
9493   // Handle all of the outgoing arguments.
9494   CLI.Outs.clear();
9495   CLI.OutVals.clear();
9496   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9497     SmallVector<EVT, 4> ValueVTs;
9498     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9499     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9500     Type *FinalType = Args[i].Ty;
9501     if (Args[i].IsByVal)
9502       FinalType = Args[i].IndirectType;
9503     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9504         FinalType, CLI.CallConv, CLI.IsVarArg);
9505     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9506          ++Value) {
9507       EVT VT = ValueVTs[Value];
9508       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9509       SDValue Op = SDValue(Args[i].Node.getNode(),
9510                            Args[i].Node.getResNo() + Value);
9511       ISD::ArgFlagsTy Flags;
9512 
9513       // Certain targets (such as MIPS), may have a different ABI alignment
9514       // for a type depending on the context. Give the target a chance to
9515       // specify the alignment it wants.
9516       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9517       Flags.setOrigAlign(OriginalAlignment);
9518 
9519       if (Args[i].Ty->isPointerTy()) {
9520         Flags.setPointer();
9521         Flags.setPointerAddrSpace(
9522             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9523       }
9524       if (Args[i].IsZExt)
9525         Flags.setZExt();
9526       if (Args[i].IsSExt)
9527         Flags.setSExt();
9528       if (Args[i].IsInReg) {
9529         // If we are using vectorcall calling convention, a structure that is
9530         // passed InReg - is surely an HVA
9531         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9532             isa<StructType>(FinalType)) {
9533           // The first value of a structure is marked
9534           if (0 == Value)
9535             Flags.setHvaStart();
9536           Flags.setHva();
9537         }
9538         // Set InReg Flag
9539         Flags.setInReg();
9540       }
9541       if (Args[i].IsSRet)
9542         Flags.setSRet();
9543       if (Args[i].IsSwiftSelf)
9544         Flags.setSwiftSelf();
9545       if (Args[i].IsSwiftAsync)
9546         Flags.setSwiftAsync();
9547       if (Args[i].IsSwiftError)
9548         Flags.setSwiftError();
9549       if (Args[i].IsCFGuardTarget)
9550         Flags.setCFGuardTarget();
9551       if (Args[i].IsByVal)
9552         Flags.setByVal();
9553       if (Args[i].IsByRef)
9554         Flags.setByRef();
9555       if (Args[i].IsPreallocated) {
9556         Flags.setPreallocated();
9557         // Set the byval flag for CCAssignFn callbacks that don't know about
9558         // preallocated.  This way we can know how many bytes we should've
9559         // allocated and how many bytes a callee cleanup function will pop.  If
9560         // we port preallocated to more targets, we'll have to add custom
9561         // preallocated handling in the various CC lowering callbacks.
9562         Flags.setByVal();
9563       }
9564       if (Args[i].IsInAlloca) {
9565         Flags.setInAlloca();
9566         // Set the byval flag for CCAssignFn callbacks that don't know about
9567         // inalloca.  This way we can know how many bytes we should've allocated
9568         // and how many bytes a callee cleanup function will pop.  If we port
9569         // inalloca to more targets, we'll have to add custom inalloca handling
9570         // in the various CC lowering callbacks.
9571         Flags.setByVal();
9572       }
9573       Align MemAlign;
9574       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9575         Type *ElementTy = Args[i].IndirectType;
9576         assert(ElementTy && "Indirect type not set in ArgListEntry");
9577 
9578         unsigned FrameSize = DL.getTypeAllocSize(ElementTy);
9579         Flags.setByValSize(FrameSize);
9580 
9581         // info is not there but there are cases it cannot get right.
9582         if (auto MA = Args[i].Alignment)
9583           MemAlign = *MA;
9584         else
9585           MemAlign = Align(getByValTypeAlignment(ElementTy, DL));
9586       } else if (auto MA = Args[i].Alignment) {
9587         MemAlign = *MA;
9588       } else {
9589         MemAlign = OriginalAlignment;
9590       }
9591       Flags.setMemAlign(MemAlign);
9592       if (Args[i].IsNest)
9593         Flags.setNest();
9594       if (NeedsRegBlock)
9595         Flags.setInConsecutiveRegs();
9596 
9597       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9598                                                  CLI.CallConv, VT);
9599       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9600                                                         CLI.CallConv, VT);
9601       SmallVector<SDValue, 4> Parts(NumParts);
9602       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9603 
9604       if (Args[i].IsSExt)
9605         ExtendKind = ISD::SIGN_EXTEND;
9606       else if (Args[i].IsZExt)
9607         ExtendKind = ISD::ZERO_EXTEND;
9608 
9609       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9610       // for now.
9611       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9612           CanLowerReturn) {
9613         assert((CLI.RetTy == Args[i].Ty ||
9614                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9615                  CLI.RetTy->getPointerAddressSpace() ==
9616                      Args[i].Ty->getPointerAddressSpace())) &&
9617                RetTys.size() == NumValues && "unexpected use of 'returned'");
9618         // Before passing 'returned' to the target lowering code, ensure that
9619         // either the register MVT and the actual EVT are the same size or that
9620         // the return value and argument are extended in the same way; in these
9621         // cases it's safe to pass the argument register value unchanged as the
9622         // return register value (although it's at the target's option whether
9623         // to do so)
9624         // TODO: allow code generation to take advantage of partially preserved
9625         // registers rather than clobbering the entire register when the
9626         // parameter extension method is not compatible with the return
9627         // extension method
9628         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9629             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9630              CLI.RetZExt == Args[i].IsZExt))
9631           Flags.setReturned();
9632       }
9633 
9634       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9635                      CLI.CallConv, ExtendKind);
9636 
9637       for (unsigned j = 0; j != NumParts; ++j) {
9638         // if it isn't first piece, alignment must be 1
9639         // For scalable vectors the scalable part is currently handled
9640         // by individual targets, so we just use the known minimum size here.
9641         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9642                     i < CLI.NumFixedArgs, i,
9643                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9644         if (NumParts > 1 && j == 0)
9645           MyFlags.Flags.setSplit();
9646         else if (j != 0) {
9647           MyFlags.Flags.setOrigAlign(Align(1));
9648           if (j == NumParts - 1)
9649             MyFlags.Flags.setSplitEnd();
9650         }
9651 
9652         CLI.Outs.push_back(MyFlags);
9653         CLI.OutVals.push_back(Parts[j]);
9654       }
9655 
9656       if (NeedsRegBlock && Value == NumValues - 1)
9657         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9658     }
9659   }
9660 
9661   SmallVector<SDValue, 4> InVals;
9662   CLI.Chain = LowerCall(CLI, InVals);
9663 
9664   // Update CLI.InVals to use outside of this function.
9665   CLI.InVals = InVals;
9666 
9667   // Verify that the target's LowerCall behaved as expected.
9668   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9669          "LowerCall didn't return a valid chain!");
9670   assert((!CLI.IsTailCall || InVals.empty()) &&
9671          "LowerCall emitted a return value for a tail call!");
9672   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9673          "LowerCall didn't emit the correct number of values!");
9674 
9675   // For a tail call, the return value is merely live-out and there aren't
9676   // any nodes in the DAG representing it. Return a special value to
9677   // indicate that a tail call has been emitted and no more Instructions
9678   // should be processed in the current block.
9679   if (CLI.IsTailCall) {
9680     CLI.DAG.setRoot(CLI.Chain);
9681     return std::make_pair(SDValue(), SDValue());
9682   }
9683 
9684 #ifndef NDEBUG
9685   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9686     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9687     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9688            "LowerCall emitted a value with the wrong type!");
9689   }
9690 #endif
9691 
9692   SmallVector<SDValue, 4> ReturnValues;
9693   if (!CanLowerReturn) {
9694     // The instruction result is the result of loading from the
9695     // hidden sret parameter.
9696     SmallVector<EVT, 1> PVTs;
9697     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9698 
9699     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9700     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9701     EVT PtrVT = PVTs[0];
9702 
9703     unsigned NumValues = RetTys.size();
9704     ReturnValues.resize(NumValues);
9705     SmallVector<SDValue, 4> Chains(NumValues);
9706 
9707     // An aggregate return value cannot wrap around the address space, so
9708     // offsets to its parts don't wrap either.
9709     SDNodeFlags Flags;
9710     Flags.setNoUnsignedWrap(true);
9711 
9712     MachineFunction &MF = CLI.DAG.getMachineFunction();
9713     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9714     for (unsigned i = 0; i < NumValues; ++i) {
9715       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9716                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9717                                                         PtrVT), Flags);
9718       SDValue L = CLI.DAG.getLoad(
9719           RetTys[i], CLI.DL, CLI.Chain, Add,
9720           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9721                                             DemoteStackIdx, Offsets[i]),
9722           HiddenSRetAlign);
9723       ReturnValues[i] = L;
9724       Chains[i] = L.getValue(1);
9725     }
9726 
9727     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9728   } else {
9729     // Collect the legal value parts into potentially illegal values
9730     // that correspond to the original function's return values.
9731     Optional<ISD::NodeType> AssertOp;
9732     if (CLI.RetSExt)
9733       AssertOp = ISD::AssertSext;
9734     else if (CLI.RetZExt)
9735       AssertOp = ISD::AssertZext;
9736     unsigned CurReg = 0;
9737     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9738       EVT VT = RetTys[I];
9739       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9740                                                      CLI.CallConv, VT);
9741       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9742                                                        CLI.CallConv, VT);
9743 
9744       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9745                                               NumRegs, RegisterVT, VT, nullptr,
9746                                               CLI.CallConv, AssertOp));
9747       CurReg += NumRegs;
9748     }
9749 
9750     // For a function returning void, there is no return value. We can't create
9751     // such a node, so we just return a null return value in that case. In
9752     // that case, nothing will actually look at the value.
9753     if (ReturnValues.empty())
9754       return std::make_pair(SDValue(), CLI.Chain);
9755   }
9756 
9757   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9758                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9759   return std::make_pair(Res, CLI.Chain);
9760 }
9761 
9762 /// Places new result values for the node in Results (their number
9763 /// and types must exactly match those of the original return values of
9764 /// the node), or leaves Results empty, which indicates that the node is not
9765 /// to be custom lowered after all.
9766 void TargetLowering::LowerOperationWrapper(SDNode *N,
9767                                            SmallVectorImpl<SDValue> &Results,
9768                                            SelectionDAG &DAG) const {
9769   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9770 
9771   if (!Res.getNode())
9772     return;
9773 
9774   // If the original node has one result, take the return value from
9775   // LowerOperation as is. It might not be result number 0.
9776   if (N->getNumValues() == 1) {
9777     Results.push_back(Res);
9778     return;
9779   }
9780 
9781   // If the original node has multiple results, then the return node should
9782   // have the same number of results.
9783   assert((N->getNumValues() == Res->getNumValues()) &&
9784       "Lowering returned the wrong number of results!");
9785 
9786   // Places new result values base on N result number.
9787   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9788     Results.push_back(Res.getValue(I));
9789 }
9790 
9791 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9792   llvm_unreachable("LowerOperation not implemented for this target!");
9793 }
9794 
9795 void
9796 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9797   SDValue Op = getNonRegisterValue(V);
9798   assert((Op.getOpcode() != ISD::CopyFromReg ||
9799           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9800          "Copy from a reg to the same reg!");
9801   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9802 
9803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9804   // If this is an InlineAsm we have to match the registers required, not the
9805   // notional registers required by the type.
9806 
9807   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9808                    None); // This is not an ABI copy.
9809   SDValue Chain = DAG.getEntryNode();
9810 
9811   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9812                               FuncInfo.PreferredExtendType.end())
9813                                  ? ISD::ANY_EXTEND
9814                                  : FuncInfo.PreferredExtendType[V];
9815   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9816   PendingExports.push_back(Chain);
9817 }
9818 
9819 #include "llvm/CodeGen/SelectionDAGISel.h"
9820 
9821 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9822 /// entry block, return true.  This includes arguments used by switches, since
9823 /// the switch may expand into multiple basic blocks.
9824 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9825   // With FastISel active, we may be splitting blocks, so force creation
9826   // of virtual registers for all non-dead arguments.
9827   if (FastISel)
9828     return A->use_empty();
9829 
9830   const BasicBlock &Entry = A->getParent()->front();
9831   for (const User *U : A->users())
9832     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9833       return false;  // Use not in entry block.
9834 
9835   return true;
9836 }
9837 
9838 using ArgCopyElisionMapTy =
9839     DenseMap<const Argument *,
9840              std::pair<const AllocaInst *, const StoreInst *>>;
9841 
9842 /// Scan the entry block of the function in FuncInfo for arguments that look
9843 /// like copies into a local alloca. Record any copied arguments in
9844 /// ArgCopyElisionCandidates.
9845 static void
9846 findArgumentCopyElisionCandidates(const DataLayout &DL,
9847                                   FunctionLoweringInfo *FuncInfo,
9848                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9849   // Record the state of every static alloca used in the entry block. Argument
9850   // allocas are all used in the entry block, so we need approximately as many
9851   // entries as we have arguments.
9852   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9853   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9854   unsigned NumArgs = FuncInfo->Fn->arg_size();
9855   StaticAllocas.reserve(NumArgs * 2);
9856 
9857   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9858     if (!V)
9859       return nullptr;
9860     V = V->stripPointerCasts();
9861     const auto *AI = dyn_cast<AllocaInst>(V);
9862     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9863       return nullptr;
9864     auto Iter = StaticAllocas.insert({AI, Unknown});
9865     return &Iter.first->second;
9866   };
9867 
9868   // Look for stores of arguments to static allocas. Look through bitcasts and
9869   // GEPs to handle type coercions, as long as the alloca is fully initialized
9870   // by the store. Any non-store use of an alloca escapes it and any subsequent
9871   // unanalyzed store might write it.
9872   // FIXME: Handle structs initialized with multiple stores.
9873   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9874     // Look for stores, and handle non-store uses conservatively.
9875     const auto *SI = dyn_cast<StoreInst>(&I);
9876     if (!SI) {
9877       // We will look through cast uses, so ignore them completely.
9878       if (I.isCast())
9879         continue;
9880       // Ignore debug info and pseudo op intrinsics, they don't escape or store
9881       // to allocas.
9882       if (I.isDebugOrPseudoInst())
9883         continue;
9884       // This is an unknown instruction. Assume it escapes or writes to all
9885       // static alloca operands.
9886       for (const Use &U : I.operands()) {
9887         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9888           *Info = StaticAllocaInfo::Clobbered;
9889       }
9890       continue;
9891     }
9892 
9893     // If the stored value is a static alloca, mark it as escaped.
9894     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9895       *Info = StaticAllocaInfo::Clobbered;
9896 
9897     // Check if the destination is a static alloca.
9898     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9899     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9900     if (!Info)
9901       continue;
9902     const AllocaInst *AI = cast<AllocaInst>(Dst);
9903 
9904     // Skip allocas that have been initialized or clobbered.
9905     if (*Info != StaticAllocaInfo::Unknown)
9906       continue;
9907 
9908     // Check if the stored value is an argument, and that this store fully
9909     // initializes the alloca.
9910     // If the argument type has padding bits we can't directly forward a pointer
9911     // as the upper bits may contain garbage.
9912     // Don't elide copies from the same argument twice.
9913     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9914     const auto *Arg = dyn_cast<Argument>(Val);
9915     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
9916         Arg->getType()->isEmptyTy() ||
9917         DL.getTypeStoreSize(Arg->getType()) !=
9918             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9919         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
9920         ArgCopyElisionCandidates.count(Arg)) {
9921       *Info = StaticAllocaInfo::Clobbered;
9922       continue;
9923     }
9924 
9925     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9926                       << '\n');
9927 
9928     // Mark this alloca and store for argument copy elision.
9929     *Info = StaticAllocaInfo::Elidable;
9930     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9931 
9932     // Stop scanning if we've seen all arguments. This will happen early in -O0
9933     // builds, which is useful, because -O0 builds have large entry blocks and
9934     // many allocas.
9935     if (ArgCopyElisionCandidates.size() == NumArgs)
9936       break;
9937   }
9938 }
9939 
9940 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9941 /// ArgVal is a load from a suitable fixed stack object.
9942 static void tryToElideArgumentCopy(
9943     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9944     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9945     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9946     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9947     SDValue ArgVal, bool &ArgHasUses) {
9948   // Check if this is a load from a fixed stack object.
9949   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9950   if (!LNode)
9951     return;
9952   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9953   if (!FINode)
9954     return;
9955 
9956   // Check that the fixed stack object is the right size and alignment.
9957   // Look at the alignment that the user wrote on the alloca instead of looking
9958   // at the stack object.
9959   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9960   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9961   const AllocaInst *AI = ArgCopyIter->second.first;
9962   int FixedIndex = FINode->getIndex();
9963   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9964   int OldIndex = AllocaIndex;
9965   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9966   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9967     LLVM_DEBUG(
9968         dbgs() << "  argument copy elision failed due to bad fixed stack "
9969                   "object size\n");
9970     return;
9971   }
9972   Align RequiredAlignment = AI->getAlign();
9973   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9974     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9975                          "greater than stack argument alignment ("
9976                       << DebugStr(RequiredAlignment) << " vs "
9977                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9978     return;
9979   }
9980 
9981   // Perform the elision. Delete the old stack object and replace its only use
9982   // in the variable info map. Mark the stack object as mutable.
9983   LLVM_DEBUG({
9984     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9985            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9986            << '\n';
9987   });
9988   MFI.RemoveStackObject(OldIndex);
9989   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9990   AllocaIndex = FixedIndex;
9991   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9992   Chains.push_back(ArgVal.getValue(1));
9993 
9994   // Avoid emitting code for the store implementing the copy.
9995   const StoreInst *SI = ArgCopyIter->second.second;
9996   ElidedArgCopyInstrs.insert(SI);
9997 
9998   // Check for uses of the argument again so that we can avoid exporting ArgVal
9999   // if it is't used by anything other than the store.
10000   for (const Value *U : Arg.users()) {
10001     if (U != SI) {
10002       ArgHasUses = true;
10003       break;
10004     }
10005   }
10006 }
10007 
10008 void SelectionDAGISel::LowerArguments(const Function &F) {
10009   SelectionDAG &DAG = SDB->DAG;
10010   SDLoc dl = SDB->getCurSDLoc();
10011   const DataLayout &DL = DAG.getDataLayout();
10012   SmallVector<ISD::InputArg, 16> Ins;
10013 
10014   // In Naked functions we aren't going to save any registers.
10015   if (F.hasFnAttribute(Attribute::Naked))
10016     return;
10017 
10018   if (!FuncInfo->CanLowerReturn) {
10019     // Put in an sret pointer parameter before all the other parameters.
10020     SmallVector<EVT, 1> ValueVTs;
10021     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10022                     F.getReturnType()->getPointerTo(
10023                         DAG.getDataLayout().getAllocaAddrSpace()),
10024                     ValueVTs);
10025 
10026     // NOTE: Assuming that a pointer will never break down to more than one VT
10027     // or one register.
10028     ISD::ArgFlagsTy Flags;
10029     Flags.setSRet();
10030     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10031     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10032                          ISD::InputArg::NoArgIndex, 0);
10033     Ins.push_back(RetArg);
10034   }
10035 
10036   // Look for stores of arguments to static allocas. Mark such arguments with a
10037   // flag to ask the target to give us the memory location of that argument if
10038   // available.
10039   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10040   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10041                                     ArgCopyElisionCandidates);
10042 
10043   // Set up the incoming argument description vector.
10044   for (const Argument &Arg : F.args()) {
10045     unsigned ArgNo = Arg.getArgNo();
10046     SmallVector<EVT, 4> ValueVTs;
10047     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10048     bool isArgValueUsed = !Arg.use_empty();
10049     unsigned PartBase = 0;
10050     Type *FinalType = Arg.getType();
10051     if (Arg.hasAttribute(Attribute::ByVal))
10052       FinalType = Arg.getParamByValType();
10053     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10054         FinalType, F.getCallingConv(), F.isVarArg());
10055     for (unsigned Value = 0, NumValues = ValueVTs.size();
10056          Value != NumValues; ++Value) {
10057       EVT VT = ValueVTs[Value];
10058       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10059       ISD::ArgFlagsTy Flags;
10060 
10061 
10062       if (Arg.getType()->isPointerTy()) {
10063         Flags.setPointer();
10064         Flags.setPointerAddrSpace(
10065             cast<PointerType>(Arg.getType())->getAddressSpace());
10066       }
10067       if (Arg.hasAttribute(Attribute::ZExt))
10068         Flags.setZExt();
10069       if (Arg.hasAttribute(Attribute::SExt))
10070         Flags.setSExt();
10071       if (Arg.hasAttribute(Attribute::InReg)) {
10072         // If we are using vectorcall calling convention, a structure that is
10073         // passed InReg - is surely an HVA
10074         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10075             isa<StructType>(Arg.getType())) {
10076           // The first value of a structure is marked
10077           if (0 == Value)
10078             Flags.setHvaStart();
10079           Flags.setHva();
10080         }
10081         // Set InReg Flag
10082         Flags.setInReg();
10083       }
10084       if (Arg.hasAttribute(Attribute::StructRet))
10085         Flags.setSRet();
10086       if (Arg.hasAttribute(Attribute::SwiftSelf))
10087         Flags.setSwiftSelf();
10088       if (Arg.hasAttribute(Attribute::SwiftAsync))
10089         Flags.setSwiftAsync();
10090       if (Arg.hasAttribute(Attribute::SwiftError))
10091         Flags.setSwiftError();
10092       if (Arg.hasAttribute(Attribute::ByVal))
10093         Flags.setByVal();
10094       if (Arg.hasAttribute(Attribute::ByRef))
10095         Flags.setByRef();
10096       if (Arg.hasAttribute(Attribute::InAlloca)) {
10097         Flags.setInAlloca();
10098         // Set the byval flag for CCAssignFn callbacks that don't know about
10099         // inalloca.  This way we can know how many bytes we should've allocated
10100         // and how many bytes a callee cleanup function will pop.  If we port
10101         // inalloca to more targets, we'll have to add custom inalloca handling
10102         // in the various CC lowering callbacks.
10103         Flags.setByVal();
10104       }
10105       if (Arg.hasAttribute(Attribute::Preallocated)) {
10106         Flags.setPreallocated();
10107         // Set the byval flag for CCAssignFn callbacks that don't know about
10108         // preallocated.  This way we can know how many bytes we should've
10109         // allocated and how many bytes a callee cleanup function will pop.  If
10110         // we port preallocated to more targets, we'll have to add custom
10111         // preallocated handling in the various CC lowering callbacks.
10112         Flags.setByVal();
10113       }
10114 
10115       // Certain targets (such as MIPS), may have a different ABI alignment
10116       // for a type depending on the context. Give the target a chance to
10117       // specify the alignment it wants.
10118       const Align OriginalAlignment(
10119           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10120       Flags.setOrigAlign(OriginalAlignment);
10121 
10122       Align MemAlign;
10123       Type *ArgMemTy = nullptr;
10124       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10125           Flags.isByRef()) {
10126         if (!ArgMemTy)
10127           ArgMemTy = Arg.getPointeeInMemoryValueType();
10128 
10129         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10130 
10131         // For in-memory arguments, size and alignment should be passed from FE.
10132         // BE will guess if this info is not there but there are cases it cannot
10133         // get right.
10134         if (auto ParamAlign = Arg.getParamStackAlign())
10135           MemAlign = *ParamAlign;
10136         else if ((ParamAlign = Arg.getParamAlign()))
10137           MemAlign = *ParamAlign;
10138         else
10139           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10140         if (Flags.isByRef())
10141           Flags.setByRefSize(MemSize);
10142         else
10143           Flags.setByValSize(MemSize);
10144       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10145         MemAlign = *ParamAlign;
10146       } else {
10147         MemAlign = OriginalAlignment;
10148       }
10149       Flags.setMemAlign(MemAlign);
10150 
10151       if (Arg.hasAttribute(Attribute::Nest))
10152         Flags.setNest();
10153       if (NeedsRegBlock)
10154         Flags.setInConsecutiveRegs();
10155       if (ArgCopyElisionCandidates.count(&Arg))
10156         Flags.setCopyElisionCandidate();
10157       if (Arg.hasAttribute(Attribute::Returned))
10158         Flags.setReturned();
10159 
10160       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10161           *CurDAG->getContext(), F.getCallingConv(), VT);
10162       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10163           *CurDAG->getContext(), F.getCallingConv(), VT);
10164       for (unsigned i = 0; i != NumRegs; ++i) {
10165         // For scalable vectors, use the minimum size; individual targets
10166         // are responsible for handling scalable vector arguments and
10167         // return values.
10168         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10169                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10170         if (NumRegs > 1 && i == 0)
10171           MyFlags.Flags.setSplit();
10172         // if it isn't first piece, alignment must be 1
10173         else if (i > 0) {
10174           MyFlags.Flags.setOrigAlign(Align(1));
10175           if (i == NumRegs - 1)
10176             MyFlags.Flags.setSplitEnd();
10177         }
10178         Ins.push_back(MyFlags);
10179       }
10180       if (NeedsRegBlock && Value == NumValues - 1)
10181         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10182       PartBase += VT.getStoreSize().getKnownMinSize();
10183     }
10184   }
10185 
10186   // Call the target to set up the argument values.
10187   SmallVector<SDValue, 8> InVals;
10188   SDValue NewRoot = TLI->LowerFormalArguments(
10189       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10190 
10191   // Verify that the target's LowerFormalArguments behaved as expected.
10192   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10193          "LowerFormalArguments didn't return a valid chain!");
10194   assert(InVals.size() == Ins.size() &&
10195          "LowerFormalArguments didn't emit the correct number of values!");
10196   LLVM_DEBUG({
10197     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10198       assert(InVals[i].getNode() &&
10199              "LowerFormalArguments emitted a null value!");
10200       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10201              "LowerFormalArguments emitted a value with the wrong type!");
10202     }
10203   });
10204 
10205   // Update the DAG with the new chain value resulting from argument lowering.
10206   DAG.setRoot(NewRoot);
10207 
10208   // Set up the argument values.
10209   unsigned i = 0;
10210   if (!FuncInfo->CanLowerReturn) {
10211     // Create a virtual register for the sret pointer, and put in a copy
10212     // from the sret argument into it.
10213     SmallVector<EVT, 1> ValueVTs;
10214     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10215                     F.getReturnType()->getPointerTo(
10216                         DAG.getDataLayout().getAllocaAddrSpace()),
10217                     ValueVTs);
10218     MVT VT = ValueVTs[0].getSimpleVT();
10219     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10220     Optional<ISD::NodeType> AssertOp = None;
10221     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10222                                         nullptr, F.getCallingConv(), AssertOp);
10223 
10224     MachineFunction& MF = SDB->DAG.getMachineFunction();
10225     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10226     Register SRetReg =
10227         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10228     FuncInfo->DemoteRegister = SRetReg;
10229     NewRoot =
10230         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10231     DAG.setRoot(NewRoot);
10232 
10233     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10234     ++i;
10235   }
10236 
10237   SmallVector<SDValue, 4> Chains;
10238   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10239   for (const Argument &Arg : F.args()) {
10240     SmallVector<SDValue, 4> ArgValues;
10241     SmallVector<EVT, 4> ValueVTs;
10242     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10243     unsigned NumValues = ValueVTs.size();
10244     if (NumValues == 0)
10245       continue;
10246 
10247     bool ArgHasUses = !Arg.use_empty();
10248 
10249     // Elide the copying store if the target loaded this argument from a
10250     // suitable fixed stack object.
10251     if (Ins[i].Flags.isCopyElisionCandidate()) {
10252       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10253                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10254                              InVals[i], ArgHasUses);
10255     }
10256 
10257     // If this argument is unused then remember its value. It is used to generate
10258     // debugging information.
10259     bool isSwiftErrorArg =
10260         TLI->supportSwiftError() &&
10261         Arg.hasAttribute(Attribute::SwiftError);
10262     if (!ArgHasUses && !isSwiftErrorArg) {
10263       SDB->setUnusedArgValue(&Arg, InVals[i]);
10264 
10265       // Also remember any frame index for use in FastISel.
10266       if (FrameIndexSDNode *FI =
10267           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10268         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10269     }
10270 
10271     for (unsigned Val = 0; Val != NumValues; ++Val) {
10272       EVT VT = ValueVTs[Val];
10273       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10274                                                       F.getCallingConv(), VT);
10275       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10276           *CurDAG->getContext(), F.getCallingConv(), VT);
10277 
10278       // Even an apparent 'unused' swifterror argument needs to be returned. So
10279       // we do generate a copy for it that can be used on return from the
10280       // function.
10281       if (ArgHasUses || isSwiftErrorArg) {
10282         Optional<ISD::NodeType> AssertOp;
10283         if (Arg.hasAttribute(Attribute::SExt))
10284           AssertOp = ISD::AssertSext;
10285         else if (Arg.hasAttribute(Attribute::ZExt))
10286           AssertOp = ISD::AssertZext;
10287 
10288         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10289                                              PartVT, VT, nullptr,
10290                                              F.getCallingConv(), AssertOp));
10291       }
10292 
10293       i += NumParts;
10294     }
10295 
10296     // We don't need to do anything else for unused arguments.
10297     if (ArgValues.empty())
10298       continue;
10299 
10300     // Note down frame index.
10301     if (FrameIndexSDNode *FI =
10302         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10303       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10304 
10305     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10306                                      SDB->getCurSDLoc());
10307 
10308     SDB->setValue(&Arg, Res);
10309     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10310       // We want to associate the argument with the frame index, among
10311       // involved operands, that correspond to the lowest address. The
10312       // getCopyFromParts function, called earlier, is swapping the order of
10313       // the operands to BUILD_PAIR depending on endianness. The result of
10314       // that swapping is that the least significant bits of the argument will
10315       // be in the first operand of the BUILD_PAIR node, and the most
10316       // significant bits will be in the second operand.
10317       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10318       if (LoadSDNode *LNode =
10319           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10320         if (FrameIndexSDNode *FI =
10321             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10322           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10323     }
10324 
10325     // Analyses past this point are naive and don't expect an assertion.
10326     if (Res.getOpcode() == ISD::AssertZext)
10327       Res = Res.getOperand(0);
10328 
10329     // Update the SwiftErrorVRegDefMap.
10330     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10331       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10332       if (Register::isVirtualRegister(Reg))
10333         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10334                                    Reg);
10335     }
10336 
10337     // If this argument is live outside of the entry block, insert a copy from
10338     // wherever we got it to the vreg that other BB's will reference it as.
10339     if (Res.getOpcode() == ISD::CopyFromReg) {
10340       // If we can, though, try to skip creating an unnecessary vreg.
10341       // FIXME: This isn't very clean... it would be nice to make this more
10342       // general.
10343       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10344       if (Register::isVirtualRegister(Reg)) {
10345         FuncInfo->ValueMap[&Arg] = Reg;
10346         continue;
10347       }
10348     }
10349     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10350       FuncInfo->InitializeRegForValue(&Arg);
10351       SDB->CopyToExportRegsIfNeeded(&Arg);
10352     }
10353   }
10354 
10355   if (!Chains.empty()) {
10356     Chains.push_back(NewRoot);
10357     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10358   }
10359 
10360   DAG.setRoot(NewRoot);
10361 
10362   assert(i == InVals.size() && "Argument register count mismatch!");
10363 
10364   // If any argument copy elisions occurred and we have debug info, update the
10365   // stale frame indices used in the dbg.declare variable info table.
10366   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10367   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10368     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10369       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10370       if (I != ArgCopyElisionFrameIndexMap.end())
10371         VI.Slot = I->second;
10372     }
10373   }
10374 
10375   // Finally, if the target has anything special to do, allow it to do so.
10376   emitFunctionEntryCode();
10377 }
10378 
10379 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10380 /// ensure constants are generated when needed.  Remember the virtual registers
10381 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10382 /// directly add them, because expansion might result in multiple MBB's for one
10383 /// BB.  As such, the start of the BB might correspond to a different MBB than
10384 /// the end.
10385 void
10386 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10387   const Instruction *TI = LLVMBB->getTerminator();
10388 
10389   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10390 
10391   // Check PHI nodes in successors that expect a value to be available from this
10392   // block.
10393   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10394     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10395     if (!isa<PHINode>(SuccBB->begin())) continue;
10396     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10397 
10398     // If this terminator has multiple identical successors (common for
10399     // switches), only handle each succ once.
10400     if (!SuccsHandled.insert(SuccMBB).second)
10401       continue;
10402 
10403     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10404 
10405     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10406     // nodes and Machine PHI nodes, but the incoming operands have not been
10407     // emitted yet.
10408     for (const PHINode &PN : SuccBB->phis()) {
10409       // Ignore dead phi's.
10410       if (PN.use_empty())
10411         continue;
10412 
10413       // Skip empty types
10414       if (PN.getType()->isEmptyTy())
10415         continue;
10416 
10417       unsigned Reg;
10418       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10419 
10420       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10421         unsigned &RegOut = ConstantsOut[C];
10422         if (RegOut == 0) {
10423           RegOut = FuncInfo.CreateRegs(C);
10424           CopyValueToVirtualRegister(C, RegOut);
10425         }
10426         Reg = RegOut;
10427       } else {
10428         DenseMap<const Value *, Register>::iterator I =
10429           FuncInfo.ValueMap.find(PHIOp);
10430         if (I != FuncInfo.ValueMap.end())
10431           Reg = I->second;
10432         else {
10433           assert(isa<AllocaInst>(PHIOp) &&
10434                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10435                  "Didn't codegen value into a register!??");
10436           Reg = FuncInfo.CreateRegs(PHIOp);
10437           CopyValueToVirtualRegister(PHIOp, Reg);
10438         }
10439       }
10440 
10441       // Remember that this register needs to added to the machine PHI node as
10442       // the input for this MBB.
10443       SmallVector<EVT, 4> ValueVTs;
10444       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10445       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10446       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10447         EVT VT = ValueVTs[vti];
10448         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10449         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10450           FuncInfo.PHINodesToUpdate.push_back(
10451               std::make_pair(&*MBBI++, Reg + i));
10452         Reg += NumRegisters;
10453       }
10454     }
10455   }
10456 
10457   ConstantsOut.clear();
10458 }
10459 
10460 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10461 /// is 0.
10462 MachineBasicBlock *
10463 SelectionDAGBuilder::StackProtectorDescriptor::
10464 AddSuccessorMBB(const BasicBlock *BB,
10465                 MachineBasicBlock *ParentMBB,
10466                 bool IsLikely,
10467                 MachineBasicBlock *SuccMBB) {
10468   // If SuccBB has not been created yet, create it.
10469   if (!SuccMBB) {
10470     MachineFunction *MF = ParentMBB->getParent();
10471     MachineFunction::iterator BBI(ParentMBB);
10472     SuccMBB = MF->CreateMachineBasicBlock(BB);
10473     MF->insert(++BBI, SuccMBB);
10474   }
10475   // Add it as a successor of ParentMBB.
10476   ParentMBB->addSuccessor(
10477       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10478   return SuccMBB;
10479 }
10480 
10481 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10482   MachineFunction::iterator I(MBB);
10483   if (++I == FuncInfo.MF->end())
10484     return nullptr;
10485   return &*I;
10486 }
10487 
10488 /// During lowering new call nodes can be created (such as memset, etc.).
10489 /// Those will become new roots of the current DAG, but complications arise
10490 /// when they are tail calls. In such cases, the call lowering will update
10491 /// the root, but the builder still needs to know that a tail call has been
10492 /// lowered in order to avoid generating an additional return.
10493 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10494   // If the node is null, we do have a tail call.
10495   if (MaybeTC.getNode() != nullptr)
10496     DAG.setRoot(MaybeTC);
10497   else
10498     HasTailCall = true;
10499 }
10500 
10501 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10502                                         MachineBasicBlock *SwitchMBB,
10503                                         MachineBasicBlock *DefaultMBB) {
10504   MachineFunction *CurMF = FuncInfo.MF;
10505   MachineBasicBlock *NextMBB = nullptr;
10506   MachineFunction::iterator BBI(W.MBB);
10507   if (++BBI != FuncInfo.MF->end())
10508     NextMBB = &*BBI;
10509 
10510   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10511 
10512   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10513 
10514   if (Size == 2 && W.MBB == SwitchMBB) {
10515     // If any two of the cases has the same destination, and if one value
10516     // is the same as the other, but has one bit unset that the other has set,
10517     // use bit manipulation to do two compares at once.  For example:
10518     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10519     // TODO: This could be extended to merge any 2 cases in switches with 3
10520     // cases.
10521     // TODO: Handle cases where W.CaseBB != SwitchBB.
10522     CaseCluster &Small = *W.FirstCluster;
10523     CaseCluster &Big = *W.LastCluster;
10524 
10525     if (Small.Low == Small.High && Big.Low == Big.High &&
10526         Small.MBB == Big.MBB) {
10527       const APInt &SmallValue = Small.Low->getValue();
10528       const APInt &BigValue = Big.Low->getValue();
10529 
10530       // Check that there is only one bit different.
10531       APInt CommonBit = BigValue ^ SmallValue;
10532       if (CommonBit.isPowerOf2()) {
10533         SDValue CondLHS = getValue(Cond);
10534         EVT VT = CondLHS.getValueType();
10535         SDLoc DL = getCurSDLoc();
10536 
10537         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10538                                  DAG.getConstant(CommonBit, DL, VT));
10539         SDValue Cond = DAG.getSetCC(
10540             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10541             ISD::SETEQ);
10542 
10543         // Update successor info.
10544         // Both Small and Big will jump to Small.BB, so we sum up the
10545         // probabilities.
10546         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10547         if (BPI)
10548           addSuccessorWithProb(
10549               SwitchMBB, DefaultMBB,
10550               // The default destination is the first successor in IR.
10551               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10552         else
10553           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10554 
10555         // Insert the true branch.
10556         SDValue BrCond =
10557             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10558                         DAG.getBasicBlock(Small.MBB));
10559         // Insert the false branch.
10560         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10561                              DAG.getBasicBlock(DefaultMBB));
10562 
10563         DAG.setRoot(BrCond);
10564         return;
10565       }
10566     }
10567   }
10568 
10569   if (TM.getOptLevel() != CodeGenOpt::None) {
10570     // Here, we order cases by probability so the most likely case will be
10571     // checked first. However, two clusters can have the same probability in
10572     // which case their relative ordering is non-deterministic. So we use Low
10573     // as a tie-breaker as clusters are guaranteed to never overlap.
10574     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10575                [](const CaseCluster &a, const CaseCluster &b) {
10576       return a.Prob != b.Prob ?
10577              a.Prob > b.Prob :
10578              a.Low->getValue().slt(b.Low->getValue());
10579     });
10580 
10581     // Rearrange the case blocks so that the last one falls through if possible
10582     // without changing the order of probabilities.
10583     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10584       --I;
10585       if (I->Prob > W.LastCluster->Prob)
10586         break;
10587       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10588         std::swap(*I, *W.LastCluster);
10589         break;
10590       }
10591     }
10592   }
10593 
10594   // Compute total probability.
10595   BranchProbability DefaultProb = W.DefaultProb;
10596   BranchProbability UnhandledProbs = DefaultProb;
10597   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10598     UnhandledProbs += I->Prob;
10599 
10600   MachineBasicBlock *CurMBB = W.MBB;
10601   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10602     bool FallthroughUnreachable = false;
10603     MachineBasicBlock *Fallthrough;
10604     if (I == W.LastCluster) {
10605       // For the last cluster, fall through to the default destination.
10606       Fallthrough = DefaultMBB;
10607       FallthroughUnreachable = isa<UnreachableInst>(
10608           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10609     } else {
10610       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10611       CurMF->insert(BBI, Fallthrough);
10612       // Put Cond in a virtual register to make it available from the new blocks.
10613       ExportFromCurrentBlock(Cond);
10614     }
10615     UnhandledProbs -= I->Prob;
10616 
10617     switch (I->Kind) {
10618       case CC_JumpTable: {
10619         // FIXME: Optimize away range check based on pivot comparisons.
10620         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10621         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10622 
10623         // The jump block hasn't been inserted yet; insert it here.
10624         MachineBasicBlock *JumpMBB = JT->MBB;
10625         CurMF->insert(BBI, JumpMBB);
10626 
10627         auto JumpProb = I->Prob;
10628         auto FallthroughProb = UnhandledProbs;
10629 
10630         // If the default statement is a target of the jump table, we evenly
10631         // distribute the default probability to successors of CurMBB. Also
10632         // update the probability on the edge from JumpMBB to Fallthrough.
10633         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10634                                               SE = JumpMBB->succ_end();
10635              SI != SE; ++SI) {
10636           if (*SI == DefaultMBB) {
10637             JumpProb += DefaultProb / 2;
10638             FallthroughProb -= DefaultProb / 2;
10639             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10640             JumpMBB->normalizeSuccProbs();
10641             break;
10642           }
10643         }
10644 
10645         if (FallthroughUnreachable) {
10646           // Skip the range check if the fallthrough block is unreachable.
10647           JTH->OmitRangeCheck = true;
10648         }
10649 
10650         if (!JTH->OmitRangeCheck)
10651           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10652         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10653         CurMBB->normalizeSuccProbs();
10654 
10655         // The jump table header will be inserted in our current block, do the
10656         // range check, and fall through to our fallthrough block.
10657         JTH->HeaderBB = CurMBB;
10658         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10659 
10660         // If we're in the right place, emit the jump table header right now.
10661         if (CurMBB == SwitchMBB) {
10662           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10663           JTH->Emitted = true;
10664         }
10665         break;
10666       }
10667       case CC_BitTests: {
10668         // FIXME: Optimize away range check based on pivot comparisons.
10669         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10670 
10671         // The bit test blocks haven't been inserted yet; insert them here.
10672         for (BitTestCase &BTC : BTB->Cases)
10673           CurMF->insert(BBI, BTC.ThisBB);
10674 
10675         // Fill in fields of the BitTestBlock.
10676         BTB->Parent = CurMBB;
10677         BTB->Default = Fallthrough;
10678 
10679         BTB->DefaultProb = UnhandledProbs;
10680         // If the cases in bit test don't form a contiguous range, we evenly
10681         // distribute the probability on the edge to Fallthrough to two
10682         // successors of CurMBB.
10683         if (!BTB->ContiguousRange) {
10684           BTB->Prob += DefaultProb / 2;
10685           BTB->DefaultProb -= DefaultProb / 2;
10686         }
10687 
10688         if (FallthroughUnreachable) {
10689           // Skip the range check if the fallthrough block is unreachable.
10690           BTB->OmitRangeCheck = true;
10691         }
10692 
10693         // If we're in the right place, emit the bit test header right now.
10694         if (CurMBB == SwitchMBB) {
10695           visitBitTestHeader(*BTB, SwitchMBB);
10696           BTB->Emitted = true;
10697         }
10698         break;
10699       }
10700       case CC_Range: {
10701         const Value *RHS, *LHS, *MHS;
10702         ISD::CondCode CC;
10703         if (I->Low == I->High) {
10704           // Check Cond == I->Low.
10705           CC = ISD::SETEQ;
10706           LHS = Cond;
10707           RHS=I->Low;
10708           MHS = nullptr;
10709         } else {
10710           // Check I->Low <= Cond <= I->High.
10711           CC = ISD::SETLE;
10712           LHS = I->Low;
10713           MHS = Cond;
10714           RHS = I->High;
10715         }
10716 
10717         // If Fallthrough is unreachable, fold away the comparison.
10718         if (FallthroughUnreachable)
10719           CC = ISD::SETTRUE;
10720 
10721         // The false probability is the sum of all unhandled cases.
10722         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10723                      getCurSDLoc(), I->Prob, UnhandledProbs);
10724 
10725         if (CurMBB == SwitchMBB)
10726           visitSwitchCase(CB, SwitchMBB);
10727         else
10728           SL->SwitchCases.push_back(CB);
10729 
10730         break;
10731       }
10732     }
10733     CurMBB = Fallthrough;
10734   }
10735 }
10736 
10737 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10738                                               CaseClusterIt First,
10739                                               CaseClusterIt Last) {
10740   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10741     if (X.Prob != CC.Prob)
10742       return X.Prob > CC.Prob;
10743 
10744     // Ties are broken by comparing the case value.
10745     return X.Low->getValue().slt(CC.Low->getValue());
10746   });
10747 }
10748 
10749 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10750                                         const SwitchWorkListItem &W,
10751                                         Value *Cond,
10752                                         MachineBasicBlock *SwitchMBB) {
10753   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10754          "Clusters not sorted?");
10755 
10756   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10757 
10758   // Balance the tree based on branch probabilities to create a near-optimal (in
10759   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10760   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10761   CaseClusterIt LastLeft = W.FirstCluster;
10762   CaseClusterIt FirstRight = W.LastCluster;
10763   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10764   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10765 
10766   // Move LastLeft and FirstRight towards each other from opposite directions to
10767   // find a partitioning of the clusters which balances the probability on both
10768   // sides. If LeftProb and RightProb are equal, alternate which side is
10769   // taken to ensure 0-probability nodes are distributed evenly.
10770   unsigned I = 0;
10771   while (LastLeft + 1 < FirstRight) {
10772     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10773       LeftProb += (++LastLeft)->Prob;
10774     else
10775       RightProb += (--FirstRight)->Prob;
10776     I++;
10777   }
10778 
10779   while (true) {
10780     // Our binary search tree differs from a typical BST in that ours can have up
10781     // to three values in each leaf. The pivot selection above doesn't take that
10782     // into account, which means the tree might require more nodes and be less
10783     // efficient. We compensate for this here.
10784 
10785     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10786     unsigned NumRight = W.LastCluster - FirstRight + 1;
10787 
10788     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10789       // If one side has less than 3 clusters, and the other has more than 3,
10790       // consider taking a cluster from the other side.
10791 
10792       if (NumLeft < NumRight) {
10793         // Consider moving the first cluster on the right to the left side.
10794         CaseCluster &CC = *FirstRight;
10795         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10796         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10797         if (LeftSideRank <= RightSideRank) {
10798           // Moving the cluster to the left does not demote it.
10799           ++LastLeft;
10800           ++FirstRight;
10801           continue;
10802         }
10803       } else {
10804         assert(NumRight < NumLeft);
10805         // Consider moving the last element on the left to the right side.
10806         CaseCluster &CC = *LastLeft;
10807         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10808         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10809         if (RightSideRank <= LeftSideRank) {
10810           // Moving the cluster to the right does not demot it.
10811           --LastLeft;
10812           --FirstRight;
10813           continue;
10814         }
10815       }
10816     }
10817     break;
10818   }
10819 
10820   assert(LastLeft + 1 == FirstRight);
10821   assert(LastLeft >= W.FirstCluster);
10822   assert(FirstRight <= W.LastCluster);
10823 
10824   // Use the first element on the right as pivot since we will make less-than
10825   // comparisons against it.
10826   CaseClusterIt PivotCluster = FirstRight;
10827   assert(PivotCluster > W.FirstCluster);
10828   assert(PivotCluster <= W.LastCluster);
10829 
10830   CaseClusterIt FirstLeft = W.FirstCluster;
10831   CaseClusterIt LastRight = W.LastCluster;
10832 
10833   const ConstantInt *Pivot = PivotCluster->Low;
10834 
10835   // New blocks will be inserted immediately after the current one.
10836   MachineFunction::iterator BBI(W.MBB);
10837   ++BBI;
10838 
10839   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10840   // we can branch to its destination directly if it's squeezed exactly in
10841   // between the known lower bound and Pivot - 1.
10842   MachineBasicBlock *LeftMBB;
10843   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10844       FirstLeft->Low == W.GE &&
10845       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10846     LeftMBB = FirstLeft->MBB;
10847   } else {
10848     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10849     FuncInfo.MF->insert(BBI, LeftMBB);
10850     WorkList.push_back(
10851         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10852     // Put Cond in a virtual register to make it available from the new blocks.
10853     ExportFromCurrentBlock(Cond);
10854   }
10855 
10856   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10857   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10858   // directly if RHS.High equals the current upper bound.
10859   MachineBasicBlock *RightMBB;
10860   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10861       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10862     RightMBB = FirstRight->MBB;
10863   } else {
10864     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10865     FuncInfo.MF->insert(BBI, RightMBB);
10866     WorkList.push_back(
10867         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10868     // Put Cond in a virtual register to make it available from the new blocks.
10869     ExportFromCurrentBlock(Cond);
10870   }
10871 
10872   // Create the CaseBlock record that will be used to lower the branch.
10873   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10874                getCurSDLoc(), LeftProb, RightProb);
10875 
10876   if (W.MBB == SwitchMBB)
10877     visitSwitchCase(CB, SwitchMBB);
10878   else
10879     SL->SwitchCases.push_back(CB);
10880 }
10881 
10882 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10883 // from the swith statement.
10884 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10885                                             BranchProbability PeeledCaseProb) {
10886   if (PeeledCaseProb == BranchProbability::getOne())
10887     return BranchProbability::getZero();
10888   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10889 
10890   uint32_t Numerator = CaseProb.getNumerator();
10891   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10892   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10893 }
10894 
10895 // Try to peel the top probability case if it exceeds the threshold.
10896 // Return current MachineBasicBlock for the switch statement if the peeling
10897 // does not occur.
10898 // If the peeling is performed, return the newly created MachineBasicBlock
10899 // for the peeled switch statement. Also update Clusters to remove the peeled
10900 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10901 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10902     const SwitchInst &SI, CaseClusterVector &Clusters,
10903     BranchProbability &PeeledCaseProb) {
10904   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10905   // Don't perform if there is only one cluster or optimizing for size.
10906   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10907       TM.getOptLevel() == CodeGenOpt::None ||
10908       SwitchMBB->getParent()->getFunction().hasMinSize())
10909     return SwitchMBB;
10910 
10911   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10912   unsigned PeeledCaseIndex = 0;
10913   bool SwitchPeeled = false;
10914   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10915     CaseCluster &CC = Clusters[Index];
10916     if (CC.Prob < TopCaseProb)
10917       continue;
10918     TopCaseProb = CC.Prob;
10919     PeeledCaseIndex = Index;
10920     SwitchPeeled = true;
10921   }
10922   if (!SwitchPeeled)
10923     return SwitchMBB;
10924 
10925   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10926                     << TopCaseProb << "\n");
10927 
10928   // Record the MBB for the peeled switch statement.
10929   MachineFunction::iterator BBI(SwitchMBB);
10930   ++BBI;
10931   MachineBasicBlock *PeeledSwitchMBB =
10932       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10933   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10934 
10935   ExportFromCurrentBlock(SI.getCondition());
10936   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10937   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10938                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10939   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10940 
10941   Clusters.erase(PeeledCaseIt);
10942   for (CaseCluster &CC : Clusters) {
10943     LLVM_DEBUG(
10944         dbgs() << "Scale the probablity for one cluster, before scaling: "
10945                << CC.Prob << "\n");
10946     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10947     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10948   }
10949   PeeledCaseProb = TopCaseProb;
10950   return PeeledSwitchMBB;
10951 }
10952 
10953 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10954   // Extract cases from the switch.
10955   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10956   CaseClusterVector Clusters;
10957   Clusters.reserve(SI.getNumCases());
10958   for (auto I : SI.cases()) {
10959     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10960     const ConstantInt *CaseVal = I.getCaseValue();
10961     BranchProbability Prob =
10962         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10963             : BranchProbability(1, SI.getNumCases() + 1);
10964     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10965   }
10966 
10967   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10968 
10969   // Cluster adjacent cases with the same destination. We do this at all
10970   // optimization levels because it's cheap to do and will make codegen faster
10971   // if there are many clusters.
10972   sortAndRangeify(Clusters);
10973 
10974   // The branch probablity of the peeled case.
10975   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10976   MachineBasicBlock *PeeledSwitchMBB =
10977       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10978 
10979   // If there is only the default destination, jump there directly.
10980   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10981   if (Clusters.empty()) {
10982     assert(PeeledSwitchMBB == SwitchMBB);
10983     SwitchMBB->addSuccessor(DefaultMBB);
10984     if (DefaultMBB != NextBlock(SwitchMBB)) {
10985       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10986                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10987     }
10988     return;
10989   }
10990 
10991   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10992   SL->findBitTestClusters(Clusters, &SI);
10993 
10994   LLVM_DEBUG({
10995     dbgs() << "Case clusters: ";
10996     for (const CaseCluster &C : Clusters) {
10997       if (C.Kind == CC_JumpTable)
10998         dbgs() << "JT:";
10999       if (C.Kind == CC_BitTests)
11000         dbgs() << "BT:";
11001 
11002       C.Low->getValue().print(dbgs(), true);
11003       if (C.Low != C.High) {
11004         dbgs() << '-';
11005         C.High->getValue().print(dbgs(), true);
11006       }
11007       dbgs() << ' ';
11008     }
11009     dbgs() << '\n';
11010   });
11011 
11012   assert(!Clusters.empty());
11013   SwitchWorkList WorkList;
11014   CaseClusterIt First = Clusters.begin();
11015   CaseClusterIt Last = Clusters.end() - 1;
11016   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11017   // Scale the branchprobability for DefaultMBB if the peel occurs and
11018   // DefaultMBB is not replaced.
11019   if (PeeledCaseProb != BranchProbability::getZero() &&
11020       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11021     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11022   WorkList.push_back(
11023       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11024 
11025   while (!WorkList.empty()) {
11026     SwitchWorkListItem W = WorkList.pop_back_val();
11027     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11028 
11029     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11030         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11031       // For optimized builds, lower large range as a balanced binary tree.
11032       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11033       continue;
11034     }
11035 
11036     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11037   }
11038 }
11039 
11040 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11042   auto DL = getCurSDLoc();
11043   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11044   EVT OpVT =
11045       TLI.getTypeToTransformTo(*DAG.getContext(), ResultVT.getScalarType());
11046   SDValue Step = DAG.getConstant(1, DL, OpVT);
11047   setValue(&I, DAG.getStepVector(DL, ResultVT, Step));
11048 }
11049 
11050 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11051   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11052   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11053 
11054   SDLoc DL = getCurSDLoc();
11055   SDValue V = getValue(I.getOperand(0));
11056   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11057 
11058   if (VT.isScalableVector()) {
11059     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11060     return;
11061   }
11062 
11063   // Use VECTOR_SHUFFLE for the fixed-length vector
11064   // to maintain existing behavior.
11065   SmallVector<int, 8> Mask;
11066   unsigned NumElts = VT.getVectorMinNumElements();
11067   for (unsigned i = 0; i != NumElts; ++i)
11068     Mask.push_back(NumElts - 1 - i);
11069 
11070   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11071 }
11072 
11073 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11074   SmallVector<EVT, 4> ValueVTs;
11075   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11076                   ValueVTs);
11077   unsigned NumValues = ValueVTs.size();
11078   if (NumValues == 0) return;
11079 
11080   SmallVector<SDValue, 4> Values(NumValues);
11081   SDValue Op = getValue(I.getOperand(0));
11082 
11083   for (unsigned i = 0; i != NumValues; ++i)
11084     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11085                             SDValue(Op.getNode(), Op.getResNo() + i));
11086 
11087   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11088                            DAG.getVTList(ValueVTs), Values));
11089 }
11090 
11091 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11092   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11093   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11094 
11095   SDLoc DL = getCurSDLoc();
11096   SDValue V1 = getValue(I.getOperand(0));
11097   SDValue V2 = getValue(I.getOperand(1));
11098   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11099 
11100   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11101   if (VT.isScalableVector()) {
11102     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11103     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11104                              DAG.getConstant(Imm, DL, IdxVT)));
11105     return;
11106   }
11107 
11108   unsigned NumElts = VT.getVectorNumElements();
11109 
11110   if ((-Imm > NumElts) || (Imm >= NumElts)) {
11111     // Result is undefined if immediate is out-of-bounds.
11112     setValue(&I, DAG.getUNDEF(VT));
11113     return;
11114   }
11115 
11116   uint64_t Idx = (NumElts + Imm) % NumElts;
11117 
11118   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11119   SmallVector<int, 8> Mask;
11120   for (unsigned i = 0; i < NumElts; ++i)
11121     Mask.push_back(Idx + i);
11122   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11123 }
11124