xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 002b944dfa3d588b05f967d6b55e6c36ce97d4e5)
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/DiagnosticInfo.h"
73 #include "llvm/IR/Function.h"
74 #include "llvm/IR/GetElementPtrTypeIterator.h"
75 #include "llvm/IR/InlineAsm.h"
76 #include "llvm/IR/InstrTypes.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/Intrinsics.h"
80 #include "llvm/IR/IntrinsicsAArch64.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Module.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Statepoint.h"
88 #include "llvm/IR/Type.h"
89 #include "llvm/IR/User.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/MC/MCContext.h"
92 #include "llvm/MC/MCSymbol.h"
93 #include "llvm/Support/AtomicOrdering.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/MathExtras.h"
99 #include "llvm/Support/raw_ostream.h"
100 #include "llvm/Target/TargetIntrinsicInfo.h"
101 #include "llvm/Target/TargetMachine.h"
102 #include "llvm/Target/TargetOptions.h"
103 #include "llvm/Transforms/Utils/Local.h"
104 #include <cstddef>
105 #include <cstring>
106 #include <iterator>
107 #include <limits>
108 #include <numeric>
109 #include <tuple>
110 
111 using namespace llvm;
112 using namespace PatternMatch;
113 using namespace SwitchCG;
114 
115 #define DEBUG_TYPE "isel"
116 
117 /// LimitFloatPrecision - Generate low-precision inline sequences for
118 /// some float libcalls (6, 8 or 12 bits).
119 static unsigned LimitFloatPrecision;
120 
121 static cl::opt<bool>
122     InsertAssertAlign("insert-assert-align", cl::init(true),
123                       cl::desc("Insert the experimental `assertalign` node."),
124                       cl::ReallyHidden);
125 
126 static cl::opt<unsigned, true>
127     LimitFPPrecision("limit-float-precision",
128                      cl::desc("Generate low-precision inline sequences "
129                               "for some float libcalls"),
130                      cl::location(LimitFloatPrecision), cl::Hidden,
131                      cl::init(0));
132 
133 static cl::opt<unsigned> SwitchPeelThreshold(
134     "switch-peel-threshold", cl::Hidden, cl::init(66),
135     cl::desc("Set the case probability threshold for peeling the case from a "
136              "switch statement. A value greater than 100 will void this "
137              "optimization"));
138 
139 // Limit the width of DAG chains. This is important in general to prevent
140 // DAG-based analysis from blowing up. For example, alias analysis and
141 // load clustering may not complete in reasonable time. It is difficult to
142 // recognize and avoid this situation within each individual analysis, and
143 // future analyses are likely to have the same behavior. Limiting DAG width is
144 // the safe approach and will be especially important with global DAGs.
145 //
146 // MaxParallelChains default is arbitrarily high to avoid affecting
147 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
148 // sequence over this should have been converted to llvm.memcpy by the
149 // frontend. It is easy to induce this behavior with .ll code such as:
150 // %buffer = alloca [4096 x i8]
151 // %data = load [4096 x i8]* %argPtr
152 // store [4096 x i8] %data, [4096 x i8]* %buffer
153 static const unsigned MaxParallelChains = 64;
154 
155 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
156                                       const SDValue *Parts, unsigned NumParts,
157                                       MVT PartVT, EVT ValueVT, const Value *V,
158                                       Optional<CallingConv::ID> CC);
159 
160 /// getCopyFromParts - Create a value that contains the specified legal parts
161 /// combined into the value they represent.  If the parts combine to a type
162 /// larger than ValueVT then AssertOp can be used to specify whether the extra
163 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164 /// (ISD::AssertSext).
165 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
166                                 const SDValue *Parts, unsigned NumParts,
167                                 MVT PartVT, EVT ValueVT, const Value *V,
168                                 Optional<CallingConv::ID> CC = None,
169                                 Optional<ISD::NodeType> AssertOp = None) {
170   // Let the target assemble the parts if it wants to
171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
172   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
173                                                    PartVT, ValueVT, CC))
174     return Val;
175 
176   if (ValueVT.isVector())
177     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
178                                   CC);
179 
180   assert(NumParts > 0 && "No parts to assemble!");
181   SDValue Val = Parts[0];
182 
183   if (NumParts > 1) {
184     // Assemble the value from multiple parts.
185     if (ValueVT.isInteger()) {
186       unsigned PartBits = PartVT.getSizeInBits();
187       unsigned ValueBits = ValueVT.getSizeInBits();
188 
189       // Assemble the power of 2 part.
190       unsigned RoundParts =
191           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
192       unsigned RoundBits = PartBits * RoundParts;
193       EVT RoundVT = RoundBits == ValueBits ?
194         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
195       SDValue Lo, Hi;
196 
197       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
198 
199       if (RoundParts > 2) {
200         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
201                               PartVT, HalfVT, V);
202         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
203                               RoundParts / 2, PartVT, HalfVT, V);
204       } else {
205         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
206         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
207       }
208 
209       if (DAG.getDataLayout().isBigEndian())
210         std::swap(Lo, Hi);
211 
212       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
213 
214       if (RoundParts < NumParts) {
215         // Assemble the trailing non-power-of-2 part.
216         unsigned OddParts = NumParts - RoundParts;
217         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
218         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
219                               OddVT, V, CC);
220 
221         // Combine the round and odd parts.
222         Lo = Val;
223         if (DAG.getDataLayout().isBigEndian())
224           std::swap(Lo, Hi);
225         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
226         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
227         Hi =
228             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
229                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
230                                         TLI.getPointerTy(DAG.getDataLayout())));
231         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
232         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
233       }
234     } else if (PartVT.isFloatingPoint()) {
235       // FP split into multiple FP parts (for ppcf128)
236       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
237              "Unexpected split");
238       SDValue Lo, Hi;
239       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
240       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
241       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
242         std::swap(Lo, Hi);
243       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
244     } else {
245       // FP split into integer parts (soft fp)
246       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
247              !PartVT.isVector() && "Unexpected split");
248       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
249       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
250     }
251   }
252 
253   // There is now one part, held in Val.  Correct it to match ValueVT.
254   // PartEVT is the type of the register class that holds the value.
255   // ValueVT is the type of the inline asm operation.
256   EVT PartEVT = Val.getValueType();
257 
258   if (PartEVT == ValueVT)
259     return Val;
260 
261   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262       ValueVT.bitsLT(PartEVT)) {
263     // For an FP value in an integer part, we need to truncate to the right
264     // width first.
265     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
266     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
267   }
268 
269   // Handle types that have the same size.
270   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
272 
273   // Handle types with different sizes.
274   if (PartEVT.isInteger() && ValueVT.isInteger()) {
275     if (ValueVT.bitsLT(PartEVT)) {
276       // For a truncate, see if we have any information to
277       // indicate whether the truncated bits will always be
278       // zero or sign-extension.
279       if (AssertOp.hasValue())
280         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
281                           DAG.getValueType(ValueVT));
282       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
283     }
284     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
285   }
286 
287   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288     // FP_ROUND's are always exact here.
289     if (ValueVT.bitsLT(Val.getValueType()))
290       return DAG.getNode(
291           ISD::FP_ROUND, DL, ValueVT, Val,
292           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
293 
294     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
295   }
296 
297   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
298   // then truncating.
299   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
300       ValueVT.bitsLT(PartEVT)) {
301     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
302     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
303   }
304 
305   report_fatal_error("Unknown mismatch in getCopyFromParts!");
306 }
307 
308 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
309                                               const Twine &ErrMsg) {
310   const Instruction *I = dyn_cast_or_null<Instruction>(V);
311   if (!V)
312     return Ctx.emitError(ErrMsg);
313 
314   const char *AsmError = ", possible invalid constraint for vector type";
315   if (const CallInst *CI = dyn_cast<CallInst>(I))
316     if (CI->isInlineAsm())
317       return Ctx.emitError(I, ErrMsg + AsmError);
318 
319   return Ctx.emitError(I, ErrMsg);
320 }
321 
322 /// getCopyFromPartsVector - Create a value that contains the specified legal
323 /// parts combined into the value they represent.  If the parts combine to a
324 /// type larger than ValueVT then AssertOp can be used to specify whether the
325 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
326 /// ValueVT (ISD::AssertSext).
327 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
328                                       const SDValue *Parts, unsigned NumParts,
329                                       MVT PartVT, EVT ValueVT, const Value *V,
330                                       Optional<CallingConv::ID> CallConv) {
331   assert(ValueVT.isVector() && "Not a vector value");
332   assert(NumParts > 0 && "No parts to assemble!");
333   const bool IsABIRegCopy = CallConv.hasValue();
334 
335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
336   SDValue Val = Parts[0];
337 
338   // Handle a multi-element vector.
339   if (NumParts > 1) {
340     EVT IntermediateVT;
341     MVT RegisterVT;
342     unsigned NumIntermediates;
343     unsigned NumRegs;
344 
345     if (IsABIRegCopy) {
346       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
347           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
348           NumIntermediates, RegisterVT);
349     } else {
350       NumRegs =
351           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
352                                      NumIntermediates, RegisterVT);
353     }
354 
355     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
356     NumParts = NumRegs; // Silence a compiler warning.
357     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
358     assert(RegisterVT.getSizeInBits() ==
359            Parts[0].getSimpleValueType().getSizeInBits() &&
360            "Part type sizes don't match!");
361 
362     // Assemble the parts into intermediate operands.
363     SmallVector<SDValue, 8> Ops(NumIntermediates);
364     if (NumIntermediates == NumParts) {
365       // If the register was not expanded, truncate or copy the value,
366       // as appropriate.
367       for (unsigned i = 0; i != NumParts; ++i)
368         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
369                                   PartVT, IntermediateVT, V, CallConv);
370     } else if (NumParts > 0) {
371       // If the intermediate type was expanded, build the intermediate
372       // operands from the parts.
373       assert(NumParts % NumIntermediates == 0 &&
374              "Must expand into a divisible number of parts!");
375       unsigned Factor = NumParts / NumIntermediates;
376       for (unsigned i = 0; i != NumIntermediates; ++i)
377         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
378                                   PartVT, IntermediateVT, V, CallConv);
379     }
380 
381     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
382     // intermediate operands.
383     EVT BuiltVectorTy =
384         IntermediateVT.isVector()
385             ? EVT::getVectorVT(
386                   *DAG.getContext(), IntermediateVT.getScalarType(),
387                   IntermediateVT.getVectorElementCount() * NumParts)
388             : EVT::getVectorVT(*DAG.getContext(),
389                                IntermediateVT.getScalarType(),
390                                NumIntermediates);
391     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
392                                                 : ISD::BUILD_VECTOR,
393                       DL, BuiltVectorTy, Ops);
394   }
395 
396   // There is now one part, held in Val.  Correct it to match ValueVT.
397   EVT PartEVT = Val.getValueType();
398 
399   if (PartEVT == ValueVT)
400     return Val;
401 
402   if (PartEVT.isVector()) {
403     // Vector/Vector bitcast.
404     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
405       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
406 
407     // If the element type of the source/dest vectors are the same, but the
408     // parts vector has more elements than the value vector, then we have a
409     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
410     // elements we want.
411     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
412       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
413               ValueVT.getVectorElementCount().getKnownMinValue()) &&
414              (PartEVT.getVectorElementCount().isScalable() ==
415               ValueVT.getVectorElementCount().isScalable()) &&
416              "Cannot narrow, it would be a lossy transformation");
417       PartEVT =
418           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
419                            ValueVT.getVectorElementCount());
420       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
421                         DAG.getVectorIdxConstant(0, DL));
422       if (PartEVT == ValueVT)
423         return Val;
424     }
425 
426     // Promoted vector extract
427     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
428   }
429 
430   // Trivial bitcast if the types are the same size and the destination
431   // vector type is legal.
432   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
433       TLI.isTypeLegal(ValueVT))
434     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
435 
436   if (ValueVT.getVectorNumElements() != 1) {
437      // Certain ABIs require that vectors are passed as integers. For vectors
438      // are the same size, this is an obvious bitcast.
439      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
440        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
441      } else if (ValueVT.bitsLT(PartEVT)) {
442        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
443        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
444        // Drop the extra bits.
445        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
446        return DAG.getBitcast(ValueVT, Val);
447      }
448 
449      diagnosePossiblyInvalidConstraint(
450          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
451      return DAG.getUNDEF(ValueVT);
452   }
453 
454   // Handle cases such as i8 -> <1 x i1>
455   EVT ValueSVT = ValueVT.getVectorElementType();
456   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
457     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
458       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
459     else
460       Val = ValueVT.isFloatingPoint()
461                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
462                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
463   }
464 
465   return DAG.getBuildVector(ValueVT, DL, Val);
466 }
467 
468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
469                                  SDValue Val, SDValue *Parts, unsigned NumParts,
470                                  MVT PartVT, const Value *V,
471                                  Optional<CallingConv::ID> CallConv);
472 
473 /// getCopyToParts - Create a series of nodes that contain the specified value
474 /// split into legal parts.  If the parts contain more bits than Val, then, for
475 /// integers, ExtendKind can be used to specify how to generate the extra bits.
476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
477                            SDValue *Parts, unsigned NumParts, MVT PartVT,
478                            const Value *V,
479                            Optional<CallingConv::ID> CallConv = None,
480                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
481   // Let the target split the parts if it wants to
482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
483   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
484                                       CallConv))
485     return;
486   EVT ValueVT = Val.getValueType();
487 
488   // Handle the vector case separately.
489   if (ValueVT.isVector())
490     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
491                                 CallConv);
492 
493   unsigned PartBits = PartVT.getSizeInBits();
494   unsigned OrigNumParts = NumParts;
495   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
496          "Copying to an illegal type!");
497 
498   if (NumParts == 0)
499     return;
500 
501   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
502   EVT PartEVT = PartVT;
503   if (PartEVT == ValueVT) {
504     assert(NumParts == 1 && "No-op copy with multiple parts!");
505     Parts[0] = Val;
506     return;
507   }
508 
509   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
510     // If the parts cover more bits than the value has, promote the value.
511     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
512       assert(NumParts == 1 && "Do not know what to promote to!");
513       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
514     } else {
515       if (ValueVT.isFloatingPoint()) {
516         // FP values need to be bitcast, then extended if they are being put
517         // into a larger container.
518         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
519         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
520       }
521       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
522              ValueVT.isInteger() &&
523              "Unknown mismatch!");
524       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
525       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
526       if (PartVT == MVT::x86mmx)
527         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
528     }
529   } else if (PartBits == ValueVT.getSizeInBits()) {
530     // Different types of the same size.
531     assert(NumParts == 1 && PartEVT != ValueVT);
532     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
533   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
534     // If the parts cover less bits than value has, truncate the value.
535     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
536            ValueVT.isInteger() &&
537            "Unknown mismatch!");
538     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
539     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
540     if (PartVT == MVT::x86mmx)
541       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
542   }
543 
544   // The value may have changed - recompute ValueVT.
545   ValueVT = Val.getValueType();
546   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
547          "Failed to tile the value with PartVT!");
548 
549   if (NumParts == 1) {
550     if (PartEVT != ValueVT) {
551       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
552                                         "scalar-to-vector conversion failed");
553       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554     }
555 
556     Parts[0] = Val;
557     return;
558   }
559 
560   // Expand the value into multiple parts.
561   if (NumParts & (NumParts - 1)) {
562     // The number of parts is not a power of 2.  Split off and copy the tail.
563     assert(PartVT.isInteger() && ValueVT.isInteger() &&
564            "Do not know what to expand to!");
565     unsigned RoundParts = 1 << Log2_32(NumParts);
566     unsigned RoundBits = RoundParts * PartBits;
567     unsigned OddParts = NumParts - RoundParts;
568     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
569       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
570 
571     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
572                    CallConv);
573 
574     if (DAG.getDataLayout().isBigEndian())
575       // The odd parts were reversed by getCopyToParts - unreverse them.
576       std::reverse(Parts + RoundParts, Parts + NumParts);
577 
578     NumParts = RoundParts;
579     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
580     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
581   }
582 
583   // The number of parts is a power of 2.  Repeatedly bisect the value using
584   // EXTRACT_ELEMENT.
585   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
586                          EVT::getIntegerVT(*DAG.getContext(),
587                                            ValueVT.getSizeInBits()),
588                          Val);
589 
590   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
591     for (unsigned i = 0; i < NumParts; i += StepSize) {
592       unsigned ThisBits = StepSize * PartBits / 2;
593       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
594       SDValue &Part0 = Parts[i];
595       SDValue &Part1 = Parts[i+StepSize/2];
596 
597       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
598                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
599       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
600                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
601 
602       if (ThisBits == PartBits && ThisVT != PartVT) {
603         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
604         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
605       }
606     }
607   }
608 
609   if (DAG.getDataLayout().isBigEndian())
610     std::reverse(Parts, Parts + OrigNumParts);
611 }
612 
613 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
614                                      const SDLoc &DL, EVT PartVT) {
615   if (!PartVT.isVector())
616     return SDValue();
617 
618   EVT ValueVT = Val.getValueType();
619   ElementCount PartNumElts = PartVT.getVectorElementCount();
620   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
621 
622   // We only support widening vectors with equivalent element types and
623   // fixed/scalable properties. If a target needs to widen a fixed-length type
624   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
625   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
626       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
627       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
628     return SDValue();
629 
630   // Widening a scalable vector to another scalable vector is done by inserting
631   // the vector into a larger undef one.
632   if (PartNumElts.isScalable())
633     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
634                        Val, DAG.getVectorIdxConstant(0, DL));
635 
636   EVT ElementVT = PartVT.getVectorElementType();
637   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
638   // undef elements.
639   SmallVector<SDValue, 16> Ops;
640   DAG.ExtractVectorElements(Val, Ops);
641   SDValue EltUndef = DAG.getUNDEF(ElementVT);
642   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
643 
644   // FIXME: Use CONCAT for 2x -> 4x.
645   return DAG.getBuildVector(PartVT, DL, Ops);
646 }
647 
648 /// getCopyToPartsVector - Create a series of nodes that contain the specified
649 /// value split into legal parts.
650 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
651                                  SDValue Val, SDValue *Parts, unsigned NumParts,
652                                  MVT PartVT, const Value *V,
653                                  Optional<CallingConv::ID> CallConv) {
654   EVT ValueVT = Val.getValueType();
655   assert(ValueVT.isVector() && "Not a vector");
656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
657   const bool IsABIRegCopy = CallConv.hasValue();
658 
659   if (NumParts == 1) {
660     EVT PartEVT = PartVT;
661     if (PartEVT == ValueVT) {
662       // Nothing to do.
663     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
664       // Bitconvert vector->vector case.
665       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
666     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
667       Val = Widened;
668     } else if (PartVT.isVector() &&
669                PartEVT.getVectorElementType().bitsGE(
670                    ValueVT.getVectorElementType()) &&
671                PartEVT.getVectorElementCount() ==
672                    ValueVT.getVectorElementCount()) {
673 
674       // Promoted vector extract
675       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
676     } else if (PartEVT.isVector() &&
677                PartEVT.getVectorElementType() !=
678                    ValueVT.getVectorElementType() &&
679                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
680                    TargetLowering::TypeWidenVector) {
681       // Combination of widening and promotion.
682       EVT WidenVT =
683           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
684                            PartVT.getVectorElementCount());
685       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
686       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
687     } else {
688       if (ValueVT.getVectorElementCount().isScalar()) {
689         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
690                           DAG.getVectorIdxConstant(0, DL));
691       } else {
692         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
693         assert(PartVT.getFixedSizeInBits() > ValueSize &&
694                "lossy conversion of vector to scalar type");
695         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
696         Val = DAG.getBitcast(IntermediateType, Val);
697         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
698       }
699     }
700 
701     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
702     Parts[0] = Val;
703     return;
704   }
705 
706   // Handle a multi-element vector.
707   EVT IntermediateVT;
708   MVT RegisterVT;
709   unsigned NumIntermediates;
710   unsigned NumRegs;
711   if (IsABIRegCopy) {
712     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
713         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
714         NumIntermediates, RegisterVT);
715   } else {
716     NumRegs =
717         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
718                                    NumIntermediates, RegisterVT);
719   }
720 
721   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
722   NumParts = NumRegs; // Silence a compiler warning.
723   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
724 
725   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
726          "Mixing scalable and fixed vectors when copying in parts");
727 
728   Optional<ElementCount> DestEltCnt;
729 
730   if (IntermediateVT.isVector())
731     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
732   else
733     DestEltCnt = ElementCount::getFixed(NumIntermediates);
734 
735   EVT BuiltVectorTy = EVT::getVectorVT(
736       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
737 
738   if (ValueVT == BuiltVectorTy) {
739     // Nothing to do.
740   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
741     // Bitconvert vector->vector case.
742     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
743   } else {
744     if (BuiltVectorTy.getVectorElementType().bitsGT(
745             ValueVT.getVectorElementType())) {
746       // Integer promotion.
747       ValueVT = EVT::getVectorVT(*DAG.getContext(),
748                                  BuiltVectorTy.getVectorElementType(),
749                                  ValueVT.getVectorElementCount());
750       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
751     }
752 
753     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
754       Val = Widened;
755     }
756   }
757 
758   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
759 
760   // Split the vector into intermediate operands.
761   SmallVector<SDValue, 8> Ops(NumIntermediates);
762   for (unsigned i = 0; i != NumIntermediates; ++i) {
763     if (IntermediateVT.isVector()) {
764       // This does something sensible for scalable vectors - see the
765       // definition of EXTRACT_SUBVECTOR for further details.
766       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
767       Ops[i] =
768           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
769                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
770     } else {
771       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
772                            DAG.getVectorIdxConstant(i, DL));
773     }
774   }
775 
776   // Split the intermediate operands into legal parts.
777   if (NumParts == NumIntermediates) {
778     // If the register was not expanded, promote or copy the value,
779     // as appropriate.
780     for (unsigned i = 0; i != NumParts; ++i)
781       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
782   } else if (NumParts > 0) {
783     // If the intermediate type was expanded, split each the value into
784     // legal parts.
785     assert(NumIntermediates != 0 && "division by zero");
786     assert(NumParts % NumIntermediates == 0 &&
787            "Must expand into a divisible number of parts!");
788     unsigned Factor = NumParts / NumIntermediates;
789     for (unsigned i = 0; i != NumIntermediates; ++i)
790       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
791                      CallConv);
792   }
793 }
794 
795 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
796                            EVT valuevt, Optional<CallingConv::ID> CC)
797     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
798       RegCount(1, regs.size()), CallConv(CC) {}
799 
800 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
801                            const DataLayout &DL, unsigned Reg, Type *Ty,
802                            Optional<CallingConv::ID> CC) {
803   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
804 
805   CallConv = CC;
806 
807   for (EVT ValueVT : ValueVTs) {
808     unsigned NumRegs =
809         isABIMangled()
810             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
811             : TLI.getNumRegisters(Context, ValueVT);
812     MVT RegisterVT =
813         isABIMangled()
814             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
815             : TLI.getRegisterType(Context, ValueVT);
816     for (unsigned i = 0; i != NumRegs; ++i)
817       Regs.push_back(Reg + i);
818     RegVTs.push_back(RegisterVT);
819     RegCount.push_back(NumRegs);
820     Reg += NumRegs;
821   }
822 }
823 
824 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
825                                       FunctionLoweringInfo &FuncInfo,
826                                       const SDLoc &dl, SDValue &Chain,
827                                       SDValue *Flag, const Value *V) const {
828   // A Value with type {} or [0 x %t] needs no registers.
829   if (ValueVTs.empty())
830     return SDValue();
831 
832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
833 
834   // Assemble the legal parts into the final values.
835   SmallVector<SDValue, 4> Values(ValueVTs.size());
836   SmallVector<SDValue, 8> Parts;
837   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
838     // Copy the legal parts from the registers.
839     EVT ValueVT = ValueVTs[Value];
840     unsigned NumRegs = RegCount[Value];
841     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
842                                           *DAG.getContext(),
843                                           CallConv.getValue(), RegVTs[Value])
844                                     : RegVTs[Value];
845 
846     Parts.resize(NumRegs);
847     for (unsigned i = 0; i != NumRegs; ++i) {
848       SDValue P;
849       if (!Flag) {
850         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
851       } else {
852         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
853         *Flag = P.getValue(2);
854       }
855 
856       Chain = P.getValue(1);
857       Parts[i] = P;
858 
859       // If the source register was virtual and if we know something about it,
860       // add an assert node.
861       if (!Register::isVirtualRegister(Regs[Part + i]) ||
862           !RegisterVT.isInteger())
863         continue;
864 
865       const FunctionLoweringInfo::LiveOutInfo *LOI =
866         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
867       if (!LOI)
868         continue;
869 
870       unsigned RegSize = RegisterVT.getScalarSizeInBits();
871       unsigned NumSignBits = LOI->NumSignBits;
872       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
873 
874       if (NumZeroBits == RegSize) {
875         // The current value is a zero.
876         // Explicitly express that as it would be easier for
877         // optimizations to kick in.
878         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
879         continue;
880       }
881 
882       // FIXME: We capture more information than the dag can represent.  For
883       // now, just use the tightest assertzext/assertsext possible.
884       bool isSExt;
885       EVT FromVT(MVT::Other);
886       if (NumZeroBits) {
887         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
888         isSExt = false;
889       } else if (NumSignBits > 1) {
890         FromVT =
891             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
892         isSExt = true;
893       } else {
894         continue;
895       }
896       // Add an assertion node.
897       assert(FromVT != MVT::Other);
898       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
899                              RegisterVT, P, DAG.getValueType(FromVT));
900     }
901 
902     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
903                                      RegisterVT, ValueVT, V, CallConv);
904     Part += NumRegs;
905     Parts.clear();
906   }
907 
908   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
909 }
910 
911 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
912                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
913                                  const Value *V,
914                                  ISD::NodeType PreferredExtendType) const {
915   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
916   ISD::NodeType ExtendKind = PreferredExtendType;
917 
918   // Get the list of the values's legal parts.
919   unsigned NumRegs = Regs.size();
920   SmallVector<SDValue, 8> Parts(NumRegs);
921   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
922     unsigned NumParts = RegCount[Value];
923 
924     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
925                                           *DAG.getContext(),
926                                           CallConv.getValue(), RegVTs[Value])
927                                     : RegVTs[Value];
928 
929     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
930       ExtendKind = ISD::ZERO_EXTEND;
931 
932     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
933                    NumParts, RegisterVT, V, CallConv, ExtendKind);
934     Part += NumParts;
935   }
936 
937   // Copy the parts into the registers.
938   SmallVector<SDValue, 8> Chains(NumRegs);
939   for (unsigned i = 0; i != NumRegs; ++i) {
940     SDValue Part;
941     if (!Flag) {
942       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
943     } else {
944       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
945       *Flag = Part.getValue(1);
946     }
947 
948     Chains[i] = Part.getValue(0);
949   }
950 
951   if (NumRegs == 1 || Flag)
952     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
953     // flagged to it. That is the CopyToReg nodes and the user are considered
954     // a single scheduling unit. If we create a TokenFactor and return it as
955     // chain, then the TokenFactor is both a predecessor (operand) of the
956     // user as well as a successor (the TF operands are flagged to the user).
957     // c1, f1 = CopyToReg
958     // c2, f2 = CopyToReg
959     // c3     = TokenFactor c1, c2
960     // ...
961     //        = op c3, ..., f2
962     Chain = Chains[NumRegs-1];
963   else
964     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
965 }
966 
967 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
968                                         unsigned MatchingIdx, const SDLoc &dl,
969                                         SelectionDAG &DAG,
970                                         std::vector<SDValue> &Ops) const {
971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
972 
973   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
974   if (HasMatching)
975     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
976   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
977     // Put the register class of the virtual registers in the flag word.  That
978     // way, later passes can recompute register class constraints for inline
979     // assembly as well as normal instructions.
980     // Don't do this for tied operands that can use the regclass information
981     // from the def.
982     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
983     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
984     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
985   }
986 
987   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
988   Ops.push_back(Res);
989 
990   if (Code == InlineAsm::Kind_Clobber) {
991     // Clobbers should always have a 1:1 mapping with registers, and may
992     // reference registers that have illegal (e.g. vector) types. Hence, we
993     // shouldn't try to apply any sort of splitting logic to them.
994     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
995            "No 1:1 mapping from clobbers to regs?");
996     Register SP = TLI.getStackPointerRegisterToSaveRestore();
997     (void)SP;
998     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
999       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1000       assert(
1001           (Regs[I] != SP ||
1002            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1003           "If we clobbered the stack pointer, MFI should know about it.");
1004     }
1005     return;
1006   }
1007 
1008   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1009     MVT RegisterVT = RegVTs[Value];
1010     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1011                                            RegisterVT);
1012     for (unsigned i = 0; i != NumRegs; ++i) {
1013       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1014       unsigned TheReg = Regs[Reg++];
1015       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1016     }
1017   }
1018 }
1019 
1020 SmallVector<std::pair<unsigned, TypeSize>, 4>
1021 RegsForValue::getRegsAndSizes() const {
1022   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1023   unsigned I = 0;
1024   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1025     unsigned RegCount = std::get<0>(CountAndVT);
1026     MVT RegisterVT = std::get<1>(CountAndVT);
1027     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1028     for (unsigned E = I + RegCount; I != E; ++I)
1029       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1030   }
1031   return OutVec;
1032 }
1033 
1034 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1035                                const TargetLibraryInfo *li) {
1036   AA = aa;
1037   GFI = gfi;
1038   LibInfo = li;
1039   Context = DAG.getContext();
1040   LPadToCallSiteMap.clear();
1041   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1042 }
1043 
1044 void SelectionDAGBuilder::clear() {
1045   NodeMap.clear();
1046   UnusedArgNodeMap.clear();
1047   PendingLoads.clear();
1048   PendingExports.clear();
1049   PendingConstrainedFP.clear();
1050   PendingConstrainedFPStrict.clear();
1051   CurInst = nullptr;
1052   HasTailCall = false;
1053   SDNodeOrder = LowestSDNodeOrder;
1054   StatepointLowering.clear();
1055 }
1056 
1057 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1058   DanglingDebugInfoMap.clear();
1059 }
1060 
1061 // Update DAG root to include dependencies on Pending chains.
1062 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1063   SDValue Root = DAG.getRoot();
1064 
1065   if (Pending.empty())
1066     return Root;
1067 
1068   // Add current root to PendingChains, unless we already indirectly
1069   // depend on it.
1070   if (Root.getOpcode() != ISD::EntryToken) {
1071     unsigned i = 0, e = Pending.size();
1072     for (; i != e; ++i) {
1073       assert(Pending[i].getNode()->getNumOperands() > 1);
1074       if (Pending[i].getNode()->getOperand(0) == Root)
1075         break;  // Don't add the root if we already indirectly depend on it.
1076     }
1077 
1078     if (i == e)
1079       Pending.push_back(Root);
1080   }
1081 
1082   if (Pending.size() == 1)
1083     Root = Pending[0];
1084   else
1085     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1086 
1087   DAG.setRoot(Root);
1088   Pending.clear();
1089   return Root;
1090 }
1091 
1092 SDValue SelectionDAGBuilder::getMemoryRoot() {
1093   return updateRoot(PendingLoads);
1094 }
1095 
1096 SDValue SelectionDAGBuilder::getRoot() {
1097   // Chain up all pending constrained intrinsics together with all
1098   // pending loads, by simply appending them to PendingLoads and
1099   // then calling getMemoryRoot().
1100   PendingLoads.reserve(PendingLoads.size() +
1101                        PendingConstrainedFP.size() +
1102                        PendingConstrainedFPStrict.size());
1103   PendingLoads.append(PendingConstrainedFP.begin(),
1104                       PendingConstrainedFP.end());
1105   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1106                       PendingConstrainedFPStrict.end());
1107   PendingConstrainedFP.clear();
1108   PendingConstrainedFPStrict.clear();
1109   return getMemoryRoot();
1110 }
1111 
1112 SDValue SelectionDAGBuilder::getControlRoot() {
1113   // We need to emit pending fpexcept.strict constrained intrinsics,
1114   // so append them to the PendingExports list.
1115   PendingExports.append(PendingConstrainedFPStrict.begin(),
1116                         PendingConstrainedFPStrict.end());
1117   PendingConstrainedFPStrict.clear();
1118   return updateRoot(PendingExports);
1119 }
1120 
1121 void SelectionDAGBuilder::visit(const Instruction &I) {
1122   // Set up outgoing PHI node register values before emitting the terminator.
1123   if (I.isTerminator()) {
1124     HandlePHINodesInSuccessorBlocks(I.getParent());
1125   }
1126 
1127   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1128   if (!isa<DbgInfoIntrinsic>(I))
1129     ++SDNodeOrder;
1130 
1131   CurInst = &I;
1132 
1133   visit(I.getOpcode(), I);
1134 
1135   if (!I.isTerminator() && !HasTailCall &&
1136       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1137     CopyToExportRegsIfNeeded(&I);
1138 
1139   CurInst = nullptr;
1140 }
1141 
1142 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1143   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1144 }
1145 
1146 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1147   // Note: this doesn't use InstVisitor, because it has to work with
1148   // ConstantExpr's in addition to instructions.
1149   switch (Opcode) {
1150   default: llvm_unreachable("Unknown instruction type encountered!");
1151     // Build the switch statement using the Instruction.def file.
1152 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1153     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1154 #include "llvm/IR/Instruction.def"
1155   }
1156 }
1157 
1158 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1159                                                DebugLoc DL, unsigned Order) {
1160   // We treat variadic dbg_values differently at this stage.
1161   if (DI->hasArgList()) {
1162     // For variadic dbg_values we will now insert an undef.
1163     // FIXME: We can potentially recover these!
1164     SmallVector<SDDbgOperand, 2> Locs;
1165     for (const Value *V : DI->getValues()) {
1166       auto Undef = UndefValue::get(V->getType());
1167       Locs.push_back(SDDbgOperand::fromConst(Undef));
1168     }
1169     SDDbgValue *SDV = DAG.getDbgValueList(
1170         DI->getVariable(), DI->getExpression(), Locs, {},
1171         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1172     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1173   } else {
1174     // TODO: Dangling debug info will eventually either be resolved or produce
1175     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1176     // between the original dbg.value location and its resolved DBG_VALUE,
1177     // which we should ideally fill with an extra Undef DBG_VALUE.
1178     assert(DI->getNumVariableLocationOps() == 1 &&
1179            "DbgValueInst without an ArgList should have a single location "
1180            "operand.");
1181     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1182   }
1183 }
1184 
1185 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1186                                                 const DIExpression *Expr) {
1187   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1188     const DbgValueInst *DI = DDI.getDI();
1189     DIVariable *DanglingVariable = DI->getVariable();
1190     DIExpression *DanglingExpr = DI->getExpression();
1191     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1192       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1193       return true;
1194     }
1195     return false;
1196   };
1197 
1198   for (auto &DDIMI : DanglingDebugInfoMap) {
1199     DanglingDebugInfoVector &DDIV = DDIMI.second;
1200 
1201     // If debug info is to be dropped, run it through final checks to see
1202     // whether it can be salvaged.
1203     for (auto &DDI : DDIV)
1204       if (isMatchingDbgValue(DDI))
1205         salvageUnresolvedDbgValue(DDI);
1206 
1207     erase_if(DDIV, isMatchingDbgValue);
1208   }
1209 }
1210 
1211 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1212 // generate the debug data structures now that we've seen its definition.
1213 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1214                                                    SDValue Val) {
1215   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1216   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1217     return;
1218 
1219   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1220   for (auto &DDI : DDIV) {
1221     const DbgValueInst *DI = DDI.getDI();
1222     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1223     assert(DI && "Ill-formed DanglingDebugInfo");
1224     DebugLoc dl = DDI.getdl();
1225     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1226     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1227     DILocalVariable *Variable = DI->getVariable();
1228     DIExpression *Expr = DI->getExpression();
1229     assert(Variable->isValidLocationForIntrinsic(dl) &&
1230            "Expected inlined-at fields to agree");
1231     SDDbgValue *SDV;
1232     if (Val.getNode()) {
1233       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1234       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1235       // we couldn't resolve it directly when examining the DbgValue intrinsic
1236       // in the first place we should not be more successful here). Unless we
1237       // have some test case that prove this to be correct we should avoid
1238       // calling EmitFuncArgumentDbgValue here.
1239       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1240         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1241                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1242         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1243         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1244         // inserted after the definition of Val when emitting the instructions
1245         // after ISel. An alternative could be to teach
1246         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1247         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1248                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1249                    << ValSDNodeOrder << "\n");
1250         SDV = getDbgValue(Val, Variable, Expr, dl,
1251                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1252         DAG.AddDbgValue(SDV, false);
1253       } else
1254         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1255                           << "in EmitFuncArgumentDbgValue\n");
1256     } else {
1257       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1258       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1259       auto SDV =
1260           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1261       DAG.AddDbgValue(SDV, false);
1262     }
1263   }
1264   DDIV.clear();
1265 }
1266 
1267 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1268   // TODO: For the variadic implementation, instead of only checking the fail
1269   // state of `handleDebugValue`, we need know specifically which values were
1270   // invalid, so that we attempt to salvage only those values when processing
1271   // a DIArgList.
1272   assert(!DDI.getDI()->hasArgList() &&
1273          "Not implemented for variadic dbg_values");
1274   Value *V = DDI.getDI()->getValue(0);
1275   DILocalVariable *Var = DDI.getDI()->getVariable();
1276   DIExpression *Expr = DDI.getDI()->getExpression();
1277   DebugLoc DL = DDI.getdl();
1278   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1279   unsigned SDOrder = DDI.getSDNodeOrder();
1280   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1281   // that DW_OP_stack_value is desired.
1282   assert(isa<DbgValueInst>(DDI.getDI()));
1283   bool StackValue = true;
1284 
1285   // Can this Value can be encoded without any further work?
1286   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1287     return;
1288 
1289   // Attempt to salvage back through as many instructions as possible. Bail if
1290   // a non-instruction is seen, such as a constant expression or global
1291   // variable. FIXME: Further work could recover those too.
1292   while (isa<Instruction>(V)) {
1293     Instruction &VAsInst = *cast<Instruction>(V);
1294     // Temporary "0", awaiting real implementation.
1295     SmallVector<uint64_t, 16> Ops;
1296     SmallVector<Value *, 4> AdditionalValues;
1297     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1298                              AdditionalValues);
1299     // If we cannot salvage any further, and haven't yet found a suitable debug
1300     // expression, bail out.
1301     if (!V)
1302       break;
1303 
1304     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1305     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1306     // here for variadic dbg_values, remove that condition.
1307     if (!AdditionalValues.empty())
1308       break;
1309 
1310     // New value and expr now represent this debuginfo.
1311     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1312 
1313     // Some kind of simplification occurred: check whether the operand of the
1314     // salvaged debug expression can be encoded in this DAG.
1315     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1316                          /*IsVariadic=*/false)) {
1317       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1318                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1319       return;
1320     }
1321   }
1322 
1323   // This was the final opportunity to salvage this debug information, and it
1324   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1325   // any earlier variable location.
1326   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1327   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1328   DAG.AddDbgValue(SDV, false);
1329 
1330   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1331                     << "\n");
1332   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1333                     << "\n");
1334 }
1335 
1336 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1337                                            DILocalVariable *Var,
1338                                            DIExpression *Expr, DebugLoc dl,
1339                                            DebugLoc InstDL, unsigned Order,
1340                                            bool IsVariadic) {
1341   if (Values.empty())
1342     return true;
1343   SmallVector<SDDbgOperand> LocationOps;
1344   SmallVector<SDNode *> Dependencies;
1345   for (const Value *V : Values) {
1346     // Constant value.
1347     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1348         isa<ConstantPointerNull>(V)) {
1349       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1350       continue;
1351     }
1352 
1353     // If the Value is a frame index, we can create a FrameIndex debug value
1354     // without relying on the DAG at all.
1355     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1356       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1357       if (SI != FuncInfo.StaticAllocaMap.end()) {
1358         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1359         continue;
1360       }
1361     }
1362 
1363     // Do not use getValue() in here; we don't want to generate code at
1364     // this point if it hasn't been done yet.
1365     SDValue N = NodeMap[V];
1366     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1367       N = UnusedArgNodeMap[V];
1368     if (N.getNode()) {
1369       // Only emit func arg dbg value for non-variadic dbg.values for now.
1370       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1371         return true;
1372       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1373         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1374         // describe stack slot locations.
1375         //
1376         // Consider "int x = 0; int *px = &x;". There are two kinds of
1377         // interesting debug values here after optimization:
1378         //
1379         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1380         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1381         //
1382         // Both describe the direct values of their associated variables.
1383         Dependencies.push_back(N.getNode());
1384         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1385         continue;
1386       }
1387       LocationOps.emplace_back(
1388           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1389       continue;
1390     }
1391 
1392     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1393     // Special rules apply for the first dbg.values of parameter variables in a
1394     // function. Identify them by the fact they reference Argument Values, that
1395     // they're parameters, and they are parameters of the current function. We
1396     // need to let them dangle until they get an SDNode.
1397     bool IsParamOfFunc =
1398         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1399     if (IsParamOfFunc)
1400       return false;
1401 
1402     // The value is not used in this block yet (or it would have an SDNode).
1403     // We still want the value to appear for the user if possible -- if it has
1404     // an associated VReg, we can refer to that instead.
1405     auto VMI = FuncInfo.ValueMap.find(V);
1406     if (VMI != FuncInfo.ValueMap.end()) {
1407       unsigned Reg = VMI->second;
1408       // If this is a PHI node, it may be split up into several MI PHI nodes
1409       // (in FunctionLoweringInfo::set).
1410       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1411                        V->getType(), None);
1412       if (RFV.occupiesMultipleRegs()) {
1413         // FIXME: We could potentially support variadic dbg_values here.
1414         if (IsVariadic)
1415           return false;
1416         unsigned Offset = 0;
1417         unsigned BitsToDescribe = 0;
1418         if (auto VarSize = Var->getSizeInBits())
1419           BitsToDescribe = *VarSize;
1420         if (auto Fragment = Expr->getFragmentInfo())
1421           BitsToDescribe = Fragment->SizeInBits;
1422         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1423           // Bail out if all bits are described already.
1424           if (Offset >= BitsToDescribe)
1425             break;
1426           // TODO: handle scalable vectors.
1427           unsigned RegisterSize = RegAndSize.second;
1428           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1429                                       ? BitsToDescribe - Offset
1430                                       : RegisterSize;
1431           auto FragmentExpr = DIExpression::createFragmentExpression(
1432               Expr, Offset, FragmentSize);
1433           if (!FragmentExpr)
1434             continue;
1435           SDDbgValue *SDV = DAG.getVRegDbgValue(
1436               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1437           DAG.AddDbgValue(SDV, false);
1438           Offset += RegisterSize;
1439         }
1440         return true;
1441       }
1442       // We can use simple vreg locations for variadic dbg_values as well.
1443       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1444       continue;
1445     }
1446     // We failed to create a SDDbgOperand for V.
1447     return false;
1448   }
1449 
1450   // We have created a SDDbgOperand for each Value in Values.
1451   // Should use Order instead of SDNodeOrder?
1452   assert(!LocationOps.empty());
1453   SDDbgValue *SDV =
1454       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1455                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1456   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1457   return true;
1458 }
1459 
1460 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1461   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1462   for (auto &Pair : DanglingDebugInfoMap)
1463     for (auto &DDI : Pair.second)
1464       salvageUnresolvedDbgValue(DDI);
1465   clearDanglingDebugInfo();
1466 }
1467 
1468 /// getCopyFromRegs - If there was virtual register allocated for the value V
1469 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1470 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1471   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1472   SDValue Result;
1473 
1474   if (It != FuncInfo.ValueMap.end()) {
1475     Register InReg = It->second;
1476 
1477     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1478                      DAG.getDataLayout(), InReg, Ty,
1479                      None); // This is not an ABI copy.
1480     SDValue Chain = DAG.getEntryNode();
1481     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1482                                  V);
1483     resolveDanglingDebugInfo(V, Result);
1484   }
1485 
1486   return Result;
1487 }
1488 
1489 /// getValue - Return an SDValue for the given Value.
1490 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1491   // If we already have an SDValue for this value, use it. It's important
1492   // to do this first, so that we don't create a CopyFromReg if we already
1493   // have a regular SDValue.
1494   SDValue &N = NodeMap[V];
1495   if (N.getNode()) return N;
1496 
1497   // If there's a virtual register allocated and initialized for this
1498   // value, use it.
1499   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1500     return copyFromReg;
1501 
1502   // Otherwise create a new SDValue and remember it.
1503   SDValue Val = getValueImpl(V);
1504   NodeMap[V] = Val;
1505   resolveDanglingDebugInfo(V, Val);
1506   return Val;
1507 }
1508 
1509 /// getNonRegisterValue - Return an SDValue for the given Value, but
1510 /// don't look in FuncInfo.ValueMap for a virtual register.
1511 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1512   // If we already have an SDValue for this value, use it.
1513   SDValue &N = NodeMap[V];
1514   if (N.getNode()) {
1515     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1516       // Remove the debug location from the node as the node is about to be used
1517       // in a location which may differ from the original debug location.  This
1518       // is relevant to Constant and ConstantFP nodes because they can appear
1519       // as constant expressions inside PHI nodes.
1520       N->setDebugLoc(DebugLoc());
1521     }
1522     return N;
1523   }
1524 
1525   // Otherwise create a new SDValue and remember it.
1526   SDValue Val = getValueImpl(V);
1527   NodeMap[V] = Val;
1528   resolveDanglingDebugInfo(V, Val);
1529   return Val;
1530 }
1531 
1532 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1533 /// Create an SDValue for the given value.
1534 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1536 
1537   if (const Constant *C = dyn_cast<Constant>(V)) {
1538     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1539 
1540     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1541       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1542 
1543     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1544       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1545 
1546     if (isa<ConstantPointerNull>(C)) {
1547       unsigned AS = V->getType()->getPointerAddressSpace();
1548       return DAG.getConstant(0, getCurSDLoc(),
1549                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1550     }
1551 
1552     if (match(C, m_VScale(DAG.getDataLayout())))
1553       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1554 
1555     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1556       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1557 
1558     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1559       return DAG.getUNDEF(VT);
1560 
1561     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1562       visit(CE->getOpcode(), *CE);
1563       SDValue N1 = NodeMap[V];
1564       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1565       return N1;
1566     }
1567 
1568     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1569       SmallVector<SDValue, 4> Constants;
1570       for (const Use &U : C->operands()) {
1571         SDNode *Val = getValue(U).getNode();
1572         // If the operand is an empty aggregate, there are no values.
1573         if (!Val) continue;
1574         // Add each leaf value from the operand to the Constants list
1575         // to form a flattened list of all the values.
1576         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1577           Constants.push_back(SDValue(Val, i));
1578       }
1579 
1580       return DAG.getMergeValues(Constants, getCurSDLoc());
1581     }
1582 
1583     if (const ConstantDataSequential *CDS =
1584           dyn_cast<ConstantDataSequential>(C)) {
1585       SmallVector<SDValue, 4> Ops;
1586       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1587         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1588         // Add each leaf value from the operand to the Constants list
1589         // to form a flattened list of all the values.
1590         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1591           Ops.push_back(SDValue(Val, i));
1592       }
1593 
1594       if (isa<ArrayType>(CDS->getType()))
1595         return DAG.getMergeValues(Ops, getCurSDLoc());
1596       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1597     }
1598 
1599     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1600       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1601              "Unknown struct or array constant!");
1602 
1603       SmallVector<EVT, 4> ValueVTs;
1604       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1605       unsigned NumElts = ValueVTs.size();
1606       if (NumElts == 0)
1607         return SDValue(); // empty struct
1608       SmallVector<SDValue, 4> Constants(NumElts);
1609       for (unsigned i = 0; i != NumElts; ++i) {
1610         EVT EltVT = ValueVTs[i];
1611         if (isa<UndefValue>(C))
1612           Constants[i] = DAG.getUNDEF(EltVT);
1613         else if (EltVT.isFloatingPoint())
1614           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1615         else
1616           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1617       }
1618 
1619       return DAG.getMergeValues(Constants, getCurSDLoc());
1620     }
1621 
1622     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1623       return DAG.getBlockAddress(BA, VT);
1624 
1625     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1626       return getValue(Equiv->getGlobalValue());
1627 
1628     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1629       return getValue(NC->getGlobalValue());
1630 
1631     VectorType *VecTy = cast<VectorType>(V->getType());
1632 
1633     // Now that we know the number and type of the elements, get that number of
1634     // elements into the Ops array based on what kind of constant it is.
1635     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1636       SmallVector<SDValue, 16> Ops;
1637       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1638       for (unsigned i = 0; i != NumElements; ++i)
1639         Ops.push_back(getValue(CV->getOperand(i)));
1640 
1641       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1642     } else if (isa<ConstantAggregateZero>(C)) {
1643       EVT EltVT =
1644           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1645 
1646       SDValue Op;
1647       if (EltVT.isFloatingPoint())
1648         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1649       else
1650         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1651 
1652       if (isa<ScalableVectorType>(VecTy))
1653         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1654       else {
1655         SmallVector<SDValue, 16> Ops;
1656         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1657         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1658       }
1659     }
1660     llvm_unreachable("Unknown vector constant");
1661   }
1662 
1663   // If this is a static alloca, generate it as the frameindex instead of
1664   // computation.
1665   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1666     DenseMap<const AllocaInst*, int>::iterator SI =
1667       FuncInfo.StaticAllocaMap.find(AI);
1668     if (SI != FuncInfo.StaticAllocaMap.end())
1669       return DAG.getFrameIndex(SI->second,
1670                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1671   }
1672 
1673   // If this is an instruction which fast-isel has deferred, select it now.
1674   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1675     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1676 
1677     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1678                      Inst->getType(), None);
1679     SDValue Chain = DAG.getEntryNode();
1680     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1681   }
1682 
1683   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1684     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1685   }
1686   if (const auto *BB = dyn_cast<BasicBlock>(V))
1687     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1688   llvm_unreachable("Can't get register for value!");
1689 }
1690 
1691 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1692   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1693   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1694   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1695   bool IsSEH = isAsynchronousEHPersonality(Pers);
1696   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1697   if (!IsSEH)
1698     CatchPadMBB->setIsEHScopeEntry();
1699   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1700   if (IsMSVCCXX || IsCoreCLR)
1701     CatchPadMBB->setIsEHFuncletEntry();
1702 }
1703 
1704 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1705   // Update machine-CFG edge.
1706   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1707   FuncInfo.MBB->addSuccessor(TargetMBB);
1708   TargetMBB->setIsEHCatchretTarget(true);
1709   DAG.getMachineFunction().setHasEHCatchret(true);
1710 
1711   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1712   bool IsSEH = isAsynchronousEHPersonality(Pers);
1713   if (IsSEH) {
1714     // If this is not a fall-through branch or optimizations are switched off,
1715     // emit the branch.
1716     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1717         TM.getOptLevel() == CodeGenOpt::None)
1718       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1719                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1720     return;
1721   }
1722 
1723   // Figure out the funclet membership for the catchret's successor.
1724   // This will be used by the FuncletLayout pass to determine how to order the
1725   // BB's.
1726   // A 'catchret' returns to the outer scope's color.
1727   Value *ParentPad = I.getCatchSwitchParentPad();
1728   const BasicBlock *SuccessorColor;
1729   if (isa<ConstantTokenNone>(ParentPad))
1730     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1731   else
1732     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1733   assert(SuccessorColor && "No parent funclet for catchret!");
1734   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1735   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1736 
1737   // Create the terminator node.
1738   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1739                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1740                             DAG.getBasicBlock(SuccessorColorMBB));
1741   DAG.setRoot(Ret);
1742 }
1743 
1744 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1745   // Don't emit any special code for the cleanuppad instruction. It just marks
1746   // the start of an EH scope/funclet.
1747   FuncInfo.MBB->setIsEHScopeEntry();
1748   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1749   if (Pers != EHPersonality::Wasm_CXX) {
1750     FuncInfo.MBB->setIsEHFuncletEntry();
1751     FuncInfo.MBB->setIsCleanupFuncletEntry();
1752   }
1753 }
1754 
1755 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1756 // not match, it is OK to add only the first unwind destination catchpad to the
1757 // successors, because there will be at least one invoke instruction within the
1758 // catch scope that points to the next unwind destination, if one exists, so
1759 // CFGSort cannot mess up with BB sorting order.
1760 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1761 // call within them, and catchpads only consisting of 'catch (...)' have a
1762 // '__cxa_end_catch' call within them, both of which generate invokes in case
1763 // the next unwind destination exists, i.e., the next unwind destination is not
1764 // the caller.)
1765 //
1766 // Having at most one EH pad successor is also simpler and helps later
1767 // transformations.
1768 //
1769 // For example,
1770 // current:
1771 //   invoke void @foo to ... unwind label %catch.dispatch
1772 // catch.dispatch:
1773 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1774 // catch.start:
1775 //   ...
1776 //   ... in this BB or some other child BB dominated by this BB there will be an
1777 //   invoke that points to 'next' BB as an unwind destination
1778 //
1779 // next: ; We don't need to add this to 'current' BB's successor
1780 //   ...
1781 static void findWasmUnwindDestinations(
1782     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1783     BranchProbability Prob,
1784     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1785         &UnwindDests) {
1786   while (EHPadBB) {
1787     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1788     if (isa<CleanupPadInst>(Pad)) {
1789       // Stop on cleanup pads.
1790       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1791       UnwindDests.back().first->setIsEHScopeEntry();
1792       break;
1793     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1794       // Add the catchpad handlers to the possible destinations. We don't
1795       // continue to the unwind destination of the catchswitch for wasm.
1796       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1797         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1798         UnwindDests.back().first->setIsEHScopeEntry();
1799       }
1800       break;
1801     } else {
1802       continue;
1803     }
1804   }
1805 }
1806 
1807 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1808 /// many places it could ultimately go. In the IR, we have a single unwind
1809 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1810 /// This function skips over imaginary basic blocks that hold catchswitch
1811 /// instructions, and finds all the "real" machine
1812 /// basic block destinations. As those destinations may not be successors of
1813 /// EHPadBB, here we also calculate the edge probability to those destinations.
1814 /// The passed-in Prob is the edge probability to EHPadBB.
1815 static void findUnwindDestinations(
1816     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1817     BranchProbability Prob,
1818     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1819         &UnwindDests) {
1820   EHPersonality Personality =
1821     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1822   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1823   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1824   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1825   bool IsSEH = isAsynchronousEHPersonality(Personality);
1826 
1827   if (IsWasmCXX) {
1828     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1829     assert(UnwindDests.size() <= 1 &&
1830            "There should be at most one unwind destination for wasm");
1831     return;
1832   }
1833 
1834   while (EHPadBB) {
1835     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1836     BasicBlock *NewEHPadBB = nullptr;
1837     if (isa<LandingPadInst>(Pad)) {
1838       // Stop on landingpads. They are not funclets.
1839       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1840       break;
1841     } else if (isa<CleanupPadInst>(Pad)) {
1842       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1843       // personalities.
1844       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1845       UnwindDests.back().first->setIsEHScopeEntry();
1846       UnwindDests.back().first->setIsEHFuncletEntry();
1847       break;
1848     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1849       // Add the catchpad handlers to the possible destinations.
1850       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1851         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1852         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1853         if (IsMSVCCXX || IsCoreCLR)
1854           UnwindDests.back().first->setIsEHFuncletEntry();
1855         if (!IsSEH)
1856           UnwindDests.back().first->setIsEHScopeEntry();
1857       }
1858       NewEHPadBB = CatchSwitch->getUnwindDest();
1859     } else {
1860       continue;
1861     }
1862 
1863     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1864     if (BPI && NewEHPadBB)
1865       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1866     EHPadBB = NewEHPadBB;
1867   }
1868 }
1869 
1870 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1871   // Update successor info.
1872   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1873   auto UnwindDest = I.getUnwindDest();
1874   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1875   BranchProbability UnwindDestProb =
1876       (BPI && UnwindDest)
1877           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1878           : BranchProbability::getZero();
1879   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1880   for (auto &UnwindDest : UnwindDests) {
1881     UnwindDest.first->setIsEHPad();
1882     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1883   }
1884   FuncInfo.MBB->normalizeSuccProbs();
1885 
1886   // Create the terminator node.
1887   SDValue Ret =
1888       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1889   DAG.setRoot(Ret);
1890 }
1891 
1892 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1893   report_fatal_error("visitCatchSwitch not yet implemented!");
1894 }
1895 
1896 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1898   auto &DL = DAG.getDataLayout();
1899   SDValue Chain = getControlRoot();
1900   SmallVector<ISD::OutputArg, 8> Outs;
1901   SmallVector<SDValue, 8> OutVals;
1902 
1903   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1904   // lower
1905   //
1906   //   %val = call <ty> @llvm.experimental.deoptimize()
1907   //   ret <ty> %val
1908   //
1909   // differently.
1910   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1911     LowerDeoptimizingReturn();
1912     return;
1913   }
1914 
1915   if (!FuncInfo.CanLowerReturn) {
1916     unsigned DemoteReg = FuncInfo.DemoteRegister;
1917     const Function *F = I.getParent()->getParent();
1918 
1919     // Emit a store of the return value through the virtual register.
1920     // Leave Outs empty so that LowerReturn won't try to load return
1921     // registers the usual way.
1922     SmallVector<EVT, 1> PtrValueVTs;
1923     ComputeValueVTs(TLI, DL,
1924                     F->getReturnType()->getPointerTo(
1925                         DAG.getDataLayout().getAllocaAddrSpace()),
1926                     PtrValueVTs);
1927 
1928     SDValue RetPtr =
1929         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1930     SDValue RetOp = getValue(I.getOperand(0));
1931 
1932     SmallVector<EVT, 4> ValueVTs, MemVTs;
1933     SmallVector<uint64_t, 4> Offsets;
1934     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1935                     &Offsets);
1936     unsigned NumValues = ValueVTs.size();
1937 
1938     SmallVector<SDValue, 4> Chains(NumValues);
1939     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1940     for (unsigned i = 0; i != NumValues; ++i) {
1941       // An aggregate return value cannot wrap around the address space, so
1942       // offsets to its parts don't wrap either.
1943       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1944                                            TypeSize::Fixed(Offsets[i]));
1945 
1946       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1947       if (MemVTs[i] != ValueVTs[i])
1948         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1949       Chains[i] = DAG.getStore(
1950           Chain, getCurSDLoc(), Val,
1951           // FIXME: better loc info would be nice.
1952           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1953           commonAlignment(BaseAlign, Offsets[i]));
1954     }
1955 
1956     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1957                         MVT::Other, Chains);
1958   } else if (I.getNumOperands() != 0) {
1959     SmallVector<EVT, 4> ValueVTs;
1960     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1961     unsigned NumValues = ValueVTs.size();
1962     if (NumValues) {
1963       SDValue RetOp = getValue(I.getOperand(0));
1964 
1965       const Function *F = I.getParent()->getParent();
1966 
1967       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1968           I.getOperand(0)->getType(), F->getCallingConv(),
1969           /*IsVarArg*/ false, DL);
1970 
1971       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1972       if (F->getAttributes().hasRetAttr(Attribute::SExt))
1973         ExtendKind = ISD::SIGN_EXTEND;
1974       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
1975         ExtendKind = ISD::ZERO_EXTEND;
1976 
1977       LLVMContext &Context = F->getContext();
1978       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
1979 
1980       for (unsigned j = 0; j != NumValues; ++j) {
1981         EVT VT = ValueVTs[j];
1982 
1983         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1984           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1985 
1986         CallingConv::ID CC = F->getCallingConv();
1987 
1988         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1989         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1990         SmallVector<SDValue, 4> Parts(NumParts);
1991         getCopyToParts(DAG, getCurSDLoc(),
1992                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1993                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1994 
1995         // 'inreg' on function refers to return value
1996         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1997         if (RetInReg)
1998           Flags.setInReg();
1999 
2000         if (I.getOperand(0)->getType()->isPointerTy()) {
2001           Flags.setPointer();
2002           Flags.setPointerAddrSpace(
2003               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2004         }
2005 
2006         if (NeedsRegBlock) {
2007           Flags.setInConsecutiveRegs();
2008           if (j == NumValues - 1)
2009             Flags.setInConsecutiveRegsLast();
2010         }
2011 
2012         // Propagate extension type if any
2013         if (ExtendKind == ISD::SIGN_EXTEND)
2014           Flags.setSExt();
2015         else if (ExtendKind == ISD::ZERO_EXTEND)
2016           Flags.setZExt();
2017 
2018         for (unsigned i = 0; i < NumParts; ++i) {
2019           Outs.push_back(ISD::OutputArg(Flags,
2020                                         Parts[i].getValueType().getSimpleVT(),
2021                                         VT, /*isfixed=*/true, 0, 0));
2022           OutVals.push_back(Parts[i]);
2023         }
2024       }
2025     }
2026   }
2027 
2028   // Push in swifterror virtual register as the last element of Outs. This makes
2029   // sure swifterror virtual register will be returned in the swifterror
2030   // physical register.
2031   const Function *F = I.getParent()->getParent();
2032   if (TLI.supportSwiftError() &&
2033       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2034     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2035     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2036     Flags.setSwiftError();
2037     Outs.push_back(ISD::OutputArg(
2038         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2039         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2040     // Create SDNode for the swifterror virtual register.
2041     OutVals.push_back(
2042         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2043                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2044                         EVT(TLI.getPointerTy(DL))));
2045   }
2046 
2047   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2048   CallingConv::ID CallConv =
2049     DAG.getMachineFunction().getFunction().getCallingConv();
2050   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2051       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2052 
2053   // Verify that the target's LowerReturn behaved as expected.
2054   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2055          "LowerReturn didn't return a valid chain!");
2056 
2057   // Update the DAG with the new chain value resulting from return lowering.
2058   DAG.setRoot(Chain);
2059 }
2060 
2061 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2062 /// created for it, emit nodes to copy the value into the virtual
2063 /// registers.
2064 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2065   // Skip empty types
2066   if (V->getType()->isEmptyTy())
2067     return;
2068 
2069   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2070   if (VMI != FuncInfo.ValueMap.end()) {
2071     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2072     CopyValueToVirtualRegister(V, VMI->second);
2073   }
2074 }
2075 
2076 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2077 /// the current basic block, add it to ValueMap now so that we'll get a
2078 /// CopyTo/FromReg.
2079 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2080   // No need to export constants.
2081   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2082 
2083   // Already exported?
2084   if (FuncInfo.isExportedInst(V)) return;
2085 
2086   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2087   CopyValueToVirtualRegister(V, Reg);
2088 }
2089 
2090 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2091                                                      const BasicBlock *FromBB) {
2092   // The operands of the setcc have to be in this block.  We don't know
2093   // how to export them from some other block.
2094   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2095     // Can export from current BB.
2096     if (VI->getParent() == FromBB)
2097       return true;
2098 
2099     // Is already exported, noop.
2100     return FuncInfo.isExportedInst(V);
2101   }
2102 
2103   // If this is an argument, we can export it if the BB is the entry block or
2104   // if it is already exported.
2105   if (isa<Argument>(V)) {
2106     if (FromBB->isEntryBlock())
2107       return true;
2108 
2109     // Otherwise, can only export this if it is already exported.
2110     return FuncInfo.isExportedInst(V);
2111   }
2112 
2113   // Otherwise, constants can always be exported.
2114   return true;
2115 }
2116 
2117 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2118 BranchProbability
2119 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2120                                         const MachineBasicBlock *Dst) const {
2121   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2122   const BasicBlock *SrcBB = Src->getBasicBlock();
2123   const BasicBlock *DstBB = Dst->getBasicBlock();
2124   if (!BPI) {
2125     // If BPI is not available, set the default probability as 1 / N, where N is
2126     // the number of successors.
2127     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2128     return BranchProbability(1, SuccSize);
2129   }
2130   return BPI->getEdgeProbability(SrcBB, DstBB);
2131 }
2132 
2133 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2134                                                MachineBasicBlock *Dst,
2135                                                BranchProbability Prob) {
2136   if (!FuncInfo.BPI)
2137     Src->addSuccessorWithoutProb(Dst);
2138   else {
2139     if (Prob.isUnknown())
2140       Prob = getEdgeProbability(Src, Dst);
2141     Src->addSuccessor(Dst, Prob);
2142   }
2143 }
2144 
2145 static bool InBlock(const Value *V, const BasicBlock *BB) {
2146   if (const Instruction *I = dyn_cast<Instruction>(V))
2147     return I->getParent() == BB;
2148   return true;
2149 }
2150 
2151 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2152 /// This function emits a branch and is used at the leaves of an OR or an
2153 /// AND operator tree.
2154 void
2155 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2156                                                   MachineBasicBlock *TBB,
2157                                                   MachineBasicBlock *FBB,
2158                                                   MachineBasicBlock *CurBB,
2159                                                   MachineBasicBlock *SwitchBB,
2160                                                   BranchProbability TProb,
2161                                                   BranchProbability FProb,
2162                                                   bool InvertCond) {
2163   const BasicBlock *BB = CurBB->getBasicBlock();
2164 
2165   // If the leaf of the tree is a comparison, merge the condition into
2166   // the caseblock.
2167   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2168     // The operands of the cmp have to be in this block.  We don't know
2169     // how to export them from some other block.  If this is the first block
2170     // of the sequence, no exporting is needed.
2171     if (CurBB == SwitchBB ||
2172         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2173          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2174       ISD::CondCode Condition;
2175       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2176         ICmpInst::Predicate Pred =
2177             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2178         Condition = getICmpCondCode(Pred);
2179       } else {
2180         const FCmpInst *FC = cast<FCmpInst>(Cond);
2181         FCmpInst::Predicate Pred =
2182             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2183         Condition = getFCmpCondCode(Pred);
2184         if (TM.Options.NoNaNsFPMath)
2185           Condition = getFCmpCodeWithoutNaN(Condition);
2186       }
2187 
2188       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2189                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2190       SL->SwitchCases.push_back(CB);
2191       return;
2192     }
2193   }
2194 
2195   // Create a CaseBlock record representing this branch.
2196   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2197   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2198                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2199   SL->SwitchCases.push_back(CB);
2200 }
2201 
2202 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2203                                                MachineBasicBlock *TBB,
2204                                                MachineBasicBlock *FBB,
2205                                                MachineBasicBlock *CurBB,
2206                                                MachineBasicBlock *SwitchBB,
2207                                                Instruction::BinaryOps Opc,
2208                                                BranchProbability TProb,
2209                                                BranchProbability FProb,
2210                                                bool InvertCond) {
2211   // Skip over not part of the tree and remember to invert op and operands at
2212   // next level.
2213   Value *NotCond;
2214   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2215       InBlock(NotCond, CurBB->getBasicBlock())) {
2216     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2217                          !InvertCond);
2218     return;
2219   }
2220 
2221   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2222   const Value *BOpOp0, *BOpOp1;
2223   // Compute the effective opcode for Cond, taking into account whether it needs
2224   // to be inverted, e.g.
2225   //   and (not (or A, B)), C
2226   // gets lowered as
2227   //   and (and (not A, not B), C)
2228   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2229   if (BOp) {
2230     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2231                ? Instruction::And
2232                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2233                       ? Instruction::Or
2234                       : (Instruction::BinaryOps)0);
2235     if (InvertCond) {
2236       if (BOpc == Instruction::And)
2237         BOpc = Instruction::Or;
2238       else if (BOpc == Instruction::Or)
2239         BOpc = Instruction::And;
2240     }
2241   }
2242 
2243   // If this node is not part of the or/and tree, emit it as a branch.
2244   // Note that all nodes in the tree should have same opcode.
2245   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2246   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2247       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2248       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2249     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2250                                  TProb, FProb, InvertCond);
2251     return;
2252   }
2253 
2254   //  Create TmpBB after CurBB.
2255   MachineFunction::iterator BBI(CurBB);
2256   MachineFunction &MF = DAG.getMachineFunction();
2257   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2258   CurBB->getParent()->insert(++BBI, TmpBB);
2259 
2260   if (Opc == Instruction::Or) {
2261     // Codegen X | Y as:
2262     // BB1:
2263     //   jmp_if_X TBB
2264     //   jmp TmpBB
2265     // TmpBB:
2266     //   jmp_if_Y TBB
2267     //   jmp FBB
2268     //
2269 
2270     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2271     // The requirement is that
2272     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2273     //     = TrueProb for original BB.
2274     // Assuming the original probabilities are A and B, one choice is to set
2275     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2276     // A/(1+B) and 2B/(1+B). This choice assumes that
2277     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2278     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2279     // TmpBB, but the math is more complicated.
2280 
2281     auto NewTrueProb = TProb / 2;
2282     auto NewFalseProb = TProb / 2 + FProb;
2283     // Emit the LHS condition.
2284     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2285                          NewFalseProb, InvertCond);
2286 
2287     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2288     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2289     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2290     // Emit the RHS condition into TmpBB.
2291     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2292                          Probs[1], InvertCond);
2293   } else {
2294     assert(Opc == Instruction::And && "Unknown merge op!");
2295     // Codegen X & Y as:
2296     // BB1:
2297     //   jmp_if_X TmpBB
2298     //   jmp FBB
2299     // TmpBB:
2300     //   jmp_if_Y TBB
2301     //   jmp FBB
2302     //
2303     //  This requires creation of TmpBB after CurBB.
2304 
2305     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2306     // The requirement is that
2307     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2308     //     = FalseProb for original BB.
2309     // Assuming the original probabilities are A and B, one choice is to set
2310     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2311     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2312     // TrueProb for BB1 * FalseProb for TmpBB.
2313 
2314     auto NewTrueProb = TProb + FProb / 2;
2315     auto NewFalseProb = FProb / 2;
2316     // Emit the LHS condition.
2317     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2318                          NewFalseProb, InvertCond);
2319 
2320     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2321     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2322     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2323     // Emit the RHS condition into TmpBB.
2324     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2325                          Probs[1], InvertCond);
2326   }
2327 }
2328 
2329 /// If the set of cases should be emitted as a series of branches, return true.
2330 /// If we should emit this as a bunch of and/or'd together conditions, return
2331 /// false.
2332 bool
2333 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2334   if (Cases.size() != 2) return true;
2335 
2336   // If this is two comparisons of the same values or'd or and'd together, they
2337   // will get folded into a single comparison, so don't emit two blocks.
2338   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2339        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2340       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2341        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2342     return false;
2343   }
2344 
2345   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2346   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2347   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2348       Cases[0].CC == Cases[1].CC &&
2349       isa<Constant>(Cases[0].CmpRHS) &&
2350       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2351     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2352       return false;
2353     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2354       return false;
2355   }
2356 
2357   return true;
2358 }
2359 
2360 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2361   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2362 
2363   // Update machine-CFG edges.
2364   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2365 
2366   if (I.isUnconditional()) {
2367     // Update machine-CFG edges.
2368     BrMBB->addSuccessor(Succ0MBB);
2369 
2370     // If this is not a fall-through branch or optimizations are switched off,
2371     // emit the branch.
2372     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2373       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2374                               MVT::Other, getControlRoot(),
2375                               DAG.getBasicBlock(Succ0MBB)));
2376 
2377     return;
2378   }
2379 
2380   // If this condition is one of the special cases we handle, do special stuff
2381   // now.
2382   const Value *CondVal = I.getCondition();
2383   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2384 
2385   // If this is a series of conditions that are or'd or and'd together, emit
2386   // this as a sequence of branches instead of setcc's with and/or operations.
2387   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2388   // unpredictable branches, and vector extracts because those jumps are likely
2389   // expensive for any target), this should improve performance.
2390   // For example, instead of something like:
2391   //     cmp A, B
2392   //     C = seteq
2393   //     cmp D, E
2394   //     F = setle
2395   //     or C, F
2396   //     jnz foo
2397   // Emit:
2398   //     cmp A, B
2399   //     je foo
2400   //     cmp D, E
2401   //     jle foo
2402   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2403   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2404       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2405     Value *Vec;
2406     const Value *BOp0, *BOp1;
2407     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2408     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2409       Opcode = Instruction::And;
2410     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2411       Opcode = Instruction::Or;
2412 
2413     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2414                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2415       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2416                            getEdgeProbability(BrMBB, Succ0MBB),
2417                            getEdgeProbability(BrMBB, Succ1MBB),
2418                            /*InvertCond=*/false);
2419       // If the compares in later blocks need to use values not currently
2420       // exported from this block, export them now.  This block should always
2421       // be the first entry.
2422       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2423 
2424       // Allow some cases to be rejected.
2425       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2426         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2427           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2428           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2429         }
2430 
2431         // Emit the branch for this block.
2432         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2433         SL->SwitchCases.erase(SL->SwitchCases.begin());
2434         return;
2435       }
2436 
2437       // Okay, we decided not to do this, remove any inserted MBB's and clear
2438       // SwitchCases.
2439       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2440         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2441 
2442       SL->SwitchCases.clear();
2443     }
2444   }
2445 
2446   // Create a CaseBlock record representing this branch.
2447   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2448                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2449 
2450   // Use visitSwitchCase to actually insert the fast branch sequence for this
2451   // cond branch.
2452   visitSwitchCase(CB, BrMBB);
2453 }
2454 
2455 /// visitSwitchCase - Emits the necessary code to represent a single node in
2456 /// the binary search tree resulting from lowering a switch instruction.
2457 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2458                                           MachineBasicBlock *SwitchBB) {
2459   SDValue Cond;
2460   SDValue CondLHS = getValue(CB.CmpLHS);
2461   SDLoc dl = CB.DL;
2462 
2463   if (CB.CC == ISD::SETTRUE) {
2464     // Branch or fall through to TrueBB.
2465     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2466     SwitchBB->normalizeSuccProbs();
2467     if (CB.TrueBB != NextBlock(SwitchBB)) {
2468       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2469                               DAG.getBasicBlock(CB.TrueBB)));
2470     }
2471     return;
2472   }
2473 
2474   auto &TLI = DAG.getTargetLoweringInfo();
2475   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2476 
2477   // Build the setcc now.
2478   if (!CB.CmpMHS) {
2479     // Fold "(X == true)" to X and "(X == false)" to !X to
2480     // handle common cases produced by branch lowering.
2481     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2482         CB.CC == ISD::SETEQ)
2483       Cond = CondLHS;
2484     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2485              CB.CC == ISD::SETEQ) {
2486       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2487       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2488     } else {
2489       SDValue CondRHS = getValue(CB.CmpRHS);
2490 
2491       // If a pointer's DAG type is larger than its memory type then the DAG
2492       // values are zero-extended. This breaks signed comparisons so truncate
2493       // back to the underlying type before doing the compare.
2494       if (CondLHS.getValueType() != MemVT) {
2495         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2496         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2497       }
2498       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2499     }
2500   } else {
2501     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2502 
2503     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2504     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2505 
2506     SDValue CmpOp = getValue(CB.CmpMHS);
2507     EVT VT = CmpOp.getValueType();
2508 
2509     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2510       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2511                           ISD::SETLE);
2512     } else {
2513       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2514                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2515       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2516                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2517     }
2518   }
2519 
2520   // Update successor info
2521   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2522   // TrueBB and FalseBB are always different unless the incoming IR is
2523   // degenerate. This only happens when running llc on weird IR.
2524   if (CB.TrueBB != CB.FalseBB)
2525     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2526   SwitchBB->normalizeSuccProbs();
2527 
2528   // If the lhs block is the next block, invert the condition so that we can
2529   // fall through to the lhs instead of the rhs block.
2530   if (CB.TrueBB == NextBlock(SwitchBB)) {
2531     std::swap(CB.TrueBB, CB.FalseBB);
2532     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2533     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2534   }
2535 
2536   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2537                                MVT::Other, getControlRoot(), Cond,
2538                                DAG.getBasicBlock(CB.TrueBB));
2539 
2540   // Insert the false branch. Do this even if it's a fall through branch,
2541   // this makes it easier to do DAG optimizations which require inverting
2542   // the branch condition.
2543   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2544                        DAG.getBasicBlock(CB.FalseBB));
2545 
2546   DAG.setRoot(BrCond);
2547 }
2548 
2549 /// visitJumpTable - Emit JumpTable node in the current MBB
2550 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2551   // Emit the code for the jump table
2552   assert(JT.Reg != -1U && "Should lower JT Header first!");
2553   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2554   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2555                                      JT.Reg, PTy);
2556   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2557   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2558                                     MVT::Other, Index.getValue(1),
2559                                     Table, Index);
2560   DAG.setRoot(BrJumpTable);
2561 }
2562 
2563 /// visitJumpTableHeader - This function emits necessary code to produce index
2564 /// in the JumpTable from switch case.
2565 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2566                                                JumpTableHeader &JTH,
2567                                                MachineBasicBlock *SwitchBB) {
2568   SDLoc dl = getCurSDLoc();
2569 
2570   // Subtract the lowest switch case value from the value being switched on.
2571   SDValue SwitchOp = getValue(JTH.SValue);
2572   EVT VT = SwitchOp.getValueType();
2573   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2574                             DAG.getConstant(JTH.First, dl, VT));
2575 
2576   // The SDNode we just created, which holds the value being switched on minus
2577   // the smallest case value, needs to be copied to a virtual register so it
2578   // can be used as an index into the jump table in a subsequent basic block.
2579   // This value may be smaller or larger than the target's pointer type, and
2580   // therefore require extension or truncating.
2581   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2582   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2583 
2584   unsigned JumpTableReg =
2585       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2586   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2587                                     JumpTableReg, SwitchOp);
2588   JT.Reg = JumpTableReg;
2589 
2590   if (!JTH.FallthroughUnreachable) {
2591     // Emit the range check for the jump table, and branch to the default block
2592     // for the switch statement if the value being switched on exceeds the
2593     // largest case in the switch.
2594     SDValue CMP = DAG.getSetCC(
2595         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2596                                    Sub.getValueType()),
2597         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2598 
2599     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2600                                  MVT::Other, CopyTo, CMP,
2601                                  DAG.getBasicBlock(JT.Default));
2602 
2603     // Avoid emitting unnecessary branches to the next block.
2604     if (JT.MBB != NextBlock(SwitchBB))
2605       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2606                            DAG.getBasicBlock(JT.MBB));
2607 
2608     DAG.setRoot(BrCond);
2609   } else {
2610     // Avoid emitting unnecessary branches to the next block.
2611     if (JT.MBB != NextBlock(SwitchBB))
2612       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2613                               DAG.getBasicBlock(JT.MBB)));
2614     else
2615       DAG.setRoot(CopyTo);
2616   }
2617 }
2618 
2619 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2620 /// variable if there exists one.
2621 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2622                                  SDValue &Chain) {
2623   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2624   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2625   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2626   MachineFunction &MF = DAG.getMachineFunction();
2627   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2628   MachineSDNode *Node =
2629       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2630   if (Global) {
2631     MachinePointerInfo MPInfo(Global);
2632     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2633                  MachineMemOperand::MODereferenceable;
2634     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2635         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2636     DAG.setNodeMemRefs(Node, {MemRef});
2637   }
2638   if (PtrTy != PtrMemTy)
2639     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2640   return SDValue(Node, 0);
2641 }
2642 
2643 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2644 /// tail spliced into a stack protector check success bb.
2645 ///
2646 /// For a high level explanation of how this fits into the stack protector
2647 /// generation see the comment on the declaration of class
2648 /// StackProtectorDescriptor.
2649 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2650                                                   MachineBasicBlock *ParentBB) {
2651 
2652   // First create the loads to the guard/stack slot for the comparison.
2653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2654   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2655   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2656 
2657   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2658   int FI = MFI.getStackProtectorIndex();
2659 
2660   SDValue Guard;
2661   SDLoc dl = getCurSDLoc();
2662   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2663   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2664   Align Align =
2665       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2666 
2667   // Generate code to load the content of the guard slot.
2668   SDValue GuardVal = DAG.getLoad(
2669       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2670       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2671       MachineMemOperand::MOVolatile);
2672 
2673   if (TLI.useStackGuardXorFP())
2674     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2675 
2676   // Retrieve guard check function, nullptr if instrumentation is inlined.
2677   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2678     // The target provides a guard check function to validate the guard value.
2679     // Generate a call to that function with the content of the guard slot as
2680     // argument.
2681     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2682     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2683 
2684     TargetLowering::ArgListTy Args;
2685     TargetLowering::ArgListEntry Entry;
2686     Entry.Node = GuardVal;
2687     Entry.Ty = FnTy->getParamType(0);
2688     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2689       Entry.IsInReg = true;
2690     Args.push_back(Entry);
2691 
2692     TargetLowering::CallLoweringInfo CLI(DAG);
2693     CLI.setDebugLoc(getCurSDLoc())
2694         .setChain(DAG.getEntryNode())
2695         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2696                    getValue(GuardCheckFn), std::move(Args));
2697 
2698     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2699     DAG.setRoot(Result.second);
2700     return;
2701   }
2702 
2703   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2704   // Otherwise, emit a volatile load to retrieve the stack guard value.
2705   SDValue Chain = DAG.getEntryNode();
2706   if (TLI.useLoadStackGuardNode()) {
2707     Guard = getLoadStackGuard(DAG, dl, Chain);
2708   } else {
2709     const Value *IRGuard = TLI.getSDagStackGuard(M);
2710     SDValue GuardPtr = getValue(IRGuard);
2711 
2712     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2713                         MachinePointerInfo(IRGuard, 0), Align,
2714                         MachineMemOperand::MOVolatile);
2715   }
2716 
2717   // Perform the comparison via a getsetcc.
2718   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2719                                                         *DAG.getContext(),
2720                                                         Guard.getValueType()),
2721                              Guard, GuardVal, ISD::SETNE);
2722 
2723   // If the guard/stackslot do not equal, branch to failure MBB.
2724   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2725                                MVT::Other, GuardVal.getOperand(0),
2726                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2727   // Otherwise branch to success MBB.
2728   SDValue Br = DAG.getNode(ISD::BR, dl,
2729                            MVT::Other, BrCond,
2730                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2731 
2732   DAG.setRoot(Br);
2733 }
2734 
2735 /// Codegen the failure basic block for a stack protector check.
2736 ///
2737 /// A failure stack protector machine basic block consists simply of a call to
2738 /// __stack_chk_fail().
2739 ///
2740 /// For a high level explanation of how this fits into the stack protector
2741 /// generation see the comment on the declaration of class
2742 /// StackProtectorDescriptor.
2743 void
2744 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2745   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2746   TargetLowering::MakeLibCallOptions CallOptions;
2747   CallOptions.setDiscardResult(true);
2748   SDValue Chain =
2749       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2750                       None, CallOptions, getCurSDLoc()).second;
2751   // On PS4, the "return address" must still be within the calling function,
2752   // even if it's at the very end, so emit an explicit TRAP here.
2753   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2754   if (TM.getTargetTriple().isPS4CPU())
2755     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2756   // WebAssembly needs an unreachable instruction after a non-returning call,
2757   // because the function return type can be different from __stack_chk_fail's
2758   // return type (void).
2759   if (TM.getTargetTriple().isWasm())
2760     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2761 
2762   DAG.setRoot(Chain);
2763 }
2764 
2765 /// visitBitTestHeader - This function emits necessary code to produce value
2766 /// suitable for "bit tests"
2767 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2768                                              MachineBasicBlock *SwitchBB) {
2769   SDLoc dl = getCurSDLoc();
2770 
2771   // Subtract the minimum value.
2772   SDValue SwitchOp = getValue(B.SValue);
2773   EVT VT = SwitchOp.getValueType();
2774   SDValue RangeSub =
2775       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2776 
2777   // Determine the type of the test operands.
2778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2779   bool UsePtrType = false;
2780   if (!TLI.isTypeLegal(VT)) {
2781     UsePtrType = true;
2782   } else {
2783     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2784       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2785         // Switch table case range are encoded into series of masks.
2786         // Just use pointer type, it's guaranteed to fit.
2787         UsePtrType = true;
2788         break;
2789       }
2790   }
2791   SDValue Sub = RangeSub;
2792   if (UsePtrType) {
2793     VT = TLI.getPointerTy(DAG.getDataLayout());
2794     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2795   }
2796 
2797   B.RegVT = VT.getSimpleVT();
2798   B.Reg = FuncInfo.CreateReg(B.RegVT);
2799   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2800 
2801   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2802 
2803   if (!B.FallthroughUnreachable)
2804     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2805   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2806   SwitchBB->normalizeSuccProbs();
2807 
2808   SDValue Root = CopyTo;
2809   if (!B.FallthroughUnreachable) {
2810     // Conditional branch to the default block.
2811     SDValue RangeCmp = DAG.getSetCC(dl,
2812         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2813                                RangeSub.getValueType()),
2814         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2815         ISD::SETUGT);
2816 
2817     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2818                        DAG.getBasicBlock(B.Default));
2819   }
2820 
2821   // Avoid emitting unnecessary branches to the next block.
2822   if (MBB != NextBlock(SwitchBB))
2823     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2824 
2825   DAG.setRoot(Root);
2826 }
2827 
2828 /// visitBitTestCase - this function produces one "bit test"
2829 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2830                                            MachineBasicBlock* NextMBB,
2831                                            BranchProbability BranchProbToNext,
2832                                            unsigned Reg,
2833                                            BitTestCase &B,
2834                                            MachineBasicBlock *SwitchBB) {
2835   SDLoc dl = getCurSDLoc();
2836   MVT VT = BB.RegVT;
2837   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2838   SDValue Cmp;
2839   unsigned PopCount = countPopulation(B.Mask);
2840   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2841   if (PopCount == 1) {
2842     // Testing for a single bit; just compare the shift count with what it
2843     // would need to be to shift a 1 bit in that position.
2844     Cmp = DAG.getSetCC(
2845         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2846         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2847         ISD::SETEQ);
2848   } else if (PopCount == BB.Range) {
2849     // There is only one zero bit in the range, test for it directly.
2850     Cmp = DAG.getSetCC(
2851         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2852         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2853         ISD::SETNE);
2854   } else {
2855     // Make desired shift
2856     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2857                                     DAG.getConstant(1, dl, VT), ShiftOp);
2858 
2859     // Emit bit tests and jumps
2860     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2861                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2862     Cmp = DAG.getSetCC(
2863         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2864         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2865   }
2866 
2867   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2868   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2869   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2870   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2871   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2872   // one as they are relative probabilities (and thus work more like weights),
2873   // and hence we need to normalize them to let the sum of them become one.
2874   SwitchBB->normalizeSuccProbs();
2875 
2876   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2877                               MVT::Other, getControlRoot(),
2878                               Cmp, DAG.getBasicBlock(B.TargetBB));
2879 
2880   // Avoid emitting unnecessary branches to the next block.
2881   if (NextMBB != NextBlock(SwitchBB))
2882     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2883                         DAG.getBasicBlock(NextMBB));
2884 
2885   DAG.setRoot(BrAnd);
2886 }
2887 
2888 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2889   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2890 
2891   // Retrieve successors. Look through artificial IR level blocks like
2892   // catchswitch for successors.
2893   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2894   const BasicBlock *EHPadBB = I.getSuccessor(1);
2895 
2896   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2897   // have to do anything here to lower funclet bundles.
2898   assert(!I.hasOperandBundlesOtherThan(
2899              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2900               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2901               LLVMContext::OB_cfguardtarget,
2902               LLVMContext::OB_clang_arc_attachedcall}) &&
2903          "Cannot lower invokes with arbitrary operand bundles yet!");
2904 
2905   const Value *Callee(I.getCalledOperand());
2906   const Function *Fn = dyn_cast<Function>(Callee);
2907   if (isa<InlineAsm>(Callee))
2908     visitInlineAsm(I, EHPadBB);
2909   else if (Fn && Fn->isIntrinsic()) {
2910     switch (Fn->getIntrinsicID()) {
2911     default:
2912       llvm_unreachable("Cannot invoke this intrinsic");
2913     case Intrinsic::donothing:
2914       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2915     case Intrinsic::seh_try_begin:
2916     case Intrinsic::seh_scope_begin:
2917     case Intrinsic::seh_try_end:
2918     case Intrinsic::seh_scope_end:
2919       break;
2920     case Intrinsic::experimental_patchpoint_void:
2921     case Intrinsic::experimental_patchpoint_i64:
2922       visitPatchpoint(I, EHPadBB);
2923       break;
2924     case Intrinsic::experimental_gc_statepoint:
2925       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2926       break;
2927     case Intrinsic::wasm_rethrow: {
2928       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2929       // special because it can be invoked, so we manually lower it to a DAG
2930       // node here.
2931       SmallVector<SDValue, 8> Ops;
2932       Ops.push_back(getRoot()); // inchain
2933       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2934       Ops.push_back(
2935           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2936                                 TLI.getPointerTy(DAG.getDataLayout())));
2937       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2938       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2939       break;
2940     }
2941     }
2942   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2943     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2944     // Eventually we will support lowering the @llvm.experimental.deoptimize
2945     // intrinsic, and right now there are no plans to support other intrinsics
2946     // with deopt state.
2947     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2948   } else {
2949     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2950   }
2951 
2952   // If the value of the invoke is used outside of its defining block, make it
2953   // available as a virtual register.
2954   // We already took care of the exported value for the statepoint instruction
2955   // during call to the LowerStatepoint.
2956   if (!isa<GCStatepointInst>(I)) {
2957     CopyToExportRegsIfNeeded(&I);
2958   }
2959 
2960   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2961   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2962   BranchProbability EHPadBBProb =
2963       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2964           : BranchProbability::getZero();
2965   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2966 
2967   // Update successor info.
2968   addSuccessorWithProb(InvokeMBB, Return);
2969   for (auto &UnwindDest : UnwindDests) {
2970     UnwindDest.first->setIsEHPad();
2971     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2972   }
2973   InvokeMBB->normalizeSuccProbs();
2974 
2975   // Drop into normal successor.
2976   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2977                           DAG.getBasicBlock(Return)));
2978 }
2979 
2980 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2981   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2982 
2983   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2984   // have to do anything here to lower funclet bundles.
2985   assert(!I.hasOperandBundlesOtherThan(
2986              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2987          "Cannot lower callbrs with arbitrary operand bundles yet!");
2988 
2989   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2990   visitInlineAsm(I);
2991   CopyToExportRegsIfNeeded(&I);
2992 
2993   // Retrieve successors.
2994   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2995 
2996   // Update successor info.
2997   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2998   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2999     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
3000     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3001     Target->setIsInlineAsmBrIndirectTarget();
3002   }
3003   CallBrMBB->normalizeSuccProbs();
3004 
3005   // Drop into default successor.
3006   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3007                           MVT::Other, getControlRoot(),
3008                           DAG.getBasicBlock(Return)));
3009 }
3010 
3011 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3012   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3013 }
3014 
3015 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3016   assert(FuncInfo.MBB->isEHPad() &&
3017          "Call to landingpad not in landing pad!");
3018 
3019   // If there aren't registers to copy the values into (e.g., during SjLj
3020   // exceptions), then don't bother to create these DAG nodes.
3021   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3022   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3023   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3024       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3025     return;
3026 
3027   // If landingpad's return type is token type, we don't create DAG nodes
3028   // for its exception pointer and selector value. The extraction of exception
3029   // pointer or selector value from token type landingpads is not currently
3030   // supported.
3031   if (LP.getType()->isTokenTy())
3032     return;
3033 
3034   SmallVector<EVT, 2> ValueVTs;
3035   SDLoc dl = getCurSDLoc();
3036   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3037   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3038 
3039   // Get the two live-in registers as SDValues. The physregs have already been
3040   // copied into virtual registers.
3041   SDValue Ops[2];
3042   if (FuncInfo.ExceptionPointerVirtReg) {
3043     Ops[0] = DAG.getZExtOrTrunc(
3044         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3045                            FuncInfo.ExceptionPointerVirtReg,
3046                            TLI.getPointerTy(DAG.getDataLayout())),
3047         dl, ValueVTs[0]);
3048   } else {
3049     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3050   }
3051   Ops[1] = DAG.getZExtOrTrunc(
3052       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3053                          FuncInfo.ExceptionSelectorVirtReg,
3054                          TLI.getPointerTy(DAG.getDataLayout())),
3055       dl, ValueVTs[1]);
3056 
3057   // Merge into one.
3058   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3059                             DAG.getVTList(ValueVTs), Ops);
3060   setValue(&LP, Res);
3061 }
3062 
3063 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3064                                            MachineBasicBlock *Last) {
3065   // Update JTCases.
3066   for (JumpTableBlock &JTB : SL->JTCases)
3067     if (JTB.first.HeaderBB == First)
3068       JTB.first.HeaderBB = Last;
3069 
3070   // Update BitTestCases.
3071   for (BitTestBlock &BTB : SL->BitTestCases)
3072     if (BTB.Parent == First)
3073       BTB.Parent = Last;
3074 }
3075 
3076 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3077   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3078 
3079   // Update machine-CFG edges with unique successors.
3080   SmallSet<BasicBlock*, 32> Done;
3081   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3082     BasicBlock *BB = I.getSuccessor(i);
3083     bool Inserted = Done.insert(BB).second;
3084     if (!Inserted)
3085         continue;
3086 
3087     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3088     addSuccessorWithProb(IndirectBrMBB, Succ);
3089   }
3090   IndirectBrMBB->normalizeSuccProbs();
3091 
3092   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3093                           MVT::Other, getControlRoot(),
3094                           getValue(I.getAddress())));
3095 }
3096 
3097 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3098   if (!DAG.getTarget().Options.TrapUnreachable)
3099     return;
3100 
3101   // We may be able to ignore unreachable behind a noreturn call.
3102   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3103     const BasicBlock &BB = *I.getParent();
3104     if (&I != &BB.front()) {
3105       BasicBlock::const_iterator PredI =
3106         std::prev(BasicBlock::const_iterator(&I));
3107       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3108         if (Call->doesNotReturn())
3109           return;
3110       }
3111     }
3112   }
3113 
3114   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3115 }
3116 
3117 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3118   SDNodeFlags Flags;
3119   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3120     Flags.copyFMF(*FPOp);
3121 
3122   SDValue Op = getValue(I.getOperand(0));
3123   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3124                                     Op, Flags);
3125   setValue(&I, UnNodeValue);
3126 }
3127 
3128 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3129   SDNodeFlags Flags;
3130   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3131     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3132     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3133   }
3134   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3135     Flags.setExact(ExactOp->isExact());
3136   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3137     Flags.copyFMF(*FPOp);
3138 
3139   SDValue Op1 = getValue(I.getOperand(0));
3140   SDValue Op2 = getValue(I.getOperand(1));
3141   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3142                                      Op1, Op2, Flags);
3143   setValue(&I, BinNodeValue);
3144 }
3145 
3146 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3147   SDValue Op1 = getValue(I.getOperand(0));
3148   SDValue Op2 = getValue(I.getOperand(1));
3149 
3150   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3151       Op1.getValueType(), DAG.getDataLayout());
3152 
3153   // Coerce the shift amount to the right type if we can.
3154   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3155     unsigned ShiftSize = ShiftTy.getSizeInBits();
3156     unsigned Op2Size = Op2.getValueSizeInBits();
3157     SDLoc DL = getCurSDLoc();
3158 
3159     // If the operand is smaller than the shift count type, promote it.
3160     if (ShiftSize > Op2Size)
3161       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3162 
3163     // If the operand is larger than the shift count type but the shift
3164     // count type has enough bits to represent any shift value, truncate
3165     // it now. This is a common case and it exposes the truncate to
3166     // optimization early.
3167     else if (ShiftSize >= Log2_32_Ceil(Op1.getValueSizeInBits()))
3168       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3169     // Otherwise we'll need to temporarily settle for some other convenient
3170     // type.  Type legalization will make adjustments once the shiftee is split.
3171     else
3172       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3173   }
3174 
3175   bool nuw = false;
3176   bool nsw = false;
3177   bool exact = false;
3178 
3179   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3180 
3181     if (const OverflowingBinaryOperator *OFBinOp =
3182             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3183       nuw = OFBinOp->hasNoUnsignedWrap();
3184       nsw = OFBinOp->hasNoSignedWrap();
3185     }
3186     if (const PossiblyExactOperator *ExactOp =
3187             dyn_cast<const PossiblyExactOperator>(&I))
3188       exact = ExactOp->isExact();
3189   }
3190   SDNodeFlags Flags;
3191   Flags.setExact(exact);
3192   Flags.setNoSignedWrap(nsw);
3193   Flags.setNoUnsignedWrap(nuw);
3194   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3195                             Flags);
3196   setValue(&I, Res);
3197 }
3198 
3199 void SelectionDAGBuilder::visitSDiv(const User &I) {
3200   SDValue Op1 = getValue(I.getOperand(0));
3201   SDValue Op2 = getValue(I.getOperand(1));
3202 
3203   SDNodeFlags Flags;
3204   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3205                  cast<PossiblyExactOperator>(&I)->isExact());
3206   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3207                            Op2, Flags));
3208 }
3209 
3210 void SelectionDAGBuilder::visitICmp(const User &I) {
3211   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3212   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3213     predicate = IC->getPredicate();
3214   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3215     predicate = ICmpInst::Predicate(IC->getPredicate());
3216   SDValue Op1 = getValue(I.getOperand(0));
3217   SDValue Op2 = getValue(I.getOperand(1));
3218   ISD::CondCode Opcode = getICmpCondCode(predicate);
3219 
3220   auto &TLI = DAG.getTargetLoweringInfo();
3221   EVT MemVT =
3222       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3223 
3224   // If a pointer's DAG type is larger than its memory type then the DAG values
3225   // are zero-extended. This breaks signed comparisons so truncate back to the
3226   // underlying type before doing the compare.
3227   if (Op1.getValueType() != MemVT) {
3228     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3229     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3230   }
3231 
3232   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3233                                                         I.getType());
3234   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3235 }
3236 
3237 void SelectionDAGBuilder::visitFCmp(const User &I) {
3238   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3239   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3240     predicate = FC->getPredicate();
3241   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3242     predicate = FCmpInst::Predicate(FC->getPredicate());
3243   SDValue Op1 = getValue(I.getOperand(0));
3244   SDValue Op2 = getValue(I.getOperand(1));
3245 
3246   ISD::CondCode Condition = getFCmpCondCode(predicate);
3247   auto *FPMO = cast<FPMathOperator>(&I);
3248   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3249     Condition = getFCmpCodeWithoutNaN(Condition);
3250 
3251   SDNodeFlags Flags;
3252   Flags.copyFMF(*FPMO);
3253   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3254 
3255   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3256                                                         I.getType());
3257   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3258 }
3259 
3260 // Check if the condition of the select has one use or two users that are both
3261 // selects with the same condition.
3262 static bool hasOnlySelectUsers(const Value *Cond) {
3263   return llvm::all_of(Cond->users(), [](const Value *V) {
3264     return isa<SelectInst>(V);
3265   });
3266 }
3267 
3268 void SelectionDAGBuilder::visitSelect(const User &I) {
3269   SmallVector<EVT, 4> ValueVTs;
3270   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3271                   ValueVTs);
3272   unsigned NumValues = ValueVTs.size();
3273   if (NumValues == 0) return;
3274 
3275   SmallVector<SDValue, 4> Values(NumValues);
3276   SDValue Cond     = getValue(I.getOperand(0));
3277   SDValue LHSVal   = getValue(I.getOperand(1));
3278   SDValue RHSVal   = getValue(I.getOperand(2));
3279   SmallVector<SDValue, 1> BaseOps(1, Cond);
3280   ISD::NodeType OpCode =
3281       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3282 
3283   bool IsUnaryAbs = false;
3284   bool Negate = false;
3285 
3286   SDNodeFlags Flags;
3287   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3288     Flags.copyFMF(*FPOp);
3289 
3290   // Min/max matching is only viable if all output VTs are the same.
3291   if (is_splat(ValueVTs)) {
3292     EVT VT = ValueVTs[0];
3293     LLVMContext &Ctx = *DAG.getContext();
3294     auto &TLI = DAG.getTargetLoweringInfo();
3295 
3296     // We care about the legality of the operation after it has been type
3297     // legalized.
3298     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3299       VT = TLI.getTypeToTransformTo(Ctx, VT);
3300 
3301     // If the vselect is legal, assume we want to leave this as a vector setcc +
3302     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3303     // min/max is legal on the scalar type.
3304     bool UseScalarMinMax = VT.isVector() &&
3305       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3306 
3307     Value *LHS, *RHS;
3308     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3309     ISD::NodeType Opc = ISD::DELETED_NODE;
3310     switch (SPR.Flavor) {
3311     case SPF_UMAX:    Opc = ISD::UMAX; break;
3312     case SPF_UMIN:    Opc = ISD::UMIN; break;
3313     case SPF_SMAX:    Opc = ISD::SMAX; break;
3314     case SPF_SMIN:    Opc = ISD::SMIN; break;
3315     case SPF_FMINNUM:
3316       switch (SPR.NaNBehavior) {
3317       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3318       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3319       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3320       case SPNB_RETURNS_ANY: {
3321         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3322           Opc = ISD::FMINNUM;
3323         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3324           Opc = ISD::FMINIMUM;
3325         else if (UseScalarMinMax)
3326           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3327             ISD::FMINNUM : ISD::FMINIMUM;
3328         break;
3329       }
3330       }
3331       break;
3332     case SPF_FMAXNUM:
3333       switch (SPR.NaNBehavior) {
3334       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3335       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3336       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3337       case SPNB_RETURNS_ANY:
3338 
3339         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3340           Opc = ISD::FMAXNUM;
3341         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3342           Opc = ISD::FMAXIMUM;
3343         else if (UseScalarMinMax)
3344           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3345             ISD::FMAXNUM : ISD::FMAXIMUM;
3346         break;
3347       }
3348       break;
3349     case SPF_NABS:
3350       Negate = true;
3351       LLVM_FALLTHROUGH;
3352     case SPF_ABS:
3353       IsUnaryAbs = true;
3354       Opc = ISD::ABS;
3355       break;
3356     default: break;
3357     }
3358 
3359     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3360         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3361          (UseScalarMinMax &&
3362           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3363         // If the underlying comparison instruction is used by any other
3364         // instruction, the consumed instructions won't be destroyed, so it is
3365         // not profitable to convert to a min/max.
3366         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3367       OpCode = Opc;
3368       LHSVal = getValue(LHS);
3369       RHSVal = getValue(RHS);
3370       BaseOps.clear();
3371     }
3372 
3373     if (IsUnaryAbs) {
3374       OpCode = Opc;
3375       LHSVal = getValue(LHS);
3376       BaseOps.clear();
3377     }
3378   }
3379 
3380   if (IsUnaryAbs) {
3381     for (unsigned i = 0; i != NumValues; ++i) {
3382       SDLoc dl = getCurSDLoc();
3383       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3384       Values[i] =
3385           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3386       if (Negate)
3387         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3388                                 Values[i]);
3389     }
3390   } else {
3391     for (unsigned i = 0; i != NumValues; ++i) {
3392       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3393       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3394       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3395       Values[i] = DAG.getNode(
3396           OpCode, getCurSDLoc(),
3397           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3398     }
3399   }
3400 
3401   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3402                            DAG.getVTList(ValueVTs), Values));
3403 }
3404 
3405 void SelectionDAGBuilder::visitTrunc(const User &I) {
3406   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3407   SDValue N = getValue(I.getOperand(0));
3408   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3409                                                         I.getType());
3410   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3411 }
3412 
3413 void SelectionDAGBuilder::visitZExt(const User &I) {
3414   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3415   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3416   SDValue N = getValue(I.getOperand(0));
3417   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3418                                                         I.getType());
3419   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3420 }
3421 
3422 void SelectionDAGBuilder::visitSExt(const User &I) {
3423   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3424   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3425   SDValue N = getValue(I.getOperand(0));
3426   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3427                                                         I.getType());
3428   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3429 }
3430 
3431 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3432   // FPTrunc is never a no-op cast, no need to check
3433   SDValue N = getValue(I.getOperand(0));
3434   SDLoc dl = getCurSDLoc();
3435   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3436   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3437   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3438                            DAG.getTargetConstant(
3439                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3440 }
3441 
3442 void SelectionDAGBuilder::visitFPExt(const User &I) {
3443   // FPExt 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::FP_EXTEND, getCurSDLoc(), DestVT, N));
3448 }
3449 
3450 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3451   // FPToUI 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::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3456 }
3457 
3458 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3459   // FPToSI is never a no-op cast, no need to check
3460   SDValue N = getValue(I.getOperand(0));
3461   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3462                                                         I.getType());
3463   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3464 }
3465 
3466 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3467   // UIToFP is never a no-op cast, no need to check
3468   SDValue N = getValue(I.getOperand(0));
3469   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3470                                                         I.getType());
3471   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3472 }
3473 
3474 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3475   // SIToFP is never a no-op cast, no need to check
3476   SDValue N = getValue(I.getOperand(0));
3477   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3478                                                         I.getType());
3479   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3480 }
3481 
3482 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3483   // What to do depends on the size of the integer and the size of the pointer.
3484   // We can either truncate, zero extend, or no-op, accordingly.
3485   SDValue N = getValue(I.getOperand(0));
3486   auto &TLI = DAG.getTargetLoweringInfo();
3487   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3488                                                         I.getType());
3489   EVT PtrMemVT =
3490       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3491   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3492   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3493   setValue(&I, N);
3494 }
3495 
3496 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3497   // What to do depends on the size of the integer and the size of the pointer.
3498   // We can either truncate, zero extend, or no-op, accordingly.
3499   SDValue N = getValue(I.getOperand(0));
3500   auto &TLI = DAG.getTargetLoweringInfo();
3501   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3502   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3503   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3504   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3505   setValue(&I, N);
3506 }
3507 
3508 void SelectionDAGBuilder::visitBitCast(const User &I) {
3509   SDValue N = getValue(I.getOperand(0));
3510   SDLoc dl = getCurSDLoc();
3511   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3512                                                         I.getType());
3513 
3514   // BitCast assures us that source and destination are the same size so this is
3515   // either a BITCAST or a no-op.
3516   if (DestVT != N.getValueType())
3517     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3518                              DestVT, N)); // convert types.
3519   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3520   // might fold any kind of constant expression to an integer constant and that
3521   // is not what we are looking for. Only recognize a bitcast of a genuine
3522   // constant integer as an opaque constant.
3523   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3524     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3525                                  /*isOpaque*/true));
3526   else
3527     setValue(&I, N);            // noop cast.
3528 }
3529 
3530 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3532   const Value *SV = I.getOperand(0);
3533   SDValue N = getValue(SV);
3534   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3535 
3536   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3537   unsigned DestAS = I.getType()->getPointerAddressSpace();
3538 
3539   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3540     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3541 
3542   setValue(&I, N);
3543 }
3544 
3545 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3546   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3547   SDValue InVec = getValue(I.getOperand(0));
3548   SDValue InVal = getValue(I.getOperand(1));
3549   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3550                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3551   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3552                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3553                            InVec, InVal, InIdx));
3554 }
3555 
3556 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3558   SDValue InVec = getValue(I.getOperand(0));
3559   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3560                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3561   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3562                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3563                            InVec, InIdx));
3564 }
3565 
3566 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3567   SDValue Src1 = getValue(I.getOperand(0));
3568   SDValue Src2 = getValue(I.getOperand(1));
3569   ArrayRef<int> Mask;
3570   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3571     Mask = SVI->getShuffleMask();
3572   else
3573     Mask = cast<ConstantExpr>(I).getShuffleMask();
3574   SDLoc DL = getCurSDLoc();
3575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3576   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3577   EVT SrcVT = Src1.getValueType();
3578 
3579   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3580       VT.isScalableVector()) {
3581     // Canonical splat form of first element of first input vector.
3582     SDValue FirstElt =
3583         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3584                     DAG.getVectorIdxConstant(0, DL));
3585     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3586     return;
3587   }
3588 
3589   // For now, we only handle splats for scalable vectors.
3590   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3591   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3592   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3593 
3594   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3595   unsigned MaskNumElts = Mask.size();
3596 
3597   if (SrcNumElts == MaskNumElts) {
3598     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3599     return;
3600   }
3601 
3602   // Normalize the shuffle vector since mask and vector length don't match.
3603   if (SrcNumElts < MaskNumElts) {
3604     // Mask is longer than the source vectors. We can use concatenate vector to
3605     // make the mask and vectors lengths match.
3606 
3607     if (MaskNumElts % SrcNumElts == 0) {
3608       // Mask length is a multiple of the source vector length.
3609       // Check if the shuffle is some kind of concatenation of the input
3610       // vectors.
3611       unsigned NumConcat = MaskNumElts / SrcNumElts;
3612       bool IsConcat = true;
3613       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3614       for (unsigned i = 0; i != MaskNumElts; ++i) {
3615         int Idx = Mask[i];
3616         if (Idx < 0)
3617           continue;
3618         // Ensure the indices in each SrcVT sized piece are sequential and that
3619         // the same source is used for the whole piece.
3620         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3621             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3622              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3623           IsConcat = false;
3624           break;
3625         }
3626         // Remember which source this index came from.
3627         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3628       }
3629 
3630       // The shuffle is concatenating multiple vectors together. Just emit
3631       // a CONCAT_VECTORS operation.
3632       if (IsConcat) {
3633         SmallVector<SDValue, 8> ConcatOps;
3634         for (auto Src : ConcatSrcs) {
3635           if (Src < 0)
3636             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3637           else if (Src == 0)
3638             ConcatOps.push_back(Src1);
3639           else
3640             ConcatOps.push_back(Src2);
3641         }
3642         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3643         return;
3644       }
3645     }
3646 
3647     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3648     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3649     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3650                                     PaddedMaskNumElts);
3651 
3652     // Pad both vectors with undefs to make them the same length as the mask.
3653     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3654 
3655     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3656     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3657     MOps1[0] = Src1;
3658     MOps2[0] = Src2;
3659 
3660     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3661     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3662 
3663     // Readjust mask for new input vector length.
3664     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3665     for (unsigned i = 0; i != MaskNumElts; ++i) {
3666       int Idx = Mask[i];
3667       if (Idx >= (int)SrcNumElts)
3668         Idx -= SrcNumElts - PaddedMaskNumElts;
3669       MappedOps[i] = Idx;
3670     }
3671 
3672     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3673 
3674     // If the concatenated vector was padded, extract a subvector with the
3675     // correct number of elements.
3676     if (MaskNumElts != PaddedMaskNumElts)
3677       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3678                            DAG.getVectorIdxConstant(0, DL));
3679 
3680     setValue(&I, Result);
3681     return;
3682   }
3683 
3684   if (SrcNumElts > MaskNumElts) {
3685     // Analyze the access pattern of the vector to see if we can extract
3686     // two subvectors and do the shuffle.
3687     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3688     bool CanExtract = true;
3689     for (int Idx : Mask) {
3690       unsigned Input = 0;
3691       if (Idx < 0)
3692         continue;
3693 
3694       if (Idx >= (int)SrcNumElts) {
3695         Input = 1;
3696         Idx -= SrcNumElts;
3697       }
3698 
3699       // If all the indices come from the same MaskNumElts sized portion of
3700       // the sources we can use extract. Also make sure the extract wouldn't
3701       // extract past the end of the source.
3702       int NewStartIdx = alignDown(Idx, MaskNumElts);
3703       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3704           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3705         CanExtract = false;
3706       // Make sure we always update StartIdx as we use it to track if all
3707       // elements are undef.
3708       StartIdx[Input] = NewStartIdx;
3709     }
3710 
3711     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3712       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3713       return;
3714     }
3715     if (CanExtract) {
3716       // Extract appropriate subvector and generate a vector shuffle
3717       for (unsigned Input = 0; Input < 2; ++Input) {
3718         SDValue &Src = Input == 0 ? Src1 : Src2;
3719         if (StartIdx[Input] < 0)
3720           Src = DAG.getUNDEF(VT);
3721         else {
3722           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3723                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3724         }
3725       }
3726 
3727       // Calculate new mask.
3728       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3729       for (int &Idx : MappedOps) {
3730         if (Idx >= (int)SrcNumElts)
3731           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3732         else if (Idx >= 0)
3733           Idx -= StartIdx[0];
3734       }
3735 
3736       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3737       return;
3738     }
3739   }
3740 
3741   // We can't use either concat vectors or extract subvectors so fall back to
3742   // replacing the shuffle with extract and build vector.
3743   // to insert and build vector.
3744   EVT EltVT = VT.getVectorElementType();
3745   SmallVector<SDValue,8> Ops;
3746   for (int Idx : Mask) {
3747     SDValue Res;
3748 
3749     if (Idx < 0) {
3750       Res = DAG.getUNDEF(EltVT);
3751     } else {
3752       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3753       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3754 
3755       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3756                         DAG.getVectorIdxConstant(Idx, DL));
3757     }
3758 
3759     Ops.push_back(Res);
3760   }
3761 
3762   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3763 }
3764 
3765 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3766   ArrayRef<unsigned> Indices;
3767   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3768     Indices = IV->getIndices();
3769   else
3770     Indices = cast<ConstantExpr>(&I)->getIndices();
3771 
3772   const Value *Op0 = I.getOperand(0);
3773   const Value *Op1 = I.getOperand(1);
3774   Type *AggTy = I.getType();
3775   Type *ValTy = Op1->getType();
3776   bool IntoUndef = isa<UndefValue>(Op0);
3777   bool FromUndef = isa<UndefValue>(Op1);
3778 
3779   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3780 
3781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3782   SmallVector<EVT, 4> AggValueVTs;
3783   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3784   SmallVector<EVT, 4> ValValueVTs;
3785   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3786 
3787   unsigned NumAggValues = AggValueVTs.size();
3788   unsigned NumValValues = ValValueVTs.size();
3789   SmallVector<SDValue, 4> Values(NumAggValues);
3790 
3791   // Ignore an insertvalue that produces an empty object
3792   if (!NumAggValues) {
3793     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3794     return;
3795   }
3796 
3797   SDValue Agg = getValue(Op0);
3798   unsigned i = 0;
3799   // Copy the beginning value(s) from the original aggregate.
3800   for (; i != LinearIndex; ++i)
3801     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3802                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3803   // Copy values from the inserted value(s).
3804   if (NumValValues) {
3805     SDValue Val = getValue(Op1);
3806     for (; i != LinearIndex + NumValValues; ++i)
3807       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3808                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3809   }
3810   // Copy remaining value(s) from the original aggregate.
3811   for (; i != NumAggValues; ++i)
3812     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3813                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3814 
3815   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3816                            DAG.getVTList(AggValueVTs), Values));
3817 }
3818 
3819 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3820   ArrayRef<unsigned> Indices;
3821   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3822     Indices = EV->getIndices();
3823   else
3824     Indices = cast<ConstantExpr>(&I)->getIndices();
3825 
3826   const Value *Op0 = I.getOperand(0);
3827   Type *AggTy = Op0->getType();
3828   Type *ValTy = I.getType();
3829   bool OutOfUndef = isa<UndefValue>(Op0);
3830 
3831   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3832 
3833   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3834   SmallVector<EVT, 4> ValValueVTs;
3835   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3836 
3837   unsigned NumValValues = ValValueVTs.size();
3838 
3839   // Ignore a extractvalue that produces an empty object
3840   if (!NumValValues) {
3841     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3842     return;
3843   }
3844 
3845   SmallVector<SDValue, 4> Values(NumValValues);
3846 
3847   SDValue Agg = getValue(Op0);
3848   // Copy out the selected value(s).
3849   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3850     Values[i - LinearIndex] =
3851       OutOfUndef ?
3852         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3853         SDValue(Agg.getNode(), Agg.getResNo() + i);
3854 
3855   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3856                            DAG.getVTList(ValValueVTs), Values));
3857 }
3858 
3859 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3860   Value *Op0 = I.getOperand(0);
3861   // Note that the pointer operand may be a vector of pointers. Take the scalar
3862   // element which holds a pointer.
3863   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3864   SDValue N = getValue(Op0);
3865   SDLoc dl = getCurSDLoc();
3866   auto &TLI = DAG.getTargetLoweringInfo();
3867 
3868   // Normalize Vector GEP - all scalar operands should be converted to the
3869   // splat vector.
3870   bool IsVectorGEP = I.getType()->isVectorTy();
3871   ElementCount VectorElementCount =
3872       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3873                   : ElementCount::getFixed(0);
3874 
3875   if (IsVectorGEP && !N.getValueType().isVector()) {
3876     LLVMContext &Context = *DAG.getContext();
3877     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3878     if (VectorElementCount.isScalable())
3879       N = DAG.getSplatVector(VT, dl, N);
3880     else
3881       N = DAG.getSplatBuildVector(VT, dl, N);
3882   }
3883 
3884   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3885        GTI != E; ++GTI) {
3886     const Value *Idx = GTI.getOperand();
3887     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3888       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3889       if (Field) {
3890         // N = N + Offset
3891         uint64_t Offset =
3892             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3893 
3894         // In an inbounds GEP with an offset that is nonnegative even when
3895         // interpreted as signed, assume there is no unsigned overflow.
3896         SDNodeFlags Flags;
3897         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3898           Flags.setNoUnsignedWrap(true);
3899 
3900         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3901                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3902       }
3903     } else {
3904       // IdxSize is the width of the arithmetic according to IR semantics.
3905       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3906       // (and fix up the result later).
3907       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3908       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3909       TypeSize ElementSize =
3910           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3911       // We intentionally mask away the high bits here; ElementSize may not
3912       // fit in IdxTy.
3913       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3914       bool ElementScalable = ElementSize.isScalable();
3915 
3916       // If this is a scalar constant or a splat vector of constants,
3917       // handle it quickly.
3918       const auto *C = dyn_cast<Constant>(Idx);
3919       if (C && isa<VectorType>(C->getType()))
3920         C = C->getSplatValue();
3921 
3922       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3923       if (CI && CI->isZero())
3924         continue;
3925       if (CI && !ElementScalable) {
3926         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3927         LLVMContext &Context = *DAG.getContext();
3928         SDValue OffsVal;
3929         if (IsVectorGEP)
3930           OffsVal = DAG.getConstant(
3931               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3932         else
3933           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3934 
3935         // In an inbounds GEP with an offset that is nonnegative even when
3936         // interpreted as signed, assume there is no unsigned overflow.
3937         SDNodeFlags Flags;
3938         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3939           Flags.setNoUnsignedWrap(true);
3940 
3941         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3942 
3943         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3944         continue;
3945       }
3946 
3947       // N = N + Idx * ElementMul;
3948       SDValue IdxN = getValue(Idx);
3949 
3950       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3951         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3952                                   VectorElementCount);
3953         if (VectorElementCount.isScalable())
3954           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3955         else
3956           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3957       }
3958 
3959       // If the index is smaller or larger than intptr_t, truncate or extend
3960       // it.
3961       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3962 
3963       if (ElementScalable) {
3964         EVT VScaleTy = N.getValueType().getScalarType();
3965         SDValue VScale = DAG.getNode(
3966             ISD::VSCALE, dl, VScaleTy,
3967             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3968         if (IsVectorGEP)
3969           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3970         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3971       } else {
3972         // If this is a multiply by a power of two, turn it into a shl
3973         // immediately.  This is a very common case.
3974         if (ElementMul != 1) {
3975           if (ElementMul.isPowerOf2()) {
3976             unsigned Amt = ElementMul.logBase2();
3977             IdxN = DAG.getNode(ISD::SHL, dl,
3978                                N.getValueType(), IdxN,
3979                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3980           } else {
3981             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3982                                             IdxN.getValueType());
3983             IdxN = DAG.getNode(ISD::MUL, dl,
3984                                N.getValueType(), IdxN, Scale);
3985           }
3986         }
3987       }
3988 
3989       N = DAG.getNode(ISD::ADD, dl,
3990                       N.getValueType(), N, IdxN);
3991     }
3992   }
3993 
3994   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3995   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3996   if (IsVectorGEP) {
3997     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3998     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3999   }
4000 
4001   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4002     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4003 
4004   setValue(&I, N);
4005 }
4006 
4007 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4008   // If this is a fixed sized alloca in the entry block of the function,
4009   // allocate it statically on the stack.
4010   if (FuncInfo.StaticAllocaMap.count(&I))
4011     return;   // getValue will auto-populate this.
4012 
4013   SDLoc dl = getCurSDLoc();
4014   Type *Ty = I.getAllocatedType();
4015   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4016   auto &DL = DAG.getDataLayout();
4017   TypeSize TySize = DL.getTypeAllocSize(Ty);
4018   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4019 
4020   SDValue AllocSize = getValue(I.getArraySize());
4021 
4022   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4023   if (AllocSize.getValueType() != IntPtr)
4024     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4025 
4026   if (TySize.isScalable())
4027     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4028                             DAG.getVScale(dl, IntPtr,
4029                                           APInt(IntPtr.getScalarSizeInBits(),
4030                                                 TySize.getKnownMinValue())));
4031   else
4032     AllocSize =
4033         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4034                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4035 
4036   // Handle alignment.  If the requested alignment is less than or equal to
4037   // the stack alignment, ignore it.  If the size is greater than or equal to
4038   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4039   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4040   if (*Alignment <= StackAlign)
4041     Alignment = None;
4042 
4043   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4044   // Round the size of the allocation up to the stack alignment size
4045   // by add SA-1 to the size. This doesn't overflow because we're computing
4046   // an address inside an alloca.
4047   SDNodeFlags Flags;
4048   Flags.setNoUnsignedWrap(true);
4049   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4050                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4051 
4052   // Mask out the low bits for alignment purposes.
4053   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4054                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4055 
4056   SDValue Ops[] = {
4057       getRoot(), AllocSize,
4058       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4059   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4060   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4061   setValue(&I, DSA);
4062   DAG.setRoot(DSA.getValue(1));
4063 
4064   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4065 }
4066 
4067 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4068   if (I.isAtomic())
4069     return visitAtomicLoad(I);
4070 
4071   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4072   const Value *SV = I.getOperand(0);
4073   if (TLI.supportSwiftError()) {
4074     // Swifterror values can come from either a function parameter with
4075     // swifterror attribute or an alloca with swifterror attribute.
4076     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4077       if (Arg->hasSwiftErrorAttr())
4078         return visitLoadFromSwiftError(I);
4079     }
4080 
4081     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4082       if (Alloca->isSwiftError())
4083         return visitLoadFromSwiftError(I);
4084     }
4085   }
4086 
4087   SDValue Ptr = getValue(SV);
4088 
4089   Type *Ty = I.getType();
4090   Align Alignment = I.getAlign();
4091 
4092   AAMDNodes AAInfo = I.getAAMetadata();
4093   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4094 
4095   SmallVector<EVT, 4> ValueVTs, MemVTs;
4096   SmallVector<uint64_t, 4> Offsets;
4097   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4098   unsigned NumValues = ValueVTs.size();
4099   if (NumValues == 0)
4100     return;
4101 
4102   bool isVolatile = I.isVolatile();
4103 
4104   SDValue Root;
4105   bool ConstantMemory = false;
4106   if (isVolatile)
4107     // Serialize volatile loads with other side effects.
4108     Root = getRoot();
4109   else if (NumValues > MaxParallelChains)
4110     Root = getMemoryRoot();
4111   else if (AA &&
4112            AA->pointsToConstantMemory(MemoryLocation(
4113                SV,
4114                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4115                AAInfo))) {
4116     // Do not serialize (non-volatile) loads of constant memory with anything.
4117     Root = DAG.getEntryNode();
4118     ConstantMemory = true;
4119   } else {
4120     // Do not serialize non-volatile loads against each other.
4121     Root = DAG.getRoot();
4122   }
4123 
4124   SDLoc dl = getCurSDLoc();
4125 
4126   if (isVolatile)
4127     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4128 
4129   // An aggregate load cannot wrap around the address space, so offsets to its
4130   // parts don't wrap either.
4131   SDNodeFlags Flags;
4132   Flags.setNoUnsignedWrap(true);
4133 
4134   SmallVector<SDValue, 4> Values(NumValues);
4135   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4136   EVT PtrVT = Ptr.getValueType();
4137 
4138   MachineMemOperand::Flags MMOFlags
4139     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4140 
4141   unsigned ChainI = 0;
4142   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4143     // Serializing loads here may result in excessive register pressure, and
4144     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4145     // could recover a bit by hoisting nodes upward in the chain by recognizing
4146     // they are side-effect free or do not alias. The optimizer should really
4147     // avoid this case by converting large object/array copies to llvm.memcpy
4148     // (MaxParallelChains should always remain as failsafe).
4149     if (ChainI == MaxParallelChains) {
4150       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4151       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4152                                   makeArrayRef(Chains.data(), ChainI));
4153       Root = Chain;
4154       ChainI = 0;
4155     }
4156     SDValue A = DAG.getNode(ISD::ADD, dl,
4157                             PtrVT, Ptr,
4158                             DAG.getConstant(Offsets[i], dl, PtrVT),
4159                             Flags);
4160 
4161     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4162                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4163                             MMOFlags, AAInfo, Ranges);
4164     Chains[ChainI] = L.getValue(1);
4165 
4166     if (MemVTs[i] != ValueVTs[i])
4167       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4168 
4169     Values[i] = L;
4170   }
4171 
4172   if (!ConstantMemory) {
4173     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4174                                 makeArrayRef(Chains.data(), ChainI));
4175     if (isVolatile)
4176       DAG.setRoot(Chain);
4177     else
4178       PendingLoads.push_back(Chain);
4179   }
4180 
4181   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4182                            DAG.getVTList(ValueVTs), Values));
4183 }
4184 
4185 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4186   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4187          "call visitStoreToSwiftError when backend supports swifterror");
4188 
4189   SmallVector<EVT, 4> ValueVTs;
4190   SmallVector<uint64_t, 4> Offsets;
4191   const Value *SrcV = I.getOperand(0);
4192   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4193                   SrcV->getType(), ValueVTs, &Offsets);
4194   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4195          "expect a single EVT for swifterror");
4196 
4197   SDValue Src = getValue(SrcV);
4198   // Create a virtual register, then update the virtual register.
4199   Register VReg =
4200       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4201   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4202   // Chain can be getRoot or getControlRoot.
4203   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4204                                       SDValue(Src.getNode(), Src.getResNo()));
4205   DAG.setRoot(CopyNode);
4206 }
4207 
4208 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4209   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4210          "call visitLoadFromSwiftError when backend supports swifterror");
4211 
4212   assert(!I.isVolatile() &&
4213          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4214          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4215          "Support volatile, non temporal, invariant for load_from_swift_error");
4216 
4217   const Value *SV = I.getOperand(0);
4218   Type *Ty = I.getType();
4219   assert(
4220       (!AA ||
4221        !AA->pointsToConstantMemory(MemoryLocation(
4222            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4223            I.getAAMetadata()))) &&
4224       "load_from_swift_error should not be constant memory");
4225 
4226   SmallVector<EVT, 4> ValueVTs;
4227   SmallVector<uint64_t, 4> Offsets;
4228   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4229                   ValueVTs, &Offsets);
4230   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4231          "expect a single EVT for swifterror");
4232 
4233   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4234   SDValue L = DAG.getCopyFromReg(
4235       getRoot(), getCurSDLoc(),
4236       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4237 
4238   setValue(&I, L);
4239 }
4240 
4241 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4242   if (I.isAtomic())
4243     return visitAtomicStore(I);
4244 
4245   const Value *SrcV = I.getOperand(0);
4246   const Value *PtrV = I.getOperand(1);
4247 
4248   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4249   if (TLI.supportSwiftError()) {
4250     // Swifterror values can come from either a function parameter with
4251     // swifterror attribute or an alloca with swifterror attribute.
4252     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4253       if (Arg->hasSwiftErrorAttr())
4254         return visitStoreToSwiftError(I);
4255     }
4256 
4257     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4258       if (Alloca->isSwiftError())
4259         return visitStoreToSwiftError(I);
4260     }
4261   }
4262 
4263   SmallVector<EVT, 4> ValueVTs, MemVTs;
4264   SmallVector<uint64_t, 4> Offsets;
4265   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4266                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4267   unsigned NumValues = ValueVTs.size();
4268   if (NumValues == 0)
4269     return;
4270 
4271   // Get the lowered operands. Note that we do this after
4272   // checking if NumResults is zero, because with zero results
4273   // the operands won't have values in the map.
4274   SDValue Src = getValue(SrcV);
4275   SDValue Ptr = getValue(PtrV);
4276 
4277   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4278   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4279   SDLoc dl = getCurSDLoc();
4280   Align Alignment = I.getAlign();
4281   AAMDNodes AAInfo = I.getAAMetadata();
4282 
4283   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4284 
4285   // An aggregate load cannot wrap around the address space, so offsets to its
4286   // parts don't wrap either.
4287   SDNodeFlags Flags;
4288   Flags.setNoUnsignedWrap(true);
4289 
4290   unsigned ChainI = 0;
4291   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4292     // See visitLoad comments.
4293     if (ChainI == MaxParallelChains) {
4294       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4295                                   makeArrayRef(Chains.data(), ChainI));
4296       Root = Chain;
4297       ChainI = 0;
4298     }
4299     SDValue Add =
4300         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4301     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4302     if (MemVTs[i] != ValueVTs[i])
4303       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4304     SDValue St =
4305         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4306                      Alignment, MMOFlags, AAInfo);
4307     Chains[ChainI] = St;
4308   }
4309 
4310   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4311                                   makeArrayRef(Chains.data(), ChainI));
4312   DAG.setRoot(StoreNode);
4313 }
4314 
4315 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4316                                            bool IsCompressing) {
4317   SDLoc sdl = getCurSDLoc();
4318 
4319   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4320                                MaybeAlign &Alignment) {
4321     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4322     Src0 = I.getArgOperand(0);
4323     Ptr = I.getArgOperand(1);
4324     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4325     Mask = I.getArgOperand(3);
4326   };
4327   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4328                                     MaybeAlign &Alignment) {
4329     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4330     Src0 = I.getArgOperand(0);
4331     Ptr = I.getArgOperand(1);
4332     Mask = I.getArgOperand(2);
4333     Alignment = None;
4334   };
4335 
4336   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4337   MaybeAlign Alignment;
4338   if (IsCompressing)
4339     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4340   else
4341     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4342 
4343   SDValue Ptr = getValue(PtrOperand);
4344   SDValue Src0 = getValue(Src0Operand);
4345   SDValue Mask = getValue(MaskOperand);
4346   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4347 
4348   EVT VT = Src0.getValueType();
4349   if (!Alignment)
4350     Alignment = DAG.getEVTAlign(VT);
4351 
4352   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4353       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4354       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4355   SDValue StoreNode =
4356       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4357                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4358   DAG.setRoot(StoreNode);
4359   setValue(&I, StoreNode);
4360 }
4361 
4362 // Get a uniform base for the Gather/Scatter intrinsic.
4363 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4364 // We try to represent it as a base pointer + vector of indices.
4365 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4366 // The first operand of the GEP may be a single pointer or a vector of pointers
4367 // Example:
4368 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4369 //  or
4370 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4371 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4372 //
4373 // When the first GEP operand is a single pointer - it is the uniform base we
4374 // are looking for. If first operand of the GEP is a splat vector - we
4375 // extract the splat value and use it as a uniform base.
4376 // In all other cases the function returns 'false'.
4377 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4378                            ISD::MemIndexType &IndexType, SDValue &Scale,
4379                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4380   SelectionDAG& DAG = SDB->DAG;
4381   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4382   const DataLayout &DL = DAG.getDataLayout();
4383 
4384   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4385 
4386   // Handle splat constant pointer.
4387   if (auto *C = dyn_cast<Constant>(Ptr)) {
4388     C = C->getSplatValue();
4389     if (!C)
4390       return false;
4391 
4392     Base = SDB->getValue(C);
4393 
4394     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4395     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4396     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4397     IndexType = ISD::SIGNED_SCALED;
4398     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4399     return true;
4400   }
4401 
4402   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4403   if (!GEP || GEP->getParent() != CurBB)
4404     return false;
4405 
4406   if (GEP->getNumOperands() != 2)
4407     return false;
4408 
4409   const Value *BasePtr = GEP->getPointerOperand();
4410   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4411 
4412   // Make sure the base is scalar and the index is a vector.
4413   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4414     return false;
4415 
4416   Base = SDB->getValue(BasePtr);
4417   Index = SDB->getValue(IndexVal);
4418   IndexType = ISD::SIGNED_SCALED;
4419   Scale = DAG.getTargetConstant(
4420               DL.getTypeAllocSize(GEP->getResultElementType()),
4421               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4422   return true;
4423 }
4424 
4425 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4426   SDLoc sdl = getCurSDLoc();
4427 
4428   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4429   const Value *Ptr = I.getArgOperand(1);
4430   SDValue Src0 = getValue(I.getArgOperand(0));
4431   SDValue Mask = getValue(I.getArgOperand(3));
4432   EVT VT = Src0.getValueType();
4433   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4434                         ->getMaybeAlignValue()
4435                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4437 
4438   SDValue Base;
4439   SDValue Index;
4440   ISD::MemIndexType IndexType;
4441   SDValue Scale;
4442   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4443                                     I.getParent());
4444 
4445   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4446   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4447       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4448       // TODO: Make MachineMemOperands aware of scalable
4449       // vectors.
4450       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4451   if (!UniformBase) {
4452     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4453     Index = getValue(Ptr);
4454     IndexType = ISD::SIGNED_UNSCALED;
4455     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4456   }
4457 
4458   EVT IdxVT = Index.getValueType();
4459   EVT EltTy = IdxVT.getVectorElementType();
4460   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4461     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4462     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4463   }
4464 
4465   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4466   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4467                                          Ops, MMO, IndexType, false);
4468   DAG.setRoot(Scatter);
4469   setValue(&I, Scatter);
4470 }
4471 
4472 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4473   SDLoc sdl = getCurSDLoc();
4474 
4475   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4476                               MaybeAlign &Alignment) {
4477     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4478     Ptr = I.getArgOperand(0);
4479     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4480     Mask = I.getArgOperand(2);
4481     Src0 = I.getArgOperand(3);
4482   };
4483   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4484                                  MaybeAlign &Alignment) {
4485     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4486     Ptr = I.getArgOperand(0);
4487     Alignment = None;
4488     Mask = I.getArgOperand(1);
4489     Src0 = I.getArgOperand(2);
4490   };
4491 
4492   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4493   MaybeAlign Alignment;
4494   if (IsExpanding)
4495     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4496   else
4497     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4498 
4499   SDValue Ptr = getValue(PtrOperand);
4500   SDValue Src0 = getValue(Src0Operand);
4501   SDValue Mask = getValue(MaskOperand);
4502   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4503 
4504   EVT VT = Src0.getValueType();
4505   if (!Alignment)
4506     Alignment = DAG.getEVTAlign(VT);
4507 
4508   AAMDNodes AAInfo = I.getAAMetadata();
4509   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4510 
4511   // Do not serialize masked loads of constant memory with anything.
4512   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4513   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4514 
4515   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4516 
4517   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4518       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4519       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4520 
4521   SDValue Load =
4522       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4523                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4524   if (AddToChain)
4525     PendingLoads.push_back(Load.getValue(1));
4526   setValue(&I, Load);
4527 }
4528 
4529 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4530   SDLoc sdl = getCurSDLoc();
4531 
4532   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4533   const Value *Ptr = I.getArgOperand(0);
4534   SDValue Src0 = getValue(I.getArgOperand(3));
4535   SDValue Mask = getValue(I.getArgOperand(2));
4536 
4537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4538   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4539   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4540                         ->getMaybeAlignValue()
4541                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4542 
4543   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4544 
4545   SDValue Root = DAG.getRoot();
4546   SDValue Base;
4547   SDValue Index;
4548   ISD::MemIndexType IndexType;
4549   SDValue Scale;
4550   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4551                                     I.getParent());
4552   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4553   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4554       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4555       // TODO: Make MachineMemOperands aware of scalable
4556       // vectors.
4557       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4558 
4559   if (!UniformBase) {
4560     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4561     Index = getValue(Ptr);
4562     IndexType = ISD::SIGNED_UNSCALED;
4563     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4564   }
4565 
4566   EVT IdxVT = Index.getValueType();
4567   EVT EltTy = IdxVT.getVectorElementType();
4568   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4569     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4570     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4571   }
4572 
4573   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4574   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4575                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4576 
4577   PendingLoads.push_back(Gather.getValue(1));
4578   setValue(&I, Gather);
4579 }
4580 
4581 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4582   SDLoc dl = getCurSDLoc();
4583   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4584   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4585   SyncScope::ID SSID = I.getSyncScopeID();
4586 
4587   SDValue InChain = getRoot();
4588 
4589   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4590   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4591 
4592   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4593   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4594 
4595   MachineFunction &MF = DAG.getMachineFunction();
4596   MachineMemOperand *MMO = MF.getMachineMemOperand(
4597       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4598       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4599       FailureOrdering);
4600 
4601   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4602                                    dl, MemVT, VTs, InChain,
4603                                    getValue(I.getPointerOperand()),
4604                                    getValue(I.getCompareOperand()),
4605                                    getValue(I.getNewValOperand()), MMO);
4606 
4607   SDValue OutChain = L.getValue(2);
4608 
4609   setValue(&I, L);
4610   DAG.setRoot(OutChain);
4611 }
4612 
4613 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4614   SDLoc dl = getCurSDLoc();
4615   ISD::NodeType NT;
4616   switch (I.getOperation()) {
4617   default: llvm_unreachable("Unknown atomicrmw operation");
4618   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4619   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4620   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4621   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4622   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4623   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4624   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4625   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4626   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4627   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4628   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4629   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4630   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4631   }
4632   AtomicOrdering Ordering = I.getOrdering();
4633   SyncScope::ID SSID = I.getSyncScopeID();
4634 
4635   SDValue InChain = getRoot();
4636 
4637   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4638   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4639   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4640 
4641   MachineFunction &MF = DAG.getMachineFunction();
4642   MachineMemOperand *MMO = MF.getMachineMemOperand(
4643       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4644       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4645 
4646   SDValue L =
4647     DAG.getAtomic(NT, dl, MemVT, InChain,
4648                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4649                   MMO);
4650 
4651   SDValue OutChain = L.getValue(1);
4652 
4653   setValue(&I, L);
4654   DAG.setRoot(OutChain);
4655 }
4656 
4657 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4658   SDLoc dl = getCurSDLoc();
4659   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4660   SDValue Ops[3];
4661   Ops[0] = getRoot();
4662   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4663                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4664   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4665                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4666   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4667 }
4668 
4669 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4670   SDLoc dl = getCurSDLoc();
4671   AtomicOrdering Order = I.getOrdering();
4672   SyncScope::ID SSID = I.getSyncScopeID();
4673 
4674   SDValue InChain = getRoot();
4675 
4676   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4677   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4678   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4679 
4680   if (!TLI.supportsUnalignedAtomics() &&
4681       I.getAlignment() < MemVT.getSizeInBits() / 8)
4682     report_fatal_error("Cannot generate unaligned atomic load");
4683 
4684   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4685 
4686   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4687       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4688       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4689 
4690   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4691 
4692   SDValue Ptr = getValue(I.getPointerOperand());
4693 
4694   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4695     // TODO: Once this is better exercised by tests, it should be merged with
4696     // the normal path for loads to prevent future divergence.
4697     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4698     if (MemVT != VT)
4699       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4700 
4701     setValue(&I, L);
4702     SDValue OutChain = L.getValue(1);
4703     if (!I.isUnordered())
4704       DAG.setRoot(OutChain);
4705     else
4706       PendingLoads.push_back(OutChain);
4707     return;
4708   }
4709 
4710   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4711                             Ptr, MMO);
4712 
4713   SDValue OutChain = L.getValue(1);
4714   if (MemVT != VT)
4715     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4716 
4717   setValue(&I, L);
4718   DAG.setRoot(OutChain);
4719 }
4720 
4721 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4722   SDLoc dl = getCurSDLoc();
4723 
4724   AtomicOrdering Ordering = I.getOrdering();
4725   SyncScope::ID SSID = I.getSyncScopeID();
4726 
4727   SDValue InChain = getRoot();
4728 
4729   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4730   EVT MemVT =
4731       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4732 
4733   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4734     report_fatal_error("Cannot generate unaligned atomic store");
4735 
4736   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4737 
4738   MachineFunction &MF = DAG.getMachineFunction();
4739   MachineMemOperand *MMO = MF.getMachineMemOperand(
4740       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4741       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4742 
4743   SDValue Val = getValue(I.getValueOperand());
4744   if (Val.getValueType() != MemVT)
4745     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4746   SDValue Ptr = getValue(I.getPointerOperand());
4747 
4748   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4749     // TODO: Once this is better exercised by tests, it should be merged with
4750     // the normal path for stores to prevent future divergence.
4751     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4752     DAG.setRoot(S);
4753     return;
4754   }
4755   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4756                                    Ptr, Val, MMO);
4757 
4758 
4759   DAG.setRoot(OutChain);
4760 }
4761 
4762 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4763 /// node.
4764 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4765                                                unsigned Intrinsic) {
4766   // Ignore the callsite's attributes. A specific call site may be marked with
4767   // readnone, but the lowering code will expect the chain based on the
4768   // definition.
4769   const Function *F = I.getCalledFunction();
4770   bool HasChain = !F->doesNotAccessMemory();
4771   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4772 
4773   // Build the operand list.
4774   SmallVector<SDValue, 8> Ops;
4775   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4776     if (OnlyLoad) {
4777       // We don't need to serialize loads against other loads.
4778       Ops.push_back(DAG.getRoot());
4779     } else {
4780       Ops.push_back(getRoot());
4781     }
4782   }
4783 
4784   // Info is set by getTgtMemInstrinsic
4785   TargetLowering::IntrinsicInfo Info;
4786   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4787   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4788                                                DAG.getMachineFunction(),
4789                                                Intrinsic);
4790 
4791   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4792   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4793       Info.opc == ISD::INTRINSIC_W_CHAIN)
4794     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4795                                         TLI.getPointerTy(DAG.getDataLayout())));
4796 
4797   // Add all operands of the call to the operand list.
4798   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4799     const Value *Arg = I.getArgOperand(i);
4800     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4801       Ops.push_back(getValue(Arg));
4802       continue;
4803     }
4804 
4805     // Use TargetConstant instead of a regular constant for immarg.
4806     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4807     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4808       assert(CI->getBitWidth() <= 64 &&
4809              "large intrinsic immediates not handled");
4810       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4811     } else {
4812       Ops.push_back(
4813           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4814     }
4815   }
4816 
4817   SmallVector<EVT, 4> ValueVTs;
4818   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4819 
4820   if (HasChain)
4821     ValueVTs.push_back(MVT::Other);
4822 
4823   SDVTList VTs = DAG.getVTList(ValueVTs);
4824 
4825   // Propagate fast-math-flags from IR to node(s).
4826   SDNodeFlags Flags;
4827   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4828     Flags.copyFMF(*FPMO);
4829   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4830 
4831   // Create the node.
4832   SDValue Result;
4833   if (IsTgtIntrinsic) {
4834     // This is target intrinsic that touches memory
4835     Result =
4836         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4837                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4838                                 Info.align, Info.flags, Info.size,
4839                                 I.getAAMetadata());
4840   } else if (!HasChain) {
4841     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4842   } else if (!I.getType()->isVoidTy()) {
4843     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4844   } else {
4845     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4846   }
4847 
4848   if (HasChain) {
4849     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4850     if (OnlyLoad)
4851       PendingLoads.push_back(Chain);
4852     else
4853       DAG.setRoot(Chain);
4854   }
4855 
4856   if (!I.getType()->isVoidTy()) {
4857     if (!isa<VectorType>(I.getType()))
4858       Result = lowerRangeToAssertZExt(DAG, I, Result);
4859 
4860     MaybeAlign Alignment = I.getRetAlign();
4861     if (!Alignment)
4862       Alignment = F->getAttributes().getRetAlignment();
4863     // Insert `assertalign` node if there's an alignment.
4864     if (InsertAssertAlign && Alignment) {
4865       Result =
4866           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4867     }
4868 
4869     setValue(&I, Result);
4870   }
4871 }
4872 
4873 /// GetSignificand - Get the significand and build it into a floating-point
4874 /// number with exponent of 1:
4875 ///
4876 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4877 ///
4878 /// where Op is the hexadecimal representation of floating point value.
4879 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4880   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4881                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4882   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4883                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4884   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4885 }
4886 
4887 /// GetExponent - Get the exponent:
4888 ///
4889 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4890 ///
4891 /// where Op is the hexadecimal representation of floating point value.
4892 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4893                            const TargetLowering &TLI, const SDLoc &dl) {
4894   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4895                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4896   SDValue t1 = DAG.getNode(
4897       ISD::SRL, dl, MVT::i32, t0,
4898       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4899   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4900                            DAG.getConstant(127, dl, MVT::i32));
4901   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4902 }
4903 
4904 /// getF32Constant - Get 32-bit floating point constant.
4905 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4906                               const SDLoc &dl) {
4907   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4908                            MVT::f32);
4909 }
4910 
4911 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4912                                        SelectionDAG &DAG) {
4913   // TODO: What fast-math-flags should be set on the floating-point nodes?
4914 
4915   //   IntegerPartOfX = ((int32_t)(t0);
4916   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4917 
4918   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4919   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4920   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4921 
4922   //   IntegerPartOfX <<= 23;
4923   IntegerPartOfX = DAG.getNode(
4924       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4925       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4926                                   DAG.getDataLayout())));
4927 
4928   SDValue TwoToFractionalPartOfX;
4929   if (LimitFloatPrecision <= 6) {
4930     // For floating-point precision of 6:
4931     //
4932     //   TwoToFractionalPartOfX =
4933     //     0.997535578f +
4934     //       (0.735607626f + 0.252464424f * x) * x;
4935     //
4936     // error 0.0144103317, which is 6 bits
4937     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4938                              getF32Constant(DAG, 0x3e814304, dl));
4939     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4940                              getF32Constant(DAG, 0x3f3c50c8, dl));
4941     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4942     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4943                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4944   } else if (LimitFloatPrecision <= 12) {
4945     // For floating-point precision of 12:
4946     //
4947     //   TwoToFractionalPartOfX =
4948     //     0.999892986f +
4949     //       (0.696457318f +
4950     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4951     //
4952     // error 0.000107046256, which is 13 to 14 bits
4953     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4954                              getF32Constant(DAG, 0x3da235e3, dl));
4955     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4956                              getF32Constant(DAG, 0x3e65b8f3, dl));
4957     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4958     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4959                              getF32Constant(DAG, 0x3f324b07, dl));
4960     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4961     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4962                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4963   } else { // LimitFloatPrecision <= 18
4964     // For floating-point precision of 18:
4965     //
4966     //   TwoToFractionalPartOfX =
4967     //     0.999999982f +
4968     //       (0.693148872f +
4969     //         (0.240227044f +
4970     //           (0.554906021e-1f +
4971     //             (0.961591928e-2f +
4972     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4973     // error 2.47208000*10^(-7), which is better than 18 bits
4974     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4975                              getF32Constant(DAG, 0x3924b03e, dl));
4976     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4977                              getF32Constant(DAG, 0x3ab24b87, dl));
4978     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4979     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4980                              getF32Constant(DAG, 0x3c1d8c17, dl));
4981     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4982     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4983                              getF32Constant(DAG, 0x3d634a1d, dl));
4984     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4985     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4986                              getF32Constant(DAG, 0x3e75fe14, dl));
4987     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4988     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4989                               getF32Constant(DAG, 0x3f317234, dl));
4990     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4991     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4992                                          getF32Constant(DAG, 0x3f800000, dl));
4993   }
4994 
4995   // Add the exponent into the result in integer domain.
4996   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4997   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4998                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4999 }
5000 
5001 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5002 /// limited-precision mode.
5003 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5004                          const TargetLowering &TLI, SDNodeFlags Flags) {
5005   if (Op.getValueType() == MVT::f32 &&
5006       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5007 
5008     // Put the exponent in the right bit position for later addition to the
5009     // final result:
5010     //
5011     // t0 = Op * log2(e)
5012 
5013     // TODO: What fast-math-flags should be set here?
5014     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5015                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5016     return getLimitedPrecisionExp2(t0, dl, DAG);
5017   }
5018 
5019   // No special expansion.
5020   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5021 }
5022 
5023 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5024 /// limited-precision mode.
5025 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5026                          const TargetLowering &TLI, SDNodeFlags Flags) {
5027   // TODO: What fast-math-flags should be set on the floating-point nodes?
5028 
5029   if (Op.getValueType() == MVT::f32 &&
5030       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5031     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5032 
5033     // Scale the exponent by log(2).
5034     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5035     SDValue LogOfExponent =
5036         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5037                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5038 
5039     // Get the significand and build it into a floating-point number with
5040     // exponent of 1.
5041     SDValue X = GetSignificand(DAG, Op1, dl);
5042 
5043     SDValue LogOfMantissa;
5044     if (LimitFloatPrecision <= 6) {
5045       // For floating-point precision of 6:
5046       //
5047       //   LogofMantissa =
5048       //     -1.1609546f +
5049       //       (1.4034025f - 0.23903021f * x) * x;
5050       //
5051       // error 0.0034276066, which is better than 8 bits
5052       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5053                                getF32Constant(DAG, 0xbe74c456, dl));
5054       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5055                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5056       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5057       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5058                                   getF32Constant(DAG, 0x3f949a29, dl));
5059     } else if (LimitFloatPrecision <= 12) {
5060       // For floating-point precision of 12:
5061       //
5062       //   LogOfMantissa =
5063       //     -1.7417939f +
5064       //       (2.8212026f +
5065       //         (-1.4699568f +
5066       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5067       //
5068       // error 0.000061011436, which is 14 bits
5069       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5070                                getF32Constant(DAG, 0xbd67b6d6, dl));
5071       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5072                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5073       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5074       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5075                                getF32Constant(DAG, 0x3fbc278b, dl));
5076       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5077       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5078                                getF32Constant(DAG, 0x40348e95, dl));
5079       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5080       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5081                                   getF32Constant(DAG, 0x3fdef31a, dl));
5082     } else { // LimitFloatPrecision <= 18
5083       // For floating-point precision of 18:
5084       //
5085       //   LogOfMantissa =
5086       //     -2.1072184f +
5087       //       (4.2372794f +
5088       //         (-3.7029485f +
5089       //           (2.2781945f +
5090       //             (-0.87823314f +
5091       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5092       //
5093       // error 0.0000023660568, which is better than 18 bits
5094       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5095                                getF32Constant(DAG, 0xbc91e5ac, dl));
5096       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5097                                getF32Constant(DAG, 0x3e4350aa, dl));
5098       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5099       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5100                                getF32Constant(DAG, 0x3f60d3e3, dl));
5101       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5102       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5103                                getF32Constant(DAG, 0x4011cdf0, dl));
5104       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5105       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5106                                getF32Constant(DAG, 0x406cfd1c, dl));
5107       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5108       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5109                                getF32Constant(DAG, 0x408797cb, dl));
5110       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5111       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5112                                   getF32Constant(DAG, 0x4006dcab, dl));
5113     }
5114 
5115     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5116   }
5117 
5118   // No special expansion.
5119   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5120 }
5121 
5122 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5123 /// limited-precision mode.
5124 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5125                           const TargetLowering &TLI, SDNodeFlags Flags) {
5126   // TODO: What fast-math-flags should be set on the floating-point nodes?
5127 
5128   if (Op.getValueType() == MVT::f32 &&
5129       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5130     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5131 
5132     // Get the exponent.
5133     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5134 
5135     // Get the significand and build it into a floating-point number with
5136     // exponent of 1.
5137     SDValue X = GetSignificand(DAG, Op1, dl);
5138 
5139     // Different possible minimax approximations of significand in
5140     // floating-point for various degrees of accuracy over [1,2].
5141     SDValue Log2ofMantissa;
5142     if (LimitFloatPrecision <= 6) {
5143       // For floating-point precision of 6:
5144       //
5145       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5146       //
5147       // error 0.0049451742, which is more than 7 bits
5148       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5149                                getF32Constant(DAG, 0xbeb08fe0, dl));
5150       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5151                                getF32Constant(DAG, 0x40019463, dl));
5152       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5153       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5154                                    getF32Constant(DAG, 0x3fd6633d, dl));
5155     } else if (LimitFloatPrecision <= 12) {
5156       // For floating-point precision of 12:
5157       //
5158       //   Log2ofMantissa =
5159       //     -2.51285454f +
5160       //       (4.07009056f +
5161       //         (-2.12067489f +
5162       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5163       //
5164       // error 0.0000876136000, which is better than 13 bits
5165       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5166                                getF32Constant(DAG, 0xbda7262e, dl));
5167       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5168                                getF32Constant(DAG, 0x3f25280b, dl));
5169       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5170       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5171                                getF32Constant(DAG, 0x4007b923, dl));
5172       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5173       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5174                                getF32Constant(DAG, 0x40823e2f, dl));
5175       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5176       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5177                                    getF32Constant(DAG, 0x4020d29c, dl));
5178     } else { // LimitFloatPrecision <= 18
5179       // For floating-point precision of 18:
5180       //
5181       //   Log2ofMantissa =
5182       //     -3.0400495f +
5183       //       (6.1129976f +
5184       //         (-5.3420409f +
5185       //           (3.2865683f +
5186       //             (-1.2669343f +
5187       //               (0.27515199f -
5188       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5189       //
5190       // error 0.0000018516, which is better than 18 bits
5191       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5192                                getF32Constant(DAG, 0xbcd2769e, dl));
5193       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5194                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5195       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5196       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5197                                getF32Constant(DAG, 0x3fa22ae7, dl));
5198       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5199       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5200                                getF32Constant(DAG, 0x40525723, dl));
5201       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5202       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5203                                getF32Constant(DAG, 0x40aaf200, dl));
5204       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5205       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5206                                getF32Constant(DAG, 0x40c39dad, dl));
5207       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5208       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5209                                    getF32Constant(DAG, 0x4042902c, dl));
5210     }
5211 
5212     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5213   }
5214 
5215   // No special expansion.
5216   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5217 }
5218 
5219 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5220 /// limited-precision mode.
5221 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5222                            const TargetLowering &TLI, SDNodeFlags Flags) {
5223   // TODO: What fast-math-flags should be set on the floating-point nodes?
5224 
5225   if (Op.getValueType() == MVT::f32 &&
5226       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5227     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5228 
5229     // Scale the exponent by log10(2) [0.30102999f].
5230     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5231     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5232                                         getF32Constant(DAG, 0x3e9a209a, dl));
5233 
5234     // Get the significand and build it into a floating-point number with
5235     // exponent of 1.
5236     SDValue X = GetSignificand(DAG, Op1, dl);
5237 
5238     SDValue Log10ofMantissa;
5239     if (LimitFloatPrecision <= 6) {
5240       // For floating-point precision of 6:
5241       //
5242       //   Log10ofMantissa =
5243       //     -0.50419619f +
5244       //       (0.60948995f - 0.10380950f * x) * x;
5245       //
5246       // error 0.0014886165, which is 6 bits
5247       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5248                                getF32Constant(DAG, 0xbdd49a13, dl));
5249       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5250                                getF32Constant(DAG, 0x3f1c0789, dl));
5251       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5252       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5253                                     getF32Constant(DAG, 0x3f011300, dl));
5254     } else if (LimitFloatPrecision <= 12) {
5255       // For floating-point precision of 12:
5256       //
5257       //   Log10ofMantissa =
5258       //     -0.64831180f +
5259       //       (0.91751397f +
5260       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5261       //
5262       // error 0.00019228036, which is better than 12 bits
5263       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5264                                getF32Constant(DAG, 0x3d431f31, dl));
5265       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5266                                getF32Constant(DAG, 0x3ea21fb2, dl));
5267       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5268       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5269                                getF32Constant(DAG, 0x3f6ae232, dl));
5270       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5271       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5272                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5273     } else { // LimitFloatPrecision <= 18
5274       // For floating-point precision of 18:
5275       //
5276       //   Log10ofMantissa =
5277       //     -0.84299375f +
5278       //       (1.5327582f +
5279       //         (-1.0688956f +
5280       //           (0.49102474f +
5281       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5282       //
5283       // error 0.0000037995730, which is better than 18 bits
5284       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5285                                getF32Constant(DAG, 0x3c5d51ce, dl));
5286       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5287                                getF32Constant(DAG, 0x3e00685a, dl));
5288       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5289       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5290                                getF32Constant(DAG, 0x3efb6798, dl));
5291       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5292       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5293                                getF32Constant(DAG, 0x3f88d192, dl));
5294       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5295       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5296                                getF32Constant(DAG, 0x3fc4316c, dl));
5297       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5298       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5299                                     getF32Constant(DAG, 0x3f57ce70, dl));
5300     }
5301 
5302     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5303   }
5304 
5305   // No special expansion.
5306   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5307 }
5308 
5309 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5310 /// limited-precision mode.
5311 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5312                           const TargetLowering &TLI, SDNodeFlags Flags) {
5313   if (Op.getValueType() == MVT::f32 &&
5314       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5315     return getLimitedPrecisionExp2(Op, dl, DAG);
5316 
5317   // No special expansion.
5318   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5319 }
5320 
5321 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5322 /// limited-precision mode with x == 10.0f.
5323 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5324                          SelectionDAG &DAG, const TargetLowering &TLI,
5325                          SDNodeFlags Flags) {
5326   bool IsExp10 = false;
5327   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5328       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5329     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5330       APFloat Ten(10.0f);
5331       IsExp10 = LHSC->isExactlyValue(Ten);
5332     }
5333   }
5334 
5335   // TODO: What fast-math-flags should be set on the FMUL node?
5336   if (IsExp10) {
5337     // Put the exponent in the right bit position for later addition to the
5338     // final result:
5339     //
5340     //   #define LOG2OF10 3.3219281f
5341     //   t0 = Op * LOG2OF10;
5342     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5343                              getF32Constant(DAG, 0x40549a78, dl));
5344     return getLimitedPrecisionExp2(t0, dl, DAG);
5345   }
5346 
5347   // No special expansion.
5348   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5349 }
5350 
5351 /// ExpandPowI - Expand a llvm.powi intrinsic.
5352 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5353                           SelectionDAG &DAG) {
5354   // If RHS is a constant, we can expand this out to a multiplication tree,
5355   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5356   // optimizing for size, we only want to do this if the expansion would produce
5357   // a small number of multiplies, otherwise we do the full expansion.
5358   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5359     // Get the exponent as a positive value.
5360     unsigned Val = RHSC->getSExtValue();
5361     if ((int)Val < 0) Val = -Val;
5362 
5363     // powi(x, 0) -> 1.0
5364     if (Val == 0)
5365       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5366 
5367     bool OptForSize = DAG.shouldOptForSize();
5368     if (!OptForSize ||
5369         // If optimizing for size, don't insert too many multiplies.
5370         // This inserts up to 5 multiplies.
5371         countPopulation(Val) + Log2_32(Val) < 7) {
5372       // We use the simple binary decomposition method to generate the multiply
5373       // sequence.  There are more optimal ways to do this (for example,
5374       // powi(x,15) generates one more multiply than it should), but this has
5375       // the benefit of being both really simple and much better than a libcall.
5376       SDValue Res;  // Logically starts equal to 1.0
5377       SDValue CurSquare = LHS;
5378       // TODO: Intrinsics should have fast-math-flags that propagate to these
5379       // nodes.
5380       while (Val) {
5381         if (Val & 1) {
5382           if (Res.getNode())
5383             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5384           else
5385             Res = CurSquare;  // 1.0*CurSquare.
5386         }
5387 
5388         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5389                                 CurSquare, CurSquare);
5390         Val >>= 1;
5391       }
5392 
5393       // If the original was negative, invert the result, producing 1/(x*x*x).
5394       if (RHSC->getSExtValue() < 0)
5395         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5396                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5397       return Res;
5398     }
5399   }
5400 
5401   // Otherwise, expand to a libcall.
5402   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5403 }
5404 
5405 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5406                             SDValue LHS, SDValue RHS, SDValue Scale,
5407                             SelectionDAG &DAG, const TargetLowering &TLI) {
5408   EVT VT = LHS.getValueType();
5409   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5410   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5411   LLVMContext &Ctx = *DAG.getContext();
5412 
5413   // If the type is legal but the operation isn't, this node might survive all
5414   // the way to operation legalization. If we end up there and we do not have
5415   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5416   // node.
5417 
5418   // Coax the legalizer into expanding the node during type legalization instead
5419   // by bumping the size by one bit. This will force it to Promote, enabling the
5420   // early expansion and avoiding the need to expand later.
5421 
5422   // We don't have to do this if Scale is 0; that can always be expanded, unless
5423   // it's a saturating signed operation. Those can experience true integer
5424   // division overflow, a case which we must avoid.
5425 
5426   // FIXME: We wouldn't have to do this (or any of the early
5427   // expansion/promotion) if it was possible to expand a libcall of an
5428   // illegal type during operation legalization. But it's not, so things
5429   // get a bit hacky.
5430   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5431   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5432       (TLI.isTypeLegal(VT) ||
5433        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5434     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5435         Opcode, VT, ScaleInt);
5436     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5437       EVT PromVT;
5438       if (VT.isScalarInteger())
5439         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5440       else if (VT.isVector()) {
5441         PromVT = VT.getVectorElementType();
5442         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5443         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5444       } else
5445         llvm_unreachable("Wrong VT for DIVFIX?");
5446       if (Signed) {
5447         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5448         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5449       } else {
5450         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5451         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5452       }
5453       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5454       // For saturating operations, we need to shift up the LHS to get the
5455       // proper saturation width, and then shift down again afterwards.
5456       if (Saturating)
5457         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5458                           DAG.getConstant(1, DL, ShiftTy));
5459       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5460       if (Saturating)
5461         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5462                           DAG.getConstant(1, DL, ShiftTy));
5463       return DAG.getZExtOrTrunc(Res, DL, VT);
5464     }
5465   }
5466 
5467   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5468 }
5469 
5470 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5471 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5472 static void
5473 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5474                      const SDValue &N) {
5475   switch (N.getOpcode()) {
5476   case ISD::CopyFromReg: {
5477     SDValue Op = N.getOperand(1);
5478     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5479                       Op.getValueType().getSizeInBits());
5480     return;
5481   }
5482   case ISD::BITCAST:
5483   case ISD::AssertZext:
5484   case ISD::AssertSext:
5485   case ISD::TRUNCATE:
5486     getUnderlyingArgRegs(Regs, N.getOperand(0));
5487     return;
5488   case ISD::BUILD_PAIR:
5489   case ISD::BUILD_VECTOR:
5490   case ISD::CONCAT_VECTORS:
5491     for (SDValue Op : N->op_values())
5492       getUnderlyingArgRegs(Regs, Op);
5493     return;
5494   default:
5495     return;
5496   }
5497 }
5498 
5499 /// If the DbgValueInst is a dbg_value of a function argument, create the
5500 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5501 /// instruction selection, they will be inserted to the entry BB.
5502 /// We don't currently support this for variadic dbg_values, as they shouldn't
5503 /// appear for function arguments or in the prologue.
5504 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5505     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5506     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5507   const Argument *Arg = dyn_cast<Argument>(V);
5508   if (!Arg)
5509     return false;
5510 
5511   MachineFunction &MF = DAG.getMachineFunction();
5512   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5513 
5514   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5515   // we've been asked to pursue.
5516   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5517                               bool Indirect) {
5518     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5519       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5520       // pointing at the VReg, which will be patched up later.
5521       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5522       auto MIB = BuildMI(MF, DL, Inst);
5523       MIB.addReg(Reg);
5524       MIB.addImm(0);
5525       MIB.addMetadata(Variable);
5526       auto *NewDIExpr = FragExpr;
5527       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5528       // the DIExpression.
5529       if (Indirect)
5530         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5531       MIB.addMetadata(NewDIExpr);
5532       return MIB;
5533     } else {
5534       // Create a completely standard DBG_VALUE.
5535       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5536       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5537     }
5538   };
5539 
5540   if (!IsDbgDeclare) {
5541     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5542     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5543     // the entry block.
5544     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5545     if (!IsInEntryBlock)
5546       return false;
5547 
5548     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5549     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5550     // variable that also is a param.
5551     //
5552     // Although, if we are at the top of the entry block already, we can still
5553     // emit using ArgDbgValue. This might catch some situations when the
5554     // dbg.value refers to an argument that isn't used in the entry block, so
5555     // any CopyToReg node would be optimized out and the only way to express
5556     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5557     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5558     // we should only emit as ArgDbgValue if the Variable is an argument to the
5559     // current function, and the dbg.value intrinsic is found in the entry
5560     // block.
5561     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5562         !DL->getInlinedAt();
5563     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5564     if (!IsInPrologue && !VariableIsFunctionInputArg)
5565       return false;
5566 
5567     // Here we assume that a function argument on IR level only can be used to
5568     // describe one input parameter on source level. If we for example have
5569     // source code like this
5570     //
5571     //    struct A { long x, y; };
5572     //    void foo(struct A a, long b) {
5573     //      ...
5574     //      b = a.x;
5575     //      ...
5576     //    }
5577     //
5578     // and IR like this
5579     //
5580     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5581     //  entry:
5582     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5583     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5584     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5585     //    ...
5586     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5587     //    ...
5588     //
5589     // then the last dbg.value is describing a parameter "b" using a value that
5590     // is an argument. But since we already has used %a1 to describe a parameter
5591     // we should not handle that last dbg.value here (that would result in an
5592     // incorrect hoisting of the DBG_VALUE to the function entry).
5593     // Notice that we allow one dbg.value per IR level argument, to accommodate
5594     // for the situation with fragments above.
5595     if (VariableIsFunctionInputArg) {
5596       unsigned ArgNo = Arg->getArgNo();
5597       if (ArgNo >= FuncInfo.DescribedArgs.size())
5598         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5599       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5600         return false;
5601       FuncInfo.DescribedArgs.set(ArgNo);
5602     }
5603   }
5604 
5605   bool IsIndirect = false;
5606   Optional<MachineOperand> Op;
5607   // Some arguments' frame index is recorded during argument lowering.
5608   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5609   if (FI != std::numeric_limits<int>::max())
5610     Op = MachineOperand::CreateFI(FI);
5611 
5612   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5613   if (!Op && N.getNode()) {
5614     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5615     Register Reg;
5616     if (ArgRegsAndSizes.size() == 1)
5617       Reg = ArgRegsAndSizes.front().first;
5618 
5619     if (Reg && Reg.isVirtual()) {
5620       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5621       Register PR = RegInfo.getLiveInPhysReg(Reg);
5622       if (PR)
5623         Reg = PR;
5624     }
5625     if (Reg) {
5626       Op = MachineOperand::CreateReg(Reg, false);
5627       IsIndirect = IsDbgDeclare;
5628     }
5629   }
5630 
5631   if (!Op && N.getNode()) {
5632     // Check if frame index is available.
5633     SDValue LCandidate = peekThroughBitcasts(N);
5634     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5635       if (FrameIndexSDNode *FINode =
5636           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5637         Op = MachineOperand::CreateFI(FINode->getIndex());
5638   }
5639 
5640   if (!Op) {
5641     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5642     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5643                                          SplitRegs) {
5644       unsigned Offset = 0;
5645       for (const auto &RegAndSize : SplitRegs) {
5646         // If the expression is already a fragment, the current register
5647         // offset+size might extend beyond the fragment. In this case, only
5648         // the register bits that are inside the fragment are relevant.
5649         int RegFragmentSizeInBits = RegAndSize.second;
5650         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5651           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5652           // The register is entirely outside the expression fragment,
5653           // so is irrelevant for debug info.
5654           if (Offset >= ExprFragmentSizeInBits)
5655             break;
5656           // The register is partially outside the expression fragment, only
5657           // the low bits within the fragment are relevant for debug info.
5658           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5659             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5660           }
5661         }
5662 
5663         auto FragmentExpr = DIExpression::createFragmentExpression(
5664             Expr, Offset, RegFragmentSizeInBits);
5665         Offset += RegAndSize.second;
5666         // If a valid fragment expression cannot be created, the variable's
5667         // correct value cannot be determined and so it is set as Undef.
5668         if (!FragmentExpr) {
5669           SDDbgValue *SDV = DAG.getConstantDbgValue(
5670               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5671           DAG.AddDbgValue(SDV, false);
5672           continue;
5673         }
5674         MachineInstr *NewMI =
5675             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare);
5676         FuncInfo.ArgDbgValues.push_back(NewMI);
5677       }
5678     };
5679 
5680     // Check if ValueMap has reg number.
5681     DenseMap<const Value *, Register>::const_iterator
5682       VMI = FuncInfo.ValueMap.find(V);
5683     if (VMI != FuncInfo.ValueMap.end()) {
5684       const auto &TLI = DAG.getTargetLoweringInfo();
5685       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5686                        V->getType(), None);
5687       if (RFV.occupiesMultipleRegs()) {
5688         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5689         return true;
5690       }
5691 
5692       Op = MachineOperand::CreateReg(VMI->second, false);
5693       IsIndirect = IsDbgDeclare;
5694     } else if (ArgRegsAndSizes.size() > 1) {
5695       // This was split due to the calling convention, and no virtual register
5696       // mapping exists for the value.
5697       splitMultiRegDbgValue(ArgRegsAndSizes);
5698       return true;
5699     }
5700   }
5701 
5702   if (!Op)
5703     return false;
5704 
5705   assert(Variable->isValidLocationForIntrinsic(DL) &&
5706          "Expected inlined-at fields to agree");
5707   MachineInstr *NewMI = nullptr;
5708 
5709   if (Op->isReg())
5710     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5711   else
5712     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5713                     Variable, Expr);
5714 
5715   FuncInfo.ArgDbgValues.push_back(NewMI);
5716   return true;
5717 }
5718 
5719 /// Return the appropriate SDDbgValue based on N.
5720 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5721                                              DILocalVariable *Variable,
5722                                              DIExpression *Expr,
5723                                              const DebugLoc &dl,
5724                                              unsigned DbgSDNodeOrder) {
5725   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5726     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5727     // stack slot locations.
5728     //
5729     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5730     // debug values here after optimization:
5731     //
5732     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5733     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5734     //
5735     // Both describe the direct values of their associated variables.
5736     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5737                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5738   }
5739   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5740                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5741 }
5742 
5743 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5744   switch (Intrinsic) {
5745   case Intrinsic::smul_fix:
5746     return ISD::SMULFIX;
5747   case Intrinsic::umul_fix:
5748     return ISD::UMULFIX;
5749   case Intrinsic::smul_fix_sat:
5750     return ISD::SMULFIXSAT;
5751   case Intrinsic::umul_fix_sat:
5752     return ISD::UMULFIXSAT;
5753   case Intrinsic::sdiv_fix:
5754     return ISD::SDIVFIX;
5755   case Intrinsic::udiv_fix:
5756     return ISD::UDIVFIX;
5757   case Intrinsic::sdiv_fix_sat:
5758     return ISD::SDIVFIXSAT;
5759   case Intrinsic::udiv_fix_sat:
5760     return ISD::UDIVFIXSAT;
5761   default:
5762     llvm_unreachable("Unhandled fixed point intrinsic");
5763   }
5764 }
5765 
5766 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5767                                            const char *FunctionName) {
5768   assert(FunctionName && "FunctionName must not be nullptr");
5769   SDValue Callee = DAG.getExternalSymbol(
5770       FunctionName,
5771       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5772   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5773 }
5774 
5775 /// Given a @llvm.call.preallocated.setup, return the corresponding
5776 /// preallocated call.
5777 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5778   assert(cast<CallBase>(PreallocatedSetup)
5779                  ->getCalledFunction()
5780                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5781          "expected call_preallocated_setup Value");
5782   for (auto *U : PreallocatedSetup->users()) {
5783     auto *UseCall = cast<CallBase>(U);
5784     const Function *Fn = UseCall->getCalledFunction();
5785     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5786       return UseCall;
5787     }
5788   }
5789   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5790 }
5791 
5792 /// Lower the call to the specified intrinsic function.
5793 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5794                                              unsigned Intrinsic) {
5795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5796   SDLoc sdl = getCurSDLoc();
5797   DebugLoc dl = getCurDebugLoc();
5798   SDValue Res;
5799 
5800   SDNodeFlags Flags;
5801   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5802     Flags.copyFMF(*FPOp);
5803 
5804   switch (Intrinsic) {
5805   default:
5806     // By default, turn this into a target intrinsic node.
5807     visitTargetIntrinsic(I, Intrinsic);
5808     return;
5809   case Intrinsic::vscale: {
5810     match(&I, m_VScale(DAG.getDataLayout()));
5811     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5812     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5813     return;
5814   }
5815   case Intrinsic::vastart:  visitVAStart(I); return;
5816   case Intrinsic::vaend:    visitVAEnd(I); return;
5817   case Intrinsic::vacopy:   visitVACopy(I); return;
5818   case Intrinsic::returnaddress:
5819     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5820                              TLI.getPointerTy(DAG.getDataLayout()),
5821                              getValue(I.getArgOperand(0))));
5822     return;
5823   case Intrinsic::addressofreturnaddress:
5824     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5825                              TLI.getPointerTy(DAG.getDataLayout())));
5826     return;
5827   case Intrinsic::sponentry:
5828     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5829                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5830     return;
5831   case Intrinsic::frameaddress:
5832     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5833                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5834                              getValue(I.getArgOperand(0))));
5835     return;
5836   case Intrinsic::read_volatile_register:
5837   case Intrinsic::read_register: {
5838     Value *Reg = I.getArgOperand(0);
5839     SDValue Chain = getRoot();
5840     SDValue RegName =
5841         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5842     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5843     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5844       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5845     setValue(&I, Res);
5846     DAG.setRoot(Res.getValue(1));
5847     return;
5848   }
5849   case Intrinsic::write_register: {
5850     Value *Reg = I.getArgOperand(0);
5851     Value *RegValue = I.getArgOperand(1);
5852     SDValue Chain = getRoot();
5853     SDValue RegName =
5854         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5855     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5856                             RegName, getValue(RegValue)));
5857     return;
5858   }
5859   case Intrinsic::memcpy: {
5860     const auto &MCI = cast<MemCpyInst>(I);
5861     SDValue Op1 = getValue(I.getArgOperand(0));
5862     SDValue Op2 = getValue(I.getArgOperand(1));
5863     SDValue Op3 = getValue(I.getArgOperand(2));
5864     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5865     Align DstAlign = MCI.getDestAlign().valueOrOne();
5866     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5867     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5868     bool isVol = MCI.isVolatile();
5869     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5870     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5871     // node.
5872     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5873     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5874                                /* AlwaysInline */ false, isTC,
5875                                MachinePointerInfo(I.getArgOperand(0)),
5876                                MachinePointerInfo(I.getArgOperand(1)),
5877                                I.getAAMetadata());
5878     updateDAGForMaybeTailCall(MC);
5879     return;
5880   }
5881   case Intrinsic::memcpy_inline: {
5882     const auto &MCI = cast<MemCpyInlineInst>(I);
5883     SDValue Dst = getValue(I.getArgOperand(0));
5884     SDValue Src = getValue(I.getArgOperand(1));
5885     SDValue Size = getValue(I.getArgOperand(2));
5886     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5887     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5888     Align DstAlign = MCI.getDestAlign().valueOrOne();
5889     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5890     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5891     bool isVol = MCI.isVolatile();
5892     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5893     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5894     // node.
5895     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5896                                /* AlwaysInline */ true, isTC,
5897                                MachinePointerInfo(I.getArgOperand(0)),
5898                                MachinePointerInfo(I.getArgOperand(1)),
5899                                I.getAAMetadata());
5900     updateDAGForMaybeTailCall(MC);
5901     return;
5902   }
5903   case Intrinsic::memset: {
5904     const auto &MSI = cast<MemSetInst>(I);
5905     SDValue Op1 = getValue(I.getArgOperand(0));
5906     SDValue Op2 = getValue(I.getArgOperand(1));
5907     SDValue Op3 = getValue(I.getArgOperand(2));
5908     // @llvm.memset defines 0 and 1 to both mean no alignment.
5909     Align Alignment = MSI.getDestAlign().valueOrOne();
5910     bool isVol = MSI.isVolatile();
5911     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5912     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5913     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5914                                MachinePointerInfo(I.getArgOperand(0)),
5915                                I.getAAMetadata());
5916     updateDAGForMaybeTailCall(MS);
5917     return;
5918   }
5919   case Intrinsic::memmove: {
5920     const auto &MMI = cast<MemMoveInst>(I);
5921     SDValue Op1 = getValue(I.getArgOperand(0));
5922     SDValue Op2 = getValue(I.getArgOperand(1));
5923     SDValue Op3 = getValue(I.getArgOperand(2));
5924     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5925     Align DstAlign = MMI.getDestAlign().valueOrOne();
5926     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5927     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5928     bool isVol = MMI.isVolatile();
5929     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5930     // FIXME: Support passing different dest/src alignments to the memmove DAG
5931     // node.
5932     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5933     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5934                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5935                                 MachinePointerInfo(I.getArgOperand(1)),
5936                                 I.getAAMetadata());
5937     updateDAGForMaybeTailCall(MM);
5938     return;
5939   }
5940   case Intrinsic::memcpy_element_unordered_atomic: {
5941     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5942     SDValue Dst = getValue(MI.getRawDest());
5943     SDValue Src = getValue(MI.getRawSource());
5944     SDValue Length = getValue(MI.getLength());
5945 
5946     unsigned DstAlign = MI.getDestAlignment();
5947     unsigned SrcAlign = MI.getSourceAlignment();
5948     Type *LengthTy = MI.getLength()->getType();
5949     unsigned ElemSz = MI.getElementSizeInBytes();
5950     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5951     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5952                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5953                                      MachinePointerInfo(MI.getRawDest()),
5954                                      MachinePointerInfo(MI.getRawSource()));
5955     updateDAGForMaybeTailCall(MC);
5956     return;
5957   }
5958   case Intrinsic::memmove_element_unordered_atomic: {
5959     auto &MI = cast<AtomicMemMoveInst>(I);
5960     SDValue Dst = getValue(MI.getRawDest());
5961     SDValue Src = getValue(MI.getRawSource());
5962     SDValue Length = getValue(MI.getLength());
5963 
5964     unsigned DstAlign = MI.getDestAlignment();
5965     unsigned SrcAlign = MI.getSourceAlignment();
5966     Type *LengthTy = MI.getLength()->getType();
5967     unsigned ElemSz = MI.getElementSizeInBytes();
5968     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5969     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5970                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5971                                       MachinePointerInfo(MI.getRawDest()),
5972                                       MachinePointerInfo(MI.getRawSource()));
5973     updateDAGForMaybeTailCall(MC);
5974     return;
5975   }
5976   case Intrinsic::memset_element_unordered_atomic: {
5977     auto &MI = cast<AtomicMemSetInst>(I);
5978     SDValue Dst = getValue(MI.getRawDest());
5979     SDValue Val = getValue(MI.getValue());
5980     SDValue Length = getValue(MI.getLength());
5981 
5982     unsigned DstAlign = MI.getDestAlignment();
5983     Type *LengthTy = MI.getLength()->getType();
5984     unsigned ElemSz = MI.getElementSizeInBytes();
5985     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5986     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5987                                      LengthTy, ElemSz, isTC,
5988                                      MachinePointerInfo(MI.getRawDest()));
5989     updateDAGForMaybeTailCall(MC);
5990     return;
5991   }
5992   case Intrinsic::call_preallocated_setup: {
5993     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5994     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5995     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5996                               getRoot(), SrcValue);
5997     setValue(&I, Res);
5998     DAG.setRoot(Res);
5999     return;
6000   }
6001   case Intrinsic::call_preallocated_arg: {
6002     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6003     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6004     SDValue Ops[3];
6005     Ops[0] = getRoot();
6006     Ops[1] = SrcValue;
6007     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6008                                    MVT::i32); // arg index
6009     SDValue Res = DAG.getNode(
6010         ISD::PREALLOCATED_ARG, sdl,
6011         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6012     setValue(&I, Res);
6013     DAG.setRoot(Res.getValue(1));
6014     return;
6015   }
6016   case Intrinsic::dbg_addr:
6017   case Intrinsic::dbg_declare: {
6018     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6019     // they are non-variadic.
6020     const auto &DI = cast<DbgVariableIntrinsic>(I);
6021     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6022     DILocalVariable *Variable = DI.getVariable();
6023     DIExpression *Expression = DI.getExpression();
6024     dropDanglingDebugInfo(Variable, Expression);
6025     assert(Variable && "Missing variable");
6026     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6027                       << "\n");
6028     // Check if address has undef value.
6029     const Value *Address = DI.getVariableLocationOp(0);
6030     if (!Address || isa<UndefValue>(Address) ||
6031         (Address->use_empty() && !isa<Argument>(Address))) {
6032       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6033                         << " (bad/undef/unused-arg address)\n");
6034       return;
6035     }
6036 
6037     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6038 
6039     // Check if this variable can be described by a frame index, typically
6040     // either as a static alloca or a byval parameter.
6041     int FI = std::numeric_limits<int>::max();
6042     if (const auto *AI =
6043             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6044       if (AI->isStaticAlloca()) {
6045         auto I = FuncInfo.StaticAllocaMap.find(AI);
6046         if (I != FuncInfo.StaticAllocaMap.end())
6047           FI = I->second;
6048       }
6049     } else if (const auto *Arg = dyn_cast<Argument>(
6050                    Address->stripInBoundsConstantOffsets())) {
6051       FI = FuncInfo.getArgumentFrameIndex(Arg);
6052     }
6053 
6054     // llvm.dbg.addr is control dependent and always generates indirect
6055     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6056     // the MachineFunction variable table.
6057     if (FI != std::numeric_limits<int>::max()) {
6058       if (Intrinsic == Intrinsic::dbg_addr) {
6059         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6060             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6061             dl, SDNodeOrder);
6062         DAG.AddDbgValue(SDV, isParameter);
6063       } else {
6064         LLVM_DEBUG(dbgs() << "Skipping " << DI
6065                           << " (variable info stashed in MF side table)\n");
6066       }
6067       return;
6068     }
6069 
6070     SDValue &N = NodeMap[Address];
6071     if (!N.getNode() && isa<Argument>(Address))
6072       // Check unused arguments map.
6073       N = UnusedArgNodeMap[Address];
6074     SDDbgValue *SDV;
6075     if (N.getNode()) {
6076       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6077         Address = BCI->getOperand(0);
6078       // Parameters are handled specially.
6079       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6080       if (isParameter && FINode) {
6081         // Byval parameter. We have a frame index at this point.
6082         SDV =
6083             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6084                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6085       } else if (isa<Argument>(Address)) {
6086         // Address is an argument, so try to emit its dbg value using
6087         // virtual register info from the FuncInfo.ValueMap.
6088         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6089         return;
6090       } else {
6091         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6092                               true, dl, SDNodeOrder);
6093       }
6094       DAG.AddDbgValue(SDV, isParameter);
6095     } else {
6096       // If Address is an argument then try to emit its dbg value using
6097       // virtual register info from the FuncInfo.ValueMap.
6098       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6099                                     N)) {
6100         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6101                           << " (could not emit func-arg dbg_value)\n");
6102       }
6103     }
6104     return;
6105   }
6106   case Intrinsic::dbg_label: {
6107     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6108     DILabel *Label = DI.getLabel();
6109     assert(Label && "Missing label");
6110 
6111     SDDbgLabel *SDV;
6112     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6113     DAG.AddDbgLabel(SDV);
6114     return;
6115   }
6116   case Intrinsic::dbg_value: {
6117     const DbgValueInst &DI = cast<DbgValueInst>(I);
6118     assert(DI.getVariable() && "Missing variable");
6119 
6120     DILocalVariable *Variable = DI.getVariable();
6121     DIExpression *Expression = DI.getExpression();
6122     dropDanglingDebugInfo(Variable, Expression);
6123     SmallVector<Value *, 4> Values(DI.getValues());
6124     if (Values.empty())
6125       return;
6126 
6127     if (llvm::is_contained(Values, nullptr))
6128       return;
6129 
6130     bool IsVariadic = DI.hasArgList();
6131     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6132                           SDNodeOrder, IsVariadic))
6133       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6134     return;
6135   }
6136 
6137   case Intrinsic::eh_typeid_for: {
6138     // Find the type id for the given typeinfo.
6139     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6140     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6141     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6142     setValue(&I, Res);
6143     return;
6144   }
6145 
6146   case Intrinsic::eh_return_i32:
6147   case Intrinsic::eh_return_i64:
6148     DAG.getMachineFunction().setCallsEHReturn(true);
6149     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6150                             MVT::Other,
6151                             getControlRoot(),
6152                             getValue(I.getArgOperand(0)),
6153                             getValue(I.getArgOperand(1))));
6154     return;
6155   case Intrinsic::eh_unwind_init:
6156     DAG.getMachineFunction().setCallsUnwindInit(true);
6157     return;
6158   case Intrinsic::eh_dwarf_cfa:
6159     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6160                              TLI.getPointerTy(DAG.getDataLayout()),
6161                              getValue(I.getArgOperand(0))));
6162     return;
6163   case Intrinsic::eh_sjlj_callsite: {
6164     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6165     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6166     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6167     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6168 
6169     MMI.setCurrentCallSite(CI->getZExtValue());
6170     return;
6171   }
6172   case Intrinsic::eh_sjlj_functioncontext: {
6173     // Get and store the index of the function context.
6174     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6175     AllocaInst *FnCtx =
6176       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6177     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6178     MFI.setFunctionContextIndex(FI);
6179     return;
6180   }
6181   case Intrinsic::eh_sjlj_setjmp: {
6182     SDValue Ops[2];
6183     Ops[0] = getRoot();
6184     Ops[1] = getValue(I.getArgOperand(0));
6185     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6186                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6187     setValue(&I, Op.getValue(0));
6188     DAG.setRoot(Op.getValue(1));
6189     return;
6190   }
6191   case Intrinsic::eh_sjlj_longjmp:
6192     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6193                             getRoot(), getValue(I.getArgOperand(0))));
6194     return;
6195   case Intrinsic::eh_sjlj_setup_dispatch:
6196     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6197                             getRoot()));
6198     return;
6199   case Intrinsic::masked_gather:
6200     visitMaskedGather(I);
6201     return;
6202   case Intrinsic::masked_load:
6203     visitMaskedLoad(I);
6204     return;
6205   case Intrinsic::masked_scatter:
6206     visitMaskedScatter(I);
6207     return;
6208   case Intrinsic::masked_store:
6209     visitMaskedStore(I);
6210     return;
6211   case Intrinsic::masked_expandload:
6212     visitMaskedLoad(I, true /* IsExpanding */);
6213     return;
6214   case Intrinsic::masked_compressstore:
6215     visitMaskedStore(I, true /* IsCompressing */);
6216     return;
6217   case Intrinsic::powi:
6218     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6219                             getValue(I.getArgOperand(1)), DAG));
6220     return;
6221   case Intrinsic::log:
6222     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6223     return;
6224   case Intrinsic::log2:
6225     setValue(&I,
6226              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6227     return;
6228   case Intrinsic::log10:
6229     setValue(&I,
6230              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6231     return;
6232   case Intrinsic::exp:
6233     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6234     return;
6235   case Intrinsic::exp2:
6236     setValue(&I,
6237              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6238     return;
6239   case Intrinsic::pow:
6240     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6241                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6242     return;
6243   case Intrinsic::sqrt:
6244   case Intrinsic::fabs:
6245   case Intrinsic::sin:
6246   case Intrinsic::cos:
6247   case Intrinsic::floor:
6248   case Intrinsic::ceil:
6249   case Intrinsic::trunc:
6250   case Intrinsic::rint:
6251   case Intrinsic::nearbyint:
6252   case Intrinsic::round:
6253   case Intrinsic::roundeven:
6254   case Intrinsic::canonicalize: {
6255     unsigned Opcode;
6256     switch (Intrinsic) {
6257     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6258     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6259     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6260     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6261     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6262     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6263     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6264     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6265     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6266     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6267     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6268     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6269     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6270     }
6271 
6272     setValue(&I, DAG.getNode(Opcode, sdl,
6273                              getValue(I.getArgOperand(0)).getValueType(),
6274                              getValue(I.getArgOperand(0)), Flags));
6275     return;
6276   }
6277   case Intrinsic::lround:
6278   case Intrinsic::llround:
6279   case Intrinsic::lrint:
6280   case Intrinsic::llrint: {
6281     unsigned Opcode;
6282     switch (Intrinsic) {
6283     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6284     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6285     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6286     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6287     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6288     }
6289 
6290     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6291     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6292                              getValue(I.getArgOperand(0))));
6293     return;
6294   }
6295   case Intrinsic::minnum:
6296     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6297                              getValue(I.getArgOperand(0)).getValueType(),
6298                              getValue(I.getArgOperand(0)),
6299                              getValue(I.getArgOperand(1)), Flags));
6300     return;
6301   case Intrinsic::maxnum:
6302     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6303                              getValue(I.getArgOperand(0)).getValueType(),
6304                              getValue(I.getArgOperand(0)),
6305                              getValue(I.getArgOperand(1)), Flags));
6306     return;
6307   case Intrinsic::minimum:
6308     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6309                              getValue(I.getArgOperand(0)).getValueType(),
6310                              getValue(I.getArgOperand(0)),
6311                              getValue(I.getArgOperand(1)), Flags));
6312     return;
6313   case Intrinsic::maximum:
6314     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6315                              getValue(I.getArgOperand(0)).getValueType(),
6316                              getValue(I.getArgOperand(0)),
6317                              getValue(I.getArgOperand(1)), Flags));
6318     return;
6319   case Intrinsic::copysign:
6320     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6321                              getValue(I.getArgOperand(0)).getValueType(),
6322                              getValue(I.getArgOperand(0)),
6323                              getValue(I.getArgOperand(1)), Flags));
6324     return;
6325   case Intrinsic::arithmetic_fence: {
6326     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6327                              getValue(I.getArgOperand(0)).getValueType(),
6328                              getValue(I.getArgOperand(0)), Flags));
6329     return;
6330   }
6331   case Intrinsic::fma:
6332     setValue(&I, DAG.getNode(
6333                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6334                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6335                      getValue(I.getArgOperand(2)), Flags));
6336     return;
6337 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6338   case Intrinsic::INTRINSIC:
6339 #include "llvm/IR/ConstrainedOps.def"
6340     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6341     return;
6342 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6343 #include "llvm/IR/VPIntrinsics.def"
6344     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6345     return;
6346   case Intrinsic::fmuladd: {
6347     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6348     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6349         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6350       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6351                                getValue(I.getArgOperand(0)).getValueType(),
6352                                getValue(I.getArgOperand(0)),
6353                                getValue(I.getArgOperand(1)),
6354                                getValue(I.getArgOperand(2)), Flags));
6355     } else {
6356       // TODO: Intrinsic calls should have fast-math-flags.
6357       SDValue Mul = DAG.getNode(
6358           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6359           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6360       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6361                                 getValue(I.getArgOperand(0)).getValueType(),
6362                                 Mul, getValue(I.getArgOperand(2)), Flags);
6363       setValue(&I, Add);
6364     }
6365     return;
6366   }
6367   case Intrinsic::convert_to_fp16:
6368     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6369                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6370                                          getValue(I.getArgOperand(0)),
6371                                          DAG.getTargetConstant(0, sdl,
6372                                                                MVT::i32))));
6373     return;
6374   case Intrinsic::convert_from_fp16:
6375     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6376                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6377                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6378                                          getValue(I.getArgOperand(0)))));
6379     return;
6380   case Intrinsic::fptosi_sat: {
6381     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6382     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6383                              getValue(I.getArgOperand(0)),
6384                              DAG.getValueType(VT.getScalarType())));
6385     return;
6386   }
6387   case Intrinsic::fptoui_sat: {
6388     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6389     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6390                              getValue(I.getArgOperand(0)),
6391                              DAG.getValueType(VT.getScalarType())));
6392     return;
6393   }
6394   case Intrinsic::set_rounding:
6395     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6396                       {getRoot(), getValue(I.getArgOperand(0))});
6397     setValue(&I, Res);
6398     DAG.setRoot(Res.getValue(0));
6399     return;
6400   case Intrinsic::pcmarker: {
6401     SDValue Tmp = getValue(I.getArgOperand(0));
6402     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6403     return;
6404   }
6405   case Intrinsic::readcyclecounter: {
6406     SDValue Op = getRoot();
6407     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6408                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6409     setValue(&I, Res);
6410     DAG.setRoot(Res.getValue(1));
6411     return;
6412   }
6413   case Intrinsic::bitreverse:
6414     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6415                              getValue(I.getArgOperand(0)).getValueType(),
6416                              getValue(I.getArgOperand(0))));
6417     return;
6418   case Intrinsic::bswap:
6419     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6420                              getValue(I.getArgOperand(0)).getValueType(),
6421                              getValue(I.getArgOperand(0))));
6422     return;
6423   case Intrinsic::cttz: {
6424     SDValue Arg = getValue(I.getArgOperand(0));
6425     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6426     EVT Ty = Arg.getValueType();
6427     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6428                              sdl, Ty, Arg));
6429     return;
6430   }
6431   case Intrinsic::ctlz: {
6432     SDValue Arg = getValue(I.getArgOperand(0));
6433     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6434     EVT Ty = Arg.getValueType();
6435     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6436                              sdl, Ty, Arg));
6437     return;
6438   }
6439   case Intrinsic::ctpop: {
6440     SDValue Arg = getValue(I.getArgOperand(0));
6441     EVT Ty = Arg.getValueType();
6442     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6443     return;
6444   }
6445   case Intrinsic::fshl:
6446   case Intrinsic::fshr: {
6447     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6448     SDValue X = getValue(I.getArgOperand(0));
6449     SDValue Y = getValue(I.getArgOperand(1));
6450     SDValue Z = getValue(I.getArgOperand(2));
6451     EVT VT = X.getValueType();
6452 
6453     if (X == Y) {
6454       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6455       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6456     } else {
6457       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6458       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6459     }
6460     return;
6461   }
6462   case Intrinsic::sadd_sat: {
6463     SDValue Op1 = getValue(I.getArgOperand(0));
6464     SDValue Op2 = getValue(I.getArgOperand(1));
6465     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6466     return;
6467   }
6468   case Intrinsic::uadd_sat: {
6469     SDValue Op1 = getValue(I.getArgOperand(0));
6470     SDValue Op2 = getValue(I.getArgOperand(1));
6471     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6472     return;
6473   }
6474   case Intrinsic::ssub_sat: {
6475     SDValue Op1 = getValue(I.getArgOperand(0));
6476     SDValue Op2 = getValue(I.getArgOperand(1));
6477     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6478     return;
6479   }
6480   case Intrinsic::usub_sat: {
6481     SDValue Op1 = getValue(I.getArgOperand(0));
6482     SDValue Op2 = getValue(I.getArgOperand(1));
6483     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6484     return;
6485   }
6486   case Intrinsic::sshl_sat: {
6487     SDValue Op1 = getValue(I.getArgOperand(0));
6488     SDValue Op2 = getValue(I.getArgOperand(1));
6489     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6490     return;
6491   }
6492   case Intrinsic::ushl_sat: {
6493     SDValue Op1 = getValue(I.getArgOperand(0));
6494     SDValue Op2 = getValue(I.getArgOperand(1));
6495     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6496     return;
6497   }
6498   case Intrinsic::smul_fix:
6499   case Intrinsic::umul_fix:
6500   case Intrinsic::smul_fix_sat:
6501   case Intrinsic::umul_fix_sat: {
6502     SDValue Op1 = getValue(I.getArgOperand(0));
6503     SDValue Op2 = getValue(I.getArgOperand(1));
6504     SDValue Op3 = getValue(I.getArgOperand(2));
6505     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6506                              Op1.getValueType(), Op1, Op2, Op3));
6507     return;
6508   }
6509   case Intrinsic::sdiv_fix:
6510   case Intrinsic::udiv_fix:
6511   case Intrinsic::sdiv_fix_sat:
6512   case Intrinsic::udiv_fix_sat: {
6513     SDValue Op1 = getValue(I.getArgOperand(0));
6514     SDValue Op2 = getValue(I.getArgOperand(1));
6515     SDValue Op3 = getValue(I.getArgOperand(2));
6516     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6517                               Op1, Op2, Op3, DAG, TLI));
6518     return;
6519   }
6520   case Intrinsic::smax: {
6521     SDValue Op1 = getValue(I.getArgOperand(0));
6522     SDValue Op2 = getValue(I.getArgOperand(1));
6523     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6524     return;
6525   }
6526   case Intrinsic::smin: {
6527     SDValue Op1 = getValue(I.getArgOperand(0));
6528     SDValue Op2 = getValue(I.getArgOperand(1));
6529     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6530     return;
6531   }
6532   case Intrinsic::umax: {
6533     SDValue Op1 = getValue(I.getArgOperand(0));
6534     SDValue Op2 = getValue(I.getArgOperand(1));
6535     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6536     return;
6537   }
6538   case Intrinsic::umin: {
6539     SDValue Op1 = getValue(I.getArgOperand(0));
6540     SDValue Op2 = getValue(I.getArgOperand(1));
6541     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6542     return;
6543   }
6544   case Intrinsic::abs: {
6545     // TODO: Preserve "int min is poison" arg in SDAG?
6546     SDValue Op1 = getValue(I.getArgOperand(0));
6547     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6548     return;
6549   }
6550   case Intrinsic::stacksave: {
6551     SDValue Op = getRoot();
6552     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6553     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6554     setValue(&I, Res);
6555     DAG.setRoot(Res.getValue(1));
6556     return;
6557   }
6558   case Intrinsic::stackrestore:
6559     Res = getValue(I.getArgOperand(0));
6560     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6561     return;
6562   case Intrinsic::get_dynamic_area_offset: {
6563     SDValue Op = getRoot();
6564     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6565     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6566     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6567     // target.
6568     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6569       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6570                          " intrinsic!");
6571     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6572                       Op);
6573     DAG.setRoot(Op);
6574     setValue(&I, Res);
6575     return;
6576   }
6577   case Intrinsic::stackguard: {
6578     MachineFunction &MF = DAG.getMachineFunction();
6579     const Module &M = *MF.getFunction().getParent();
6580     SDValue Chain = getRoot();
6581     if (TLI.useLoadStackGuardNode()) {
6582       Res = getLoadStackGuard(DAG, sdl, Chain);
6583     } else {
6584       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6585       const Value *Global = TLI.getSDagStackGuard(M);
6586       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6587       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6588                         MachinePointerInfo(Global, 0), Align,
6589                         MachineMemOperand::MOVolatile);
6590     }
6591     if (TLI.useStackGuardXorFP())
6592       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6593     DAG.setRoot(Chain);
6594     setValue(&I, Res);
6595     return;
6596   }
6597   case Intrinsic::stackprotector: {
6598     // Emit code into the DAG to store the stack guard onto the stack.
6599     MachineFunction &MF = DAG.getMachineFunction();
6600     MachineFrameInfo &MFI = MF.getFrameInfo();
6601     SDValue Src, Chain = getRoot();
6602 
6603     if (TLI.useLoadStackGuardNode())
6604       Src = getLoadStackGuard(DAG, sdl, Chain);
6605     else
6606       Src = getValue(I.getArgOperand(0));   // The guard's value.
6607 
6608     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6609 
6610     int FI = FuncInfo.StaticAllocaMap[Slot];
6611     MFI.setStackProtectorIndex(FI);
6612     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6613 
6614     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6615 
6616     // Store the stack protector onto the stack.
6617     Res = DAG.getStore(
6618         Chain, sdl, Src, FIN,
6619         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6620         MaybeAlign(), MachineMemOperand::MOVolatile);
6621     setValue(&I, Res);
6622     DAG.setRoot(Res);
6623     return;
6624   }
6625   case Intrinsic::objectsize:
6626     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6627 
6628   case Intrinsic::is_constant:
6629     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6630 
6631   case Intrinsic::annotation:
6632   case Intrinsic::ptr_annotation:
6633   case Intrinsic::launder_invariant_group:
6634   case Intrinsic::strip_invariant_group:
6635     // Drop the intrinsic, but forward the value
6636     setValue(&I, getValue(I.getOperand(0)));
6637     return;
6638 
6639   case Intrinsic::assume:
6640   case Intrinsic::experimental_noalias_scope_decl:
6641   case Intrinsic::var_annotation:
6642   case Intrinsic::sideeffect:
6643     // Discard annotate attributes, noalias scope declarations, assumptions, and
6644     // artificial side-effects.
6645     return;
6646 
6647   case Intrinsic::codeview_annotation: {
6648     // Emit a label associated with this metadata.
6649     MachineFunction &MF = DAG.getMachineFunction();
6650     MCSymbol *Label =
6651         MF.getMMI().getContext().createTempSymbol("annotation", true);
6652     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6653     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6654     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6655     DAG.setRoot(Res);
6656     return;
6657   }
6658 
6659   case Intrinsic::init_trampoline: {
6660     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6661 
6662     SDValue Ops[6];
6663     Ops[0] = getRoot();
6664     Ops[1] = getValue(I.getArgOperand(0));
6665     Ops[2] = getValue(I.getArgOperand(1));
6666     Ops[3] = getValue(I.getArgOperand(2));
6667     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6668     Ops[5] = DAG.getSrcValue(F);
6669 
6670     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6671 
6672     DAG.setRoot(Res);
6673     return;
6674   }
6675   case Intrinsic::adjust_trampoline:
6676     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6677                              TLI.getPointerTy(DAG.getDataLayout()),
6678                              getValue(I.getArgOperand(0))));
6679     return;
6680   case Intrinsic::gcroot: {
6681     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6682            "only valid in functions with gc specified, enforced by Verifier");
6683     assert(GFI && "implied by previous");
6684     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6685     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6686 
6687     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6688     GFI->addStackRoot(FI->getIndex(), TypeMap);
6689     return;
6690   }
6691   case Intrinsic::gcread:
6692   case Intrinsic::gcwrite:
6693     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6694   case Intrinsic::flt_rounds:
6695     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6696     setValue(&I, Res);
6697     DAG.setRoot(Res.getValue(1));
6698     return;
6699 
6700   case Intrinsic::expect:
6701     // Just replace __builtin_expect(exp, c) with EXP.
6702     setValue(&I, getValue(I.getArgOperand(0)));
6703     return;
6704 
6705   case Intrinsic::ubsantrap:
6706   case Intrinsic::debugtrap:
6707   case Intrinsic::trap: {
6708     StringRef TrapFuncName =
6709         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6710     if (TrapFuncName.empty()) {
6711       switch (Intrinsic) {
6712       case Intrinsic::trap:
6713         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6714         break;
6715       case Intrinsic::debugtrap:
6716         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6717         break;
6718       case Intrinsic::ubsantrap:
6719         DAG.setRoot(DAG.getNode(
6720             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6721             DAG.getTargetConstant(
6722                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6723                 MVT::i32)));
6724         break;
6725       default: llvm_unreachable("unknown trap intrinsic");
6726       }
6727       return;
6728     }
6729     TargetLowering::ArgListTy Args;
6730     if (Intrinsic == Intrinsic::ubsantrap) {
6731       Args.push_back(TargetLoweringBase::ArgListEntry());
6732       Args[0].Val = I.getArgOperand(0);
6733       Args[0].Node = getValue(Args[0].Val);
6734       Args[0].Ty = Args[0].Val->getType();
6735     }
6736 
6737     TargetLowering::CallLoweringInfo CLI(DAG);
6738     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6739         CallingConv::C, I.getType(),
6740         DAG.getExternalSymbol(TrapFuncName.data(),
6741                               TLI.getPointerTy(DAG.getDataLayout())),
6742         std::move(Args));
6743 
6744     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6745     DAG.setRoot(Result.second);
6746     return;
6747   }
6748 
6749   case Intrinsic::uadd_with_overflow:
6750   case Intrinsic::sadd_with_overflow:
6751   case Intrinsic::usub_with_overflow:
6752   case Intrinsic::ssub_with_overflow:
6753   case Intrinsic::umul_with_overflow:
6754   case Intrinsic::smul_with_overflow: {
6755     ISD::NodeType Op;
6756     switch (Intrinsic) {
6757     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6758     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6759     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6760     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6761     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6762     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6763     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6764     }
6765     SDValue Op1 = getValue(I.getArgOperand(0));
6766     SDValue Op2 = getValue(I.getArgOperand(1));
6767 
6768     EVT ResultVT = Op1.getValueType();
6769     EVT OverflowVT = MVT::i1;
6770     if (ResultVT.isVector())
6771       OverflowVT = EVT::getVectorVT(
6772           *Context, OverflowVT, ResultVT.getVectorElementCount());
6773 
6774     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6775     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6776     return;
6777   }
6778   case Intrinsic::prefetch: {
6779     SDValue Ops[5];
6780     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6781     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6782     Ops[0] = DAG.getRoot();
6783     Ops[1] = getValue(I.getArgOperand(0));
6784     Ops[2] = getValue(I.getArgOperand(1));
6785     Ops[3] = getValue(I.getArgOperand(2));
6786     Ops[4] = getValue(I.getArgOperand(3));
6787     SDValue Result = DAG.getMemIntrinsicNode(
6788         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6789         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6790         /* align */ None, Flags);
6791 
6792     // Chain the prefetch in parallell with any pending loads, to stay out of
6793     // the way of later optimizations.
6794     PendingLoads.push_back(Result);
6795     Result = getRoot();
6796     DAG.setRoot(Result);
6797     return;
6798   }
6799   case Intrinsic::lifetime_start:
6800   case Intrinsic::lifetime_end: {
6801     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6802     // Stack coloring is not enabled in O0, discard region information.
6803     if (TM.getOptLevel() == CodeGenOpt::None)
6804       return;
6805 
6806     const int64_t ObjectSize =
6807         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6808     Value *const ObjectPtr = I.getArgOperand(1);
6809     SmallVector<const Value *, 4> Allocas;
6810     getUnderlyingObjects(ObjectPtr, Allocas);
6811 
6812     for (const Value *Alloca : Allocas) {
6813       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6814 
6815       // Could not find an Alloca.
6816       if (!LifetimeObject)
6817         continue;
6818 
6819       // First check that the Alloca is static, otherwise it won't have a
6820       // valid frame index.
6821       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6822       if (SI == FuncInfo.StaticAllocaMap.end())
6823         return;
6824 
6825       const int FrameIndex = SI->second;
6826       int64_t Offset;
6827       if (GetPointerBaseWithConstantOffset(
6828               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6829         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6830       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6831                                 Offset);
6832       DAG.setRoot(Res);
6833     }
6834     return;
6835   }
6836   case Intrinsic::pseudoprobe: {
6837     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6838     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6839     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6840     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6841     DAG.setRoot(Res);
6842     return;
6843   }
6844   case Intrinsic::invariant_start:
6845     // Discard region information.
6846     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6847     return;
6848   case Intrinsic::invariant_end:
6849     // Discard region information.
6850     return;
6851   case Intrinsic::clear_cache:
6852     /// FunctionName may be null.
6853     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6854       lowerCallToExternalSymbol(I, FunctionName);
6855     return;
6856   case Intrinsic::donothing:
6857   case Intrinsic::seh_try_begin:
6858   case Intrinsic::seh_scope_begin:
6859   case Intrinsic::seh_try_end:
6860   case Intrinsic::seh_scope_end:
6861     // ignore
6862     return;
6863   case Intrinsic::experimental_stackmap:
6864     visitStackmap(I);
6865     return;
6866   case Intrinsic::experimental_patchpoint_void:
6867   case Intrinsic::experimental_patchpoint_i64:
6868     visitPatchpoint(I);
6869     return;
6870   case Intrinsic::experimental_gc_statepoint:
6871     LowerStatepoint(cast<GCStatepointInst>(I));
6872     return;
6873   case Intrinsic::experimental_gc_result:
6874     visitGCResult(cast<GCResultInst>(I));
6875     return;
6876   case Intrinsic::experimental_gc_relocate:
6877     visitGCRelocate(cast<GCRelocateInst>(I));
6878     return;
6879   case Intrinsic::instrprof_cover:
6880     llvm_unreachable("instrprof failed to lower a cover");
6881   case Intrinsic::instrprof_increment:
6882     llvm_unreachable("instrprof failed to lower an increment");
6883   case Intrinsic::instrprof_value_profile:
6884     llvm_unreachable("instrprof failed to lower a value profiling call");
6885   case Intrinsic::localescape: {
6886     MachineFunction &MF = DAG.getMachineFunction();
6887     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6888 
6889     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6890     // is the same on all targets.
6891     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6892       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6893       if (isa<ConstantPointerNull>(Arg))
6894         continue; // Skip null pointers. They represent a hole in index space.
6895       AllocaInst *Slot = cast<AllocaInst>(Arg);
6896       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6897              "can only escape static allocas");
6898       int FI = FuncInfo.StaticAllocaMap[Slot];
6899       MCSymbol *FrameAllocSym =
6900           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6901               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6902       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6903               TII->get(TargetOpcode::LOCAL_ESCAPE))
6904           .addSym(FrameAllocSym)
6905           .addFrameIndex(FI);
6906     }
6907 
6908     return;
6909   }
6910 
6911   case Intrinsic::localrecover: {
6912     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6913     MachineFunction &MF = DAG.getMachineFunction();
6914 
6915     // Get the symbol that defines the frame offset.
6916     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6917     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6918     unsigned IdxVal =
6919         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6920     MCSymbol *FrameAllocSym =
6921         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6922             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6923 
6924     Value *FP = I.getArgOperand(1);
6925     SDValue FPVal = getValue(FP);
6926     EVT PtrVT = FPVal.getValueType();
6927 
6928     // Create a MCSymbol for the label to avoid any target lowering
6929     // that would make this PC relative.
6930     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6931     SDValue OffsetVal =
6932         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6933 
6934     // Add the offset to the FP.
6935     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6936     setValue(&I, Add);
6937 
6938     return;
6939   }
6940 
6941   case Intrinsic::eh_exceptionpointer:
6942   case Intrinsic::eh_exceptioncode: {
6943     // Get the exception pointer vreg, copy from it, and resize it to fit.
6944     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6945     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6946     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6947     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6948     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
6949     if (Intrinsic == Intrinsic::eh_exceptioncode)
6950       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
6951     setValue(&I, N);
6952     return;
6953   }
6954   case Intrinsic::xray_customevent: {
6955     // Here we want to make sure that the intrinsic behaves as if it has a
6956     // specific calling convention, and only for x86_64.
6957     // FIXME: Support other platforms later.
6958     const auto &Triple = DAG.getTarget().getTargetTriple();
6959     if (Triple.getArch() != Triple::x86_64)
6960       return;
6961 
6962     SmallVector<SDValue, 8> Ops;
6963 
6964     // We want to say that we always want the arguments in registers.
6965     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6966     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6967     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6968     SDValue Chain = getRoot();
6969     Ops.push_back(LogEntryVal);
6970     Ops.push_back(StrSizeVal);
6971     Ops.push_back(Chain);
6972 
6973     // We need to enforce the calling convention for the callsite, so that
6974     // argument ordering is enforced correctly, and that register allocation can
6975     // see that some registers may be assumed clobbered and have to preserve
6976     // them across calls to the intrinsic.
6977     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6978                                            sdl, NodeTys, Ops);
6979     SDValue patchableNode = SDValue(MN, 0);
6980     DAG.setRoot(patchableNode);
6981     setValue(&I, patchableNode);
6982     return;
6983   }
6984   case Intrinsic::xray_typedevent: {
6985     // Here we want to make sure that the intrinsic behaves as if it has a
6986     // specific calling convention, and only for x86_64.
6987     // FIXME: Support other platforms later.
6988     const auto &Triple = DAG.getTarget().getTargetTriple();
6989     if (Triple.getArch() != Triple::x86_64)
6990       return;
6991 
6992     SmallVector<SDValue, 8> Ops;
6993 
6994     // We want to say that we always want the arguments in registers.
6995     // It's unclear to me how manipulating the selection DAG here forces callers
6996     // to provide arguments in registers instead of on the stack.
6997     SDValue LogTypeId = getValue(I.getArgOperand(0));
6998     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6999     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7000     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7001     SDValue Chain = getRoot();
7002     Ops.push_back(LogTypeId);
7003     Ops.push_back(LogEntryVal);
7004     Ops.push_back(StrSizeVal);
7005     Ops.push_back(Chain);
7006 
7007     // We need to enforce the calling convention for the callsite, so that
7008     // argument ordering is enforced correctly, and that register allocation can
7009     // see that some registers may be assumed clobbered and have to preserve
7010     // them across calls to the intrinsic.
7011     MachineSDNode *MN = DAG.getMachineNode(
7012         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7013     SDValue patchableNode = SDValue(MN, 0);
7014     DAG.setRoot(patchableNode);
7015     setValue(&I, patchableNode);
7016     return;
7017   }
7018   case Intrinsic::experimental_deoptimize:
7019     LowerDeoptimizeCall(&I);
7020     return;
7021   case Intrinsic::experimental_stepvector:
7022     visitStepVector(I);
7023     return;
7024   case Intrinsic::vector_reduce_fadd:
7025   case Intrinsic::vector_reduce_fmul:
7026   case Intrinsic::vector_reduce_add:
7027   case Intrinsic::vector_reduce_mul:
7028   case Intrinsic::vector_reduce_and:
7029   case Intrinsic::vector_reduce_or:
7030   case Intrinsic::vector_reduce_xor:
7031   case Intrinsic::vector_reduce_smax:
7032   case Intrinsic::vector_reduce_smin:
7033   case Intrinsic::vector_reduce_umax:
7034   case Intrinsic::vector_reduce_umin:
7035   case Intrinsic::vector_reduce_fmax:
7036   case Intrinsic::vector_reduce_fmin:
7037     visitVectorReduce(I, Intrinsic);
7038     return;
7039 
7040   case Intrinsic::icall_branch_funnel: {
7041     SmallVector<SDValue, 16> Ops;
7042     Ops.push_back(getValue(I.getArgOperand(0)));
7043 
7044     int64_t Offset;
7045     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7046         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7047     if (!Base)
7048       report_fatal_error(
7049           "llvm.icall.branch.funnel operand must be a GlobalValue");
7050     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7051 
7052     struct BranchFunnelTarget {
7053       int64_t Offset;
7054       SDValue Target;
7055     };
7056     SmallVector<BranchFunnelTarget, 8> Targets;
7057 
7058     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7059       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7060           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7061       if (ElemBase != Base)
7062         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7063                            "to the same GlobalValue");
7064 
7065       SDValue Val = getValue(I.getArgOperand(Op + 1));
7066       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7067       if (!GA)
7068         report_fatal_error(
7069             "llvm.icall.branch.funnel operand must be a GlobalValue");
7070       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7071                                      GA->getGlobal(), sdl, Val.getValueType(),
7072                                      GA->getOffset())});
7073     }
7074     llvm::sort(Targets,
7075                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7076                  return T1.Offset < T2.Offset;
7077                });
7078 
7079     for (auto &T : Targets) {
7080       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7081       Ops.push_back(T.Target);
7082     }
7083 
7084     Ops.push_back(DAG.getRoot()); // Chain
7085     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7086                                  MVT::Other, Ops),
7087               0);
7088     DAG.setRoot(N);
7089     setValue(&I, N);
7090     HasTailCall = true;
7091     return;
7092   }
7093 
7094   case Intrinsic::wasm_landingpad_index:
7095     // Information this intrinsic contained has been transferred to
7096     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7097     // delete it now.
7098     return;
7099 
7100   case Intrinsic::aarch64_settag:
7101   case Intrinsic::aarch64_settag_zero: {
7102     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7103     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7104     SDValue Val = TSI.EmitTargetCodeForSetTag(
7105         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7106         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7107         ZeroMemory);
7108     DAG.setRoot(Val);
7109     setValue(&I, Val);
7110     return;
7111   }
7112   case Intrinsic::ptrmask: {
7113     SDValue Ptr = getValue(I.getOperand(0));
7114     SDValue Const = getValue(I.getOperand(1));
7115 
7116     EVT PtrVT = Ptr.getValueType();
7117     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7118                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7119     return;
7120   }
7121   case Intrinsic::get_active_lane_mask: {
7122     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7123     SDValue Index = getValue(I.getOperand(0));
7124     EVT ElementVT = Index.getValueType();
7125 
7126     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7127       visitTargetIntrinsic(I, Intrinsic);
7128       return;
7129     }
7130 
7131     SDValue TripCount = getValue(I.getOperand(1));
7132     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7133 
7134     SDValue VectorIndex, VectorTripCount;
7135     if (VecTy.isScalableVector()) {
7136       VectorIndex = DAG.getSplatVector(VecTy, sdl, Index);
7137       VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount);
7138     } else {
7139       VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index);
7140       VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount);
7141     }
7142     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7143     SDValue VectorInduction = DAG.getNode(
7144         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7145     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7146                                  VectorTripCount, ISD::CondCode::SETULT);
7147     setValue(&I, SetCC);
7148     return;
7149   }
7150   case Intrinsic::experimental_vector_insert: {
7151     SDValue Vec = getValue(I.getOperand(0));
7152     SDValue SubVec = getValue(I.getOperand(1));
7153     SDValue Index = getValue(I.getOperand(2));
7154 
7155     // The intrinsic's index type is i64, but the SDNode requires an index type
7156     // suitable for the target. Convert the index as required.
7157     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7158     if (Index.getValueType() != VectorIdxTy)
7159       Index = DAG.getVectorIdxConstant(
7160           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7161 
7162     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7163     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7164                              Index));
7165     return;
7166   }
7167   case Intrinsic::experimental_vector_extract: {
7168     SDValue Vec = getValue(I.getOperand(0));
7169     SDValue Index = getValue(I.getOperand(1));
7170     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7171 
7172     // The intrinsic's index type is i64, but the SDNode requires an index type
7173     // suitable for the target. Convert the index as required.
7174     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7175     if (Index.getValueType() != VectorIdxTy)
7176       Index = DAG.getVectorIdxConstant(
7177           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7178 
7179     setValue(&I,
7180              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7181     return;
7182   }
7183   case Intrinsic::experimental_vector_reverse:
7184     visitVectorReverse(I);
7185     return;
7186   case Intrinsic::experimental_vector_splice:
7187     visitVectorSplice(I);
7188     return;
7189   }
7190 }
7191 
7192 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7193     const ConstrainedFPIntrinsic &FPI) {
7194   SDLoc sdl = getCurSDLoc();
7195 
7196   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7197   SmallVector<EVT, 4> ValueVTs;
7198   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7199   ValueVTs.push_back(MVT::Other); // Out chain
7200 
7201   // We do not need to serialize constrained FP intrinsics against
7202   // each other or against (nonvolatile) loads, so they can be
7203   // chained like loads.
7204   SDValue Chain = DAG.getRoot();
7205   SmallVector<SDValue, 4> Opers;
7206   Opers.push_back(Chain);
7207   if (FPI.isUnaryOp()) {
7208     Opers.push_back(getValue(FPI.getArgOperand(0)));
7209   } else if (FPI.isTernaryOp()) {
7210     Opers.push_back(getValue(FPI.getArgOperand(0)));
7211     Opers.push_back(getValue(FPI.getArgOperand(1)));
7212     Opers.push_back(getValue(FPI.getArgOperand(2)));
7213   } else {
7214     Opers.push_back(getValue(FPI.getArgOperand(0)));
7215     Opers.push_back(getValue(FPI.getArgOperand(1)));
7216   }
7217 
7218   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7219     assert(Result.getNode()->getNumValues() == 2);
7220 
7221     // Push node to the appropriate list so that future instructions can be
7222     // chained up correctly.
7223     SDValue OutChain = Result.getValue(1);
7224     switch (EB) {
7225     case fp::ExceptionBehavior::ebIgnore:
7226       // The only reason why ebIgnore nodes still need to be chained is that
7227       // they might depend on the current rounding mode, and therefore must
7228       // not be moved across instruction that may change that mode.
7229       LLVM_FALLTHROUGH;
7230     case fp::ExceptionBehavior::ebMayTrap:
7231       // These must not be moved across calls or instructions that may change
7232       // floating-point exception masks.
7233       PendingConstrainedFP.push_back(OutChain);
7234       break;
7235     case fp::ExceptionBehavior::ebStrict:
7236       // These must not be moved across calls or instructions that may change
7237       // floating-point exception masks or read floating-point exception flags.
7238       // In addition, they cannot be optimized out even if unused.
7239       PendingConstrainedFPStrict.push_back(OutChain);
7240       break;
7241     }
7242   };
7243 
7244   SDVTList VTs = DAG.getVTList(ValueVTs);
7245   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7246 
7247   SDNodeFlags Flags;
7248   if (EB == fp::ExceptionBehavior::ebIgnore)
7249     Flags.setNoFPExcept(true);
7250 
7251   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7252     Flags.copyFMF(*FPOp);
7253 
7254   unsigned Opcode;
7255   switch (FPI.getIntrinsicID()) {
7256   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7257 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7258   case Intrinsic::INTRINSIC:                                                   \
7259     Opcode = ISD::STRICT_##DAGN;                                               \
7260     break;
7261 #include "llvm/IR/ConstrainedOps.def"
7262   case Intrinsic::experimental_constrained_fmuladd: {
7263     Opcode = ISD::STRICT_FMA;
7264     // Break fmuladd into fmul and fadd.
7265     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7266         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7267                                         ValueVTs[0])) {
7268       Opers.pop_back();
7269       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7270       pushOutChain(Mul, EB);
7271       Opcode = ISD::STRICT_FADD;
7272       Opers.clear();
7273       Opers.push_back(Mul.getValue(1));
7274       Opers.push_back(Mul.getValue(0));
7275       Opers.push_back(getValue(FPI.getArgOperand(2)));
7276     }
7277     break;
7278   }
7279   }
7280 
7281   // A few strict DAG nodes carry additional operands that are not
7282   // set up by the default code above.
7283   switch (Opcode) {
7284   default: break;
7285   case ISD::STRICT_FP_ROUND:
7286     Opers.push_back(
7287         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7288     break;
7289   case ISD::STRICT_FSETCC:
7290   case ISD::STRICT_FSETCCS: {
7291     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7292     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7293     if (TM.Options.NoNaNsFPMath)
7294       Condition = getFCmpCodeWithoutNaN(Condition);
7295     Opers.push_back(DAG.getCondCode(Condition));
7296     break;
7297   }
7298   }
7299 
7300   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7301   pushOutChain(Result, EB);
7302 
7303   SDValue FPResult = Result.getValue(0);
7304   setValue(&FPI, FPResult);
7305 }
7306 
7307 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7308   Optional<unsigned> ResOPC;
7309   switch (VPIntrin.getIntrinsicID()) {
7310 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7311 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) ResOPC = ISD::VPSD;
7312 #define END_REGISTER_VP_INTRINSIC(VPID) break;
7313 #include "llvm/IR/VPIntrinsics.def"
7314   }
7315 
7316   if (!ResOPC.hasValue())
7317     llvm_unreachable(
7318         "Inconsistency: no SDNode available for this VPIntrinsic!");
7319 
7320   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7321       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7322     if (VPIntrin.getFastMathFlags().allowReassoc())
7323       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7324                                                 : ISD::VP_REDUCE_FMUL;
7325   }
7326 
7327   return ResOPC.getValue();
7328 }
7329 
7330 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT,
7331                                             SmallVector<SDValue, 7> &OpValues,
7332                                             bool IsGather) {
7333   SDLoc DL = getCurSDLoc();
7334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7335   Value *PtrOperand = VPIntrin.getArgOperand(0);
7336   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7337   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7338   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7339   SDValue LD;
7340   bool AddToChain = true;
7341   if (!IsGather) {
7342     // Do not serialize variable-length loads of constant memory with
7343     // anything.
7344     if (!Alignment)
7345       Alignment = DAG.getEVTAlign(VT);
7346     MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7347     AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7348     SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7349     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7350         MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7351         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7352     LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7353                        MMO, false /*IsExpanding */);
7354   } else {
7355     if (!Alignment)
7356       Alignment = DAG.getEVTAlign(VT.getScalarType());
7357     unsigned AS =
7358         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7359     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7360         MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7361         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7362     SDValue Base, Index, Scale;
7363     ISD::MemIndexType IndexType;
7364     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7365                                       this, VPIntrin.getParent());
7366     if (!UniformBase) {
7367       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7368       Index = getValue(PtrOperand);
7369       IndexType = ISD::SIGNED_UNSCALED;
7370       Scale =
7371           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7372     }
7373     EVT IdxVT = Index.getValueType();
7374     EVT EltTy = IdxVT.getVectorElementType();
7375     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7376       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7377       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7378     }
7379     LD = DAG.getGatherVP(
7380         DAG.getVTList(VT, MVT::Other), VT, DL,
7381         {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7382         IndexType);
7383   }
7384   if (AddToChain)
7385     PendingLoads.push_back(LD.getValue(1));
7386   setValue(&VPIntrin, LD);
7387 }
7388 
7389 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin,
7390                                               SmallVector<SDValue, 7> &OpValues,
7391                                               bool IsScatter) {
7392   SDLoc DL = getCurSDLoc();
7393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7394   Value *PtrOperand = VPIntrin.getArgOperand(1);
7395   EVT VT = OpValues[0].getValueType();
7396   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7397   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7398   SDValue ST;
7399   if (!IsScatter) {
7400     if (!Alignment)
7401       Alignment = DAG.getEVTAlign(VT);
7402     SDValue Ptr = OpValues[1];
7403     SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7404     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7405         MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7406         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7407     ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7408                         OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7409                         /* IsTruncating */ false, /*IsCompressing*/ false);
7410   } else {
7411     if (!Alignment)
7412       Alignment = DAG.getEVTAlign(VT.getScalarType());
7413     unsigned AS =
7414         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7415     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7416         MachinePointerInfo(AS), MachineMemOperand::MOStore,
7417         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7418     SDValue Base, Index, Scale;
7419     ISD::MemIndexType IndexType;
7420     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7421                                       this, VPIntrin.getParent());
7422     if (!UniformBase) {
7423       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7424       Index = getValue(PtrOperand);
7425       IndexType = ISD::SIGNED_UNSCALED;
7426       Scale =
7427           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7428     }
7429     EVT IdxVT = Index.getValueType();
7430     EVT EltTy = IdxVT.getVectorElementType();
7431     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7432       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7433       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7434     }
7435     ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7436                           {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7437                            OpValues[2], OpValues[3]},
7438                           MMO, IndexType);
7439   }
7440   DAG.setRoot(ST);
7441   setValue(&VPIntrin, ST);
7442 }
7443 
7444 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7445     const VPIntrinsic &VPIntrin) {
7446   SDLoc DL = getCurSDLoc();
7447   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7448 
7449   SmallVector<EVT, 4> ValueVTs;
7450   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7451   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7452   SDVTList VTs = DAG.getVTList(ValueVTs);
7453 
7454   auto EVLParamPos =
7455       VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID());
7456 
7457   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7458   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7459          "Unexpected target EVL type");
7460 
7461   // Request operands.
7462   SmallVector<SDValue, 7> OpValues;
7463   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7464     auto Op = getValue(VPIntrin.getArgOperand(I));
7465     if (I == EVLParamPos)
7466       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7467     OpValues.push_back(Op);
7468   }
7469 
7470   switch (Opcode) {
7471   default: {
7472     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7473     setValue(&VPIntrin, Result);
7474     break;
7475   }
7476   case ISD::VP_LOAD:
7477   case ISD::VP_GATHER:
7478     visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues,
7479                       Opcode == ISD::VP_GATHER);
7480     break;
7481   case ISD::VP_STORE:
7482   case ISD::VP_SCATTER:
7483     visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER);
7484     break;
7485   }
7486 }
7487 
7488 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7489                                           const BasicBlock *EHPadBB,
7490                                           MCSymbol *&BeginLabel) {
7491   MachineFunction &MF = DAG.getMachineFunction();
7492   MachineModuleInfo &MMI = MF.getMMI();
7493 
7494   // Insert a label before the invoke call to mark the try range.  This can be
7495   // used to detect deletion of the invoke via the MachineModuleInfo.
7496   BeginLabel = MMI.getContext().createTempSymbol();
7497 
7498   // For SjLj, keep track of which landing pads go with which invokes
7499   // so as to maintain the ordering of pads in the LSDA.
7500   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7501   if (CallSiteIndex) {
7502     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7503     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7504 
7505     // Now that the call site is handled, stop tracking it.
7506     MMI.setCurrentCallSite(0);
7507   }
7508 
7509   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7510 }
7511 
7512 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7513                                         const BasicBlock *EHPadBB,
7514                                         MCSymbol *BeginLabel) {
7515   assert(BeginLabel && "BeginLabel should've been set");
7516 
7517   MachineFunction &MF = DAG.getMachineFunction();
7518   MachineModuleInfo &MMI = MF.getMMI();
7519 
7520   // Insert a label at the end of the invoke call to mark the try range.  This
7521   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7522   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7523   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7524 
7525   // Inform MachineModuleInfo of range.
7526   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7527   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7528   // actually use outlined funclets and their LSDA info style.
7529   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7530     assert(II && "II should've been set");
7531     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7532     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7533   } else if (!isScopedEHPersonality(Pers)) {
7534     assert(EHPadBB);
7535     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7536   }
7537 
7538   return Chain;
7539 }
7540 
7541 std::pair<SDValue, SDValue>
7542 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7543                                     const BasicBlock *EHPadBB) {
7544   MCSymbol *BeginLabel = nullptr;
7545 
7546   if (EHPadBB) {
7547     // Both PendingLoads and PendingExports must be flushed here;
7548     // this call might not return.
7549     (void)getRoot();
7550     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7551     CLI.setChain(getRoot());
7552   }
7553 
7554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7555   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7556 
7557   assert((CLI.IsTailCall || Result.second.getNode()) &&
7558          "Non-null chain expected with non-tail call!");
7559   assert((Result.second.getNode() || !Result.first.getNode()) &&
7560          "Null value expected with tail call!");
7561 
7562   if (!Result.second.getNode()) {
7563     // As a special case, a null chain means that a tail call has been emitted
7564     // and the DAG root is already updated.
7565     HasTailCall = true;
7566 
7567     // Since there's no actual continuation from this block, nothing can be
7568     // relying on us setting vregs for them.
7569     PendingExports.clear();
7570   } else {
7571     DAG.setRoot(Result.second);
7572   }
7573 
7574   if (EHPadBB) {
7575     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7576                            BeginLabel));
7577   }
7578 
7579   return Result;
7580 }
7581 
7582 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7583                                       bool isTailCall,
7584                                       bool isMustTailCall,
7585                                       const BasicBlock *EHPadBB) {
7586   auto &DL = DAG.getDataLayout();
7587   FunctionType *FTy = CB.getFunctionType();
7588   Type *RetTy = CB.getType();
7589 
7590   TargetLowering::ArgListTy Args;
7591   Args.reserve(CB.arg_size());
7592 
7593   const Value *SwiftErrorVal = nullptr;
7594   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7595 
7596   if (isTailCall) {
7597     // Avoid emitting tail calls in functions with the disable-tail-calls
7598     // attribute.
7599     auto *Caller = CB.getParent()->getParent();
7600     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7601         "true" && !isMustTailCall)
7602       isTailCall = false;
7603 
7604     // We can't tail call inside a function with a swifterror argument. Lowering
7605     // does not support this yet. It would have to move into the swifterror
7606     // register before the call.
7607     if (TLI.supportSwiftError() &&
7608         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7609       isTailCall = false;
7610   }
7611 
7612   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7613     TargetLowering::ArgListEntry Entry;
7614     const Value *V = *I;
7615 
7616     // Skip empty types
7617     if (V->getType()->isEmptyTy())
7618       continue;
7619 
7620     SDValue ArgNode = getValue(V);
7621     Entry.Node = ArgNode; Entry.Ty = V->getType();
7622 
7623     Entry.setAttributes(&CB, I - CB.arg_begin());
7624 
7625     // Use swifterror virtual register as input to the call.
7626     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7627       SwiftErrorVal = V;
7628       // We find the virtual register for the actual swifterror argument.
7629       // Instead of using the Value, we use the virtual register instead.
7630       Entry.Node =
7631           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7632                           EVT(TLI.getPointerTy(DL)));
7633     }
7634 
7635     Args.push_back(Entry);
7636 
7637     // If we have an explicit sret argument that is an Instruction, (i.e., it
7638     // might point to function-local memory), we can't meaningfully tail-call.
7639     if (Entry.IsSRet && isa<Instruction>(V))
7640       isTailCall = false;
7641   }
7642 
7643   // If call site has a cfguardtarget operand bundle, create and add an
7644   // additional ArgListEntry.
7645   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7646     TargetLowering::ArgListEntry Entry;
7647     Value *V = Bundle->Inputs[0];
7648     SDValue ArgNode = getValue(V);
7649     Entry.Node = ArgNode;
7650     Entry.Ty = V->getType();
7651     Entry.IsCFGuardTarget = true;
7652     Args.push_back(Entry);
7653   }
7654 
7655   // Check if target-independent constraints permit a tail call here.
7656   // Target-dependent constraints are checked within TLI->LowerCallTo.
7657   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7658     isTailCall = false;
7659 
7660   // Disable tail calls if there is an swifterror argument. Targets have not
7661   // been updated to support tail calls.
7662   if (TLI.supportSwiftError() && SwiftErrorVal)
7663     isTailCall = false;
7664 
7665   TargetLowering::CallLoweringInfo CLI(DAG);
7666   CLI.setDebugLoc(getCurSDLoc())
7667       .setChain(getRoot())
7668       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7669       .setTailCall(isTailCall)
7670       .setConvergent(CB.isConvergent())
7671       .setIsPreallocated(
7672           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7673   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7674 
7675   if (Result.first.getNode()) {
7676     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7677     setValue(&CB, Result.first);
7678   }
7679 
7680   // The last element of CLI.InVals has the SDValue for swifterror return.
7681   // Here we copy it to a virtual register and update SwiftErrorMap for
7682   // book-keeping.
7683   if (SwiftErrorVal && TLI.supportSwiftError()) {
7684     // Get the last element of InVals.
7685     SDValue Src = CLI.InVals.back();
7686     Register VReg =
7687         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7688     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7689     DAG.setRoot(CopyNode);
7690   }
7691 }
7692 
7693 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7694                              SelectionDAGBuilder &Builder) {
7695   // Check to see if this load can be trivially constant folded, e.g. if the
7696   // input is from a string literal.
7697   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7698     // Cast pointer to the type we really want to load.
7699     Type *LoadTy =
7700         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7701     if (LoadVT.isVector())
7702       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7703 
7704     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7705                                          PointerType::getUnqual(LoadTy));
7706 
7707     if (const Constant *LoadCst =
7708             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7709                                          LoadTy, Builder.DAG.getDataLayout()))
7710       return Builder.getValue(LoadCst);
7711   }
7712 
7713   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7714   // still constant memory, the input chain can be the entry node.
7715   SDValue Root;
7716   bool ConstantMemory = false;
7717 
7718   // Do not serialize (non-volatile) loads of constant memory with anything.
7719   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7720     Root = Builder.DAG.getEntryNode();
7721     ConstantMemory = true;
7722   } else {
7723     // Do not serialize non-volatile loads against each other.
7724     Root = Builder.DAG.getRoot();
7725   }
7726 
7727   SDValue Ptr = Builder.getValue(PtrVal);
7728   SDValue LoadVal =
7729       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7730                           MachinePointerInfo(PtrVal), Align(1));
7731 
7732   if (!ConstantMemory)
7733     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7734   return LoadVal;
7735 }
7736 
7737 /// Record the value for an instruction that produces an integer result,
7738 /// converting the type where necessary.
7739 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7740                                                   SDValue Value,
7741                                                   bool IsSigned) {
7742   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7743                                                     I.getType(), true);
7744   if (IsSigned)
7745     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7746   else
7747     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7748   setValue(&I, Value);
7749 }
7750 
7751 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7752 /// true and lower it. Otherwise return false, and it will be lowered like a
7753 /// normal call.
7754 /// The caller already checked that \p I calls the appropriate LibFunc with a
7755 /// correct prototype.
7756 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7757   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7758   const Value *Size = I.getArgOperand(2);
7759   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7760   if (CSize && CSize->getZExtValue() == 0) {
7761     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7762                                                           I.getType(), true);
7763     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7764     return true;
7765   }
7766 
7767   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7768   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7769       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7770       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7771   if (Res.first.getNode()) {
7772     processIntegerCallValue(I, Res.first, true);
7773     PendingLoads.push_back(Res.second);
7774     return true;
7775   }
7776 
7777   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7778   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7779   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7780     return false;
7781 
7782   // If the target has a fast compare for the given size, it will return a
7783   // preferred load type for that size. Require that the load VT is legal and
7784   // that the target supports unaligned loads of that type. Otherwise, return
7785   // INVALID.
7786   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7787     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7788     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7789     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7790       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7791       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7792       // TODO: Check alignment of src and dest ptrs.
7793       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7794       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7795       if (!TLI.isTypeLegal(LVT) ||
7796           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7797           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7798         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7799     }
7800 
7801     return LVT;
7802   };
7803 
7804   // This turns into unaligned loads. We only do this if the target natively
7805   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7806   // we'll only produce a small number of byte loads.
7807   MVT LoadVT;
7808   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7809   switch (NumBitsToCompare) {
7810   default:
7811     return false;
7812   case 16:
7813     LoadVT = MVT::i16;
7814     break;
7815   case 32:
7816     LoadVT = MVT::i32;
7817     break;
7818   case 64:
7819   case 128:
7820   case 256:
7821     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7822     break;
7823   }
7824 
7825   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7826     return false;
7827 
7828   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7829   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7830 
7831   // Bitcast to a wide integer type if the loads are vectors.
7832   if (LoadVT.isVector()) {
7833     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7834     LoadL = DAG.getBitcast(CmpVT, LoadL);
7835     LoadR = DAG.getBitcast(CmpVT, LoadR);
7836   }
7837 
7838   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7839   processIntegerCallValue(I, Cmp, false);
7840   return true;
7841 }
7842 
7843 /// See if we can lower a memchr call into an optimized form. If so, return
7844 /// true and lower it. Otherwise return false, and it will be lowered like a
7845 /// normal call.
7846 /// The caller already checked that \p I calls the appropriate LibFunc with a
7847 /// correct prototype.
7848 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7849   const Value *Src = I.getArgOperand(0);
7850   const Value *Char = I.getArgOperand(1);
7851   const Value *Length = I.getArgOperand(2);
7852 
7853   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7854   std::pair<SDValue, SDValue> Res =
7855     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7856                                 getValue(Src), getValue(Char), getValue(Length),
7857                                 MachinePointerInfo(Src));
7858   if (Res.first.getNode()) {
7859     setValue(&I, Res.first);
7860     PendingLoads.push_back(Res.second);
7861     return true;
7862   }
7863 
7864   return false;
7865 }
7866 
7867 /// See if we can lower a mempcpy call into an optimized form. If so, return
7868 /// true and lower it. Otherwise return false, and it will be lowered like a
7869 /// normal call.
7870 /// The caller already checked that \p I calls the appropriate LibFunc with a
7871 /// correct prototype.
7872 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7873   SDValue Dst = getValue(I.getArgOperand(0));
7874   SDValue Src = getValue(I.getArgOperand(1));
7875   SDValue Size = getValue(I.getArgOperand(2));
7876 
7877   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7878   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7879   // DAG::getMemcpy needs Alignment to be defined.
7880   Align Alignment = std::min(DstAlign, SrcAlign);
7881 
7882   bool isVol = false;
7883   SDLoc sdl = getCurSDLoc();
7884 
7885   // In the mempcpy context we need to pass in a false value for isTailCall
7886   // because the return pointer needs to be adjusted by the size of
7887   // the copied memory.
7888   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7889   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7890                              /*isTailCall=*/false,
7891                              MachinePointerInfo(I.getArgOperand(0)),
7892                              MachinePointerInfo(I.getArgOperand(1)),
7893                              I.getAAMetadata());
7894   assert(MC.getNode() != nullptr &&
7895          "** memcpy should not be lowered as TailCall in mempcpy context **");
7896   DAG.setRoot(MC);
7897 
7898   // Check if Size needs to be truncated or extended.
7899   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7900 
7901   // Adjust return pointer to point just past the last dst byte.
7902   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7903                                     Dst, Size);
7904   setValue(&I, DstPlusSize);
7905   return true;
7906 }
7907 
7908 /// See if we can lower a strcpy call into an optimized form.  If so, return
7909 /// true and lower it, otherwise return false and it will be lowered like a
7910 /// normal call.
7911 /// The caller already checked that \p I calls the appropriate LibFunc with a
7912 /// correct prototype.
7913 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7914   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7915 
7916   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7917   std::pair<SDValue, SDValue> Res =
7918     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7919                                 getValue(Arg0), getValue(Arg1),
7920                                 MachinePointerInfo(Arg0),
7921                                 MachinePointerInfo(Arg1), isStpcpy);
7922   if (Res.first.getNode()) {
7923     setValue(&I, Res.first);
7924     DAG.setRoot(Res.second);
7925     return true;
7926   }
7927 
7928   return false;
7929 }
7930 
7931 /// See if we can lower a strcmp call into an optimized form.  If so, return
7932 /// true and lower it, otherwise return false and it will be lowered like a
7933 /// normal call.
7934 /// The caller already checked that \p I calls the appropriate LibFunc with a
7935 /// correct prototype.
7936 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7937   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7938 
7939   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7940   std::pair<SDValue, SDValue> Res =
7941     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7942                                 getValue(Arg0), getValue(Arg1),
7943                                 MachinePointerInfo(Arg0),
7944                                 MachinePointerInfo(Arg1));
7945   if (Res.first.getNode()) {
7946     processIntegerCallValue(I, Res.first, true);
7947     PendingLoads.push_back(Res.second);
7948     return true;
7949   }
7950 
7951   return false;
7952 }
7953 
7954 /// See if we can lower a strlen call into an optimized form.  If so, return
7955 /// true and lower it, otherwise return false and it will be lowered like a
7956 /// normal call.
7957 /// The caller already checked that \p I calls the appropriate LibFunc with a
7958 /// correct prototype.
7959 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7960   const Value *Arg0 = I.getArgOperand(0);
7961 
7962   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7963   std::pair<SDValue, SDValue> Res =
7964     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7965                                 getValue(Arg0), MachinePointerInfo(Arg0));
7966   if (Res.first.getNode()) {
7967     processIntegerCallValue(I, Res.first, false);
7968     PendingLoads.push_back(Res.second);
7969     return true;
7970   }
7971 
7972   return false;
7973 }
7974 
7975 /// See if we can lower a strnlen call into an optimized form.  If so, return
7976 /// true and lower it, otherwise return false and it will be lowered like a
7977 /// normal call.
7978 /// The caller already checked that \p I calls the appropriate LibFunc with a
7979 /// correct prototype.
7980 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7981   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7982 
7983   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7984   std::pair<SDValue, SDValue> Res =
7985     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7986                                  getValue(Arg0), getValue(Arg1),
7987                                  MachinePointerInfo(Arg0));
7988   if (Res.first.getNode()) {
7989     processIntegerCallValue(I, Res.first, false);
7990     PendingLoads.push_back(Res.second);
7991     return true;
7992   }
7993 
7994   return false;
7995 }
7996 
7997 /// See if we can lower a unary floating-point operation into an SDNode with
7998 /// the specified Opcode.  If so, return true and lower it, otherwise return
7999 /// false and it will be lowered like a normal call.
8000 /// The caller already checked that \p I calls the appropriate LibFunc with a
8001 /// correct prototype.
8002 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8003                                               unsigned Opcode) {
8004   // We already checked this call's prototype; verify it doesn't modify errno.
8005   if (!I.onlyReadsMemory())
8006     return false;
8007 
8008   SDNodeFlags Flags;
8009   Flags.copyFMF(cast<FPMathOperator>(I));
8010 
8011   SDValue Tmp = getValue(I.getArgOperand(0));
8012   setValue(&I,
8013            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8014   return true;
8015 }
8016 
8017 /// See if we can lower a binary floating-point operation into an SDNode with
8018 /// the specified Opcode. If so, return true and lower it. Otherwise return
8019 /// false, and it will be lowered like a normal call.
8020 /// The caller already checked that \p I calls the appropriate LibFunc with a
8021 /// correct prototype.
8022 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8023                                                unsigned Opcode) {
8024   // We already checked this call's prototype; verify it doesn't modify errno.
8025   if (!I.onlyReadsMemory())
8026     return false;
8027 
8028   SDNodeFlags Flags;
8029   Flags.copyFMF(cast<FPMathOperator>(I));
8030 
8031   SDValue Tmp0 = getValue(I.getArgOperand(0));
8032   SDValue Tmp1 = getValue(I.getArgOperand(1));
8033   EVT VT = Tmp0.getValueType();
8034   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8035   return true;
8036 }
8037 
8038 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8039   // Handle inline assembly differently.
8040   if (I.isInlineAsm()) {
8041     visitInlineAsm(I);
8042     return;
8043   }
8044 
8045   if (Function *F = I.getCalledFunction()) {
8046     diagnoseDontCall(I);
8047 
8048     if (F->isDeclaration()) {
8049       // Is this an LLVM intrinsic or a target-specific intrinsic?
8050       unsigned IID = F->getIntrinsicID();
8051       if (!IID)
8052         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8053           IID = II->getIntrinsicID(F);
8054 
8055       if (IID) {
8056         visitIntrinsicCall(I, IID);
8057         return;
8058       }
8059     }
8060 
8061     // Check for well-known libc/libm calls.  If the function is internal, it
8062     // can't be a library call.  Don't do the check if marked as nobuiltin for
8063     // some reason or the call site requires strict floating point semantics.
8064     LibFunc Func;
8065     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8066         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8067         LibInfo->hasOptimizedCodeGen(Func)) {
8068       switch (Func) {
8069       default: break;
8070       case LibFunc_bcmp:
8071         if (visitMemCmpBCmpCall(I))
8072           return;
8073         break;
8074       case LibFunc_copysign:
8075       case LibFunc_copysignf:
8076       case LibFunc_copysignl:
8077         // We already checked this call's prototype; verify it doesn't modify
8078         // errno.
8079         if (I.onlyReadsMemory()) {
8080           SDValue LHS = getValue(I.getArgOperand(0));
8081           SDValue RHS = getValue(I.getArgOperand(1));
8082           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8083                                    LHS.getValueType(), LHS, RHS));
8084           return;
8085         }
8086         break;
8087       case LibFunc_fabs:
8088       case LibFunc_fabsf:
8089       case LibFunc_fabsl:
8090         if (visitUnaryFloatCall(I, ISD::FABS))
8091           return;
8092         break;
8093       case LibFunc_fmin:
8094       case LibFunc_fminf:
8095       case LibFunc_fminl:
8096         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8097           return;
8098         break;
8099       case LibFunc_fmax:
8100       case LibFunc_fmaxf:
8101       case LibFunc_fmaxl:
8102         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8103           return;
8104         break;
8105       case LibFunc_sin:
8106       case LibFunc_sinf:
8107       case LibFunc_sinl:
8108         if (visitUnaryFloatCall(I, ISD::FSIN))
8109           return;
8110         break;
8111       case LibFunc_cos:
8112       case LibFunc_cosf:
8113       case LibFunc_cosl:
8114         if (visitUnaryFloatCall(I, ISD::FCOS))
8115           return;
8116         break;
8117       case LibFunc_sqrt:
8118       case LibFunc_sqrtf:
8119       case LibFunc_sqrtl:
8120       case LibFunc_sqrt_finite:
8121       case LibFunc_sqrtf_finite:
8122       case LibFunc_sqrtl_finite:
8123         if (visitUnaryFloatCall(I, ISD::FSQRT))
8124           return;
8125         break;
8126       case LibFunc_floor:
8127       case LibFunc_floorf:
8128       case LibFunc_floorl:
8129         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8130           return;
8131         break;
8132       case LibFunc_nearbyint:
8133       case LibFunc_nearbyintf:
8134       case LibFunc_nearbyintl:
8135         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8136           return;
8137         break;
8138       case LibFunc_ceil:
8139       case LibFunc_ceilf:
8140       case LibFunc_ceill:
8141         if (visitUnaryFloatCall(I, ISD::FCEIL))
8142           return;
8143         break;
8144       case LibFunc_rint:
8145       case LibFunc_rintf:
8146       case LibFunc_rintl:
8147         if (visitUnaryFloatCall(I, ISD::FRINT))
8148           return;
8149         break;
8150       case LibFunc_round:
8151       case LibFunc_roundf:
8152       case LibFunc_roundl:
8153         if (visitUnaryFloatCall(I, ISD::FROUND))
8154           return;
8155         break;
8156       case LibFunc_trunc:
8157       case LibFunc_truncf:
8158       case LibFunc_truncl:
8159         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8160           return;
8161         break;
8162       case LibFunc_log2:
8163       case LibFunc_log2f:
8164       case LibFunc_log2l:
8165         if (visitUnaryFloatCall(I, ISD::FLOG2))
8166           return;
8167         break;
8168       case LibFunc_exp2:
8169       case LibFunc_exp2f:
8170       case LibFunc_exp2l:
8171         if (visitUnaryFloatCall(I, ISD::FEXP2))
8172           return;
8173         break;
8174       case LibFunc_memcmp:
8175         if (visitMemCmpBCmpCall(I))
8176           return;
8177         break;
8178       case LibFunc_mempcpy:
8179         if (visitMemPCpyCall(I))
8180           return;
8181         break;
8182       case LibFunc_memchr:
8183         if (visitMemChrCall(I))
8184           return;
8185         break;
8186       case LibFunc_strcpy:
8187         if (visitStrCpyCall(I, false))
8188           return;
8189         break;
8190       case LibFunc_stpcpy:
8191         if (visitStrCpyCall(I, true))
8192           return;
8193         break;
8194       case LibFunc_strcmp:
8195         if (visitStrCmpCall(I))
8196           return;
8197         break;
8198       case LibFunc_strlen:
8199         if (visitStrLenCall(I))
8200           return;
8201         break;
8202       case LibFunc_strnlen:
8203         if (visitStrNLenCall(I))
8204           return;
8205         break;
8206       }
8207     }
8208   }
8209 
8210   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8211   // have to do anything here to lower funclet bundles.
8212   // CFGuardTarget bundles are lowered in LowerCallTo.
8213   assert(!I.hasOperandBundlesOtherThan(
8214              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8215               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8216               LLVMContext::OB_clang_arc_attachedcall}) &&
8217          "Cannot lower calls with arbitrary operand bundles!");
8218 
8219   SDValue Callee = getValue(I.getCalledOperand());
8220 
8221   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8222     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8223   else
8224     // Check if we can potentially perform a tail call. More detailed checking
8225     // is be done within LowerCallTo, after more information about the call is
8226     // known.
8227     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8228 }
8229 
8230 namespace {
8231 
8232 /// AsmOperandInfo - This contains information for each constraint that we are
8233 /// lowering.
8234 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8235 public:
8236   /// CallOperand - If this is the result output operand or a clobber
8237   /// this is null, otherwise it is the incoming operand to the CallInst.
8238   /// This gets modified as the asm is processed.
8239   SDValue CallOperand;
8240 
8241   /// AssignedRegs - If this is a register or register class operand, this
8242   /// contains the set of register corresponding to the operand.
8243   RegsForValue AssignedRegs;
8244 
8245   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8246     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8247   }
8248 
8249   /// Whether or not this operand accesses memory
8250   bool hasMemory(const TargetLowering &TLI) const {
8251     // Indirect operand accesses access memory.
8252     if (isIndirect)
8253       return true;
8254 
8255     for (const auto &Code : Codes)
8256       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8257         return true;
8258 
8259     return false;
8260   }
8261 
8262   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8263   /// corresponds to.  If there is no Value* for this operand, it returns
8264   /// MVT::Other.
8265   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8266                            const DataLayout &DL,
8267                            llvm::Type *ParamElemType) const {
8268     if (!CallOperandVal) return MVT::Other;
8269 
8270     if (isa<BasicBlock>(CallOperandVal))
8271       return TLI.getProgramPointerTy(DL);
8272 
8273     llvm::Type *OpTy = CallOperandVal->getType();
8274 
8275     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8276     // If this is an indirect operand, the operand is a pointer to the
8277     // accessed type.
8278     if (isIndirect) {
8279       OpTy = ParamElemType;
8280       assert(OpTy && "Indirect opernad must have elementtype attribute");
8281     }
8282 
8283     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8284     if (StructType *STy = dyn_cast<StructType>(OpTy))
8285       if (STy->getNumElements() == 1)
8286         OpTy = STy->getElementType(0);
8287 
8288     // If OpTy is not a single value, it may be a struct/union that we
8289     // can tile with integers.
8290     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8291       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8292       switch (BitSize) {
8293       default: break;
8294       case 1:
8295       case 8:
8296       case 16:
8297       case 32:
8298       case 64:
8299       case 128:
8300         OpTy = IntegerType::get(Context, BitSize);
8301         break;
8302       }
8303     }
8304 
8305     return TLI.getAsmOperandValueType(DL, OpTy, true);
8306   }
8307 };
8308 
8309 
8310 } // end anonymous namespace
8311 
8312 /// Make sure that the output operand \p OpInfo and its corresponding input
8313 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8314 /// out).
8315 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8316                                SDISelAsmOperandInfo &MatchingOpInfo,
8317                                SelectionDAG &DAG) {
8318   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8319     return;
8320 
8321   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8322   const auto &TLI = DAG.getTargetLoweringInfo();
8323 
8324   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8325       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8326                                        OpInfo.ConstraintVT);
8327   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8328       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8329                                        MatchingOpInfo.ConstraintVT);
8330   if ((OpInfo.ConstraintVT.isInteger() !=
8331        MatchingOpInfo.ConstraintVT.isInteger()) ||
8332       (MatchRC.second != InputRC.second)) {
8333     // FIXME: error out in a more elegant fashion
8334     report_fatal_error("Unsupported asm: input constraint"
8335                        " with a matching output constraint of"
8336                        " incompatible type!");
8337   }
8338   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8339 }
8340 
8341 /// Get a direct memory input to behave well as an indirect operand.
8342 /// This may introduce stores, hence the need for a \p Chain.
8343 /// \return The (possibly updated) chain.
8344 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8345                                         SDISelAsmOperandInfo &OpInfo,
8346                                         SelectionDAG &DAG) {
8347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8348 
8349   // If we don't have an indirect input, put it in the constpool if we can,
8350   // otherwise spill it to a stack slot.
8351   // TODO: This isn't quite right. We need to handle these according to
8352   // the addressing mode that the constraint wants. Also, this may take
8353   // an additional register for the computation and we don't want that
8354   // either.
8355 
8356   // If the operand is a float, integer, or vector constant, spill to a
8357   // constant pool entry to get its address.
8358   const Value *OpVal = OpInfo.CallOperandVal;
8359   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8360       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8361     OpInfo.CallOperand = DAG.getConstantPool(
8362         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8363     return Chain;
8364   }
8365 
8366   // Otherwise, create a stack slot and emit a store to it before the asm.
8367   Type *Ty = OpVal->getType();
8368   auto &DL = DAG.getDataLayout();
8369   uint64_t TySize = DL.getTypeAllocSize(Ty);
8370   MachineFunction &MF = DAG.getMachineFunction();
8371   int SSFI = MF.getFrameInfo().CreateStackObject(
8372       TySize, DL.getPrefTypeAlign(Ty), false);
8373   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8374   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8375                             MachinePointerInfo::getFixedStack(MF, SSFI),
8376                             TLI.getMemValueType(DL, Ty));
8377   OpInfo.CallOperand = StackSlot;
8378 
8379   return Chain;
8380 }
8381 
8382 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8383 /// specified operand.  We prefer to assign virtual registers, to allow the
8384 /// register allocator to handle the assignment process.  However, if the asm
8385 /// uses features that we can't model on machineinstrs, we have SDISel do the
8386 /// allocation.  This produces generally horrible, but correct, code.
8387 ///
8388 ///   OpInfo describes the operand
8389 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8390 static llvm::Optional<unsigned>
8391 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8392                      SDISelAsmOperandInfo &OpInfo,
8393                      SDISelAsmOperandInfo &RefOpInfo) {
8394   LLVMContext &Context = *DAG.getContext();
8395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8396 
8397   MachineFunction &MF = DAG.getMachineFunction();
8398   SmallVector<unsigned, 4> Regs;
8399   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8400 
8401   // No work to do for memory operations.
8402   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8403     return None;
8404 
8405   // If this is a constraint for a single physreg, or a constraint for a
8406   // register class, find it.
8407   unsigned AssignedReg;
8408   const TargetRegisterClass *RC;
8409   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8410       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8411   // RC is unset only on failure. Return immediately.
8412   if (!RC)
8413     return None;
8414 
8415   // Get the actual register value type.  This is important, because the user
8416   // may have asked for (e.g.) the AX register in i32 type.  We need to
8417   // remember that AX is actually i16 to get the right extension.
8418   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8419 
8420   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8421     // If this is an FP operand in an integer register (or visa versa), or more
8422     // generally if the operand value disagrees with the register class we plan
8423     // to stick it in, fix the operand type.
8424     //
8425     // If this is an input value, the bitcast to the new type is done now.
8426     // Bitcast for output value is done at the end of visitInlineAsm().
8427     if ((OpInfo.Type == InlineAsm::isOutput ||
8428          OpInfo.Type == InlineAsm::isInput) &&
8429         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8430       // Try to convert to the first EVT that the reg class contains.  If the
8431       // types are identical size, use a bitcast to convert (e.g. two differing
8432       // vector types).  Note: output bitcast is done at the end of
8433       // visitInlineAsm().
8434       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8435         // Exclude indirect inputs while they are unsupported because the code
8436         // to perform the load is missing and thus OpInfo.CallOperand still
8437         // refers to the input address rather than the pointed-to value.
8438         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8439           OpInfo.CallOperand =
8440               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8441         OpInfo.ConstraintVT = RegVT;
8442         // If the operand is an FP value and we want it in integer registers,
8443         // use the corresponding integer type. This turns an f64 value into
8444         // i64, which can be passed with two i32 values on a 32-bit machine.
8445       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8446         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8447         if (OpInfo.Type == InlineAsm::isInput)
8448           OpInfo.CallOperand =
8449               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8450         OpInfo.ConstraintVT = VT;
8451       }
8452     }
8453   }
8454 
8455   // No need to allocate a matching input constraint since the constraint it's
8456   // matching to has already been allocated.
8457   if (OpInfo.isMatchingInputConstraint())
8458     return None;
8459 
8460   EVT ValueVT = OpInfo.ConstraintVT;
8461   if (OpInfo.ConstraintVT == MVT::Other)
8462     ValueVT = RegVT;
8463 
8464   // Initialize NumRegs.
8465   unsigned NumRegs = 1;
8466   if (OpInfo.ConstraintVT != MVT::Other)
8467     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8468 
8469   // If this is a constraint for a specific physical register, like {r17},
8470   // assign it now.
8471 
8472   // If this associated to a specific register, initialize iterator to correct
8473   // place. If virtual, make sure we have enough registers
8474 
8475   // Initialize iterator if necessary
8476   TargetRegisterClass::iterator I = RC->begin();
8477   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8478 
8479   // Do not check for single registers.
8480   if (AssignedReg) {
8481     I = std::find(I, RC->end(), AssignedReg);
8482     if (I == RC->end()) {
8483       // RC does not contain the selected register, which indicates a
8484       // mismatch between the register and the required type/bitwidth.
8485       return {AssignedReg};
8486     }
8487   }
8488 
8489   for (; NumRegs; --NumRegs, ++I) {
8490     assert(I != RC->end() && "Ran out of registers to allocate!");
8491     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8492     Regs.push_back(R);
8493   }
8494 
8495   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8496   return None;
8497 }
8498 
8499 static unsigned
8500 findMatchingInlineAsmOperand(unsigned OperandNo,
8501                              const std::vector<SDValue> &AsmNodeOperands) {
8502   // Scan until we find the definition we already emitted of this operand.
8503   unsigned CurOp = InlineAsm::Op_FirstOperand;
8504   for (; OperandNo; --OperandNo) {
8505     // Advance to the next operand.
8506     unsigned OpFlag =
8507         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8508     assert((InlineAsm::isRegDefKind(OpFlag) ||
8509             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8510             InlineAsm::isMemKind(OpFlag)) &&
8511            "Skipped past definitions?");
8512     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8513   }
8514   return CurOp;
8515 }
8516 
8517 namespace {
8518 
8519 class ExtraFlags {
8520   unsigned Flags = 0;
8521 
8522 public:
8523   explicit ExtraFlags(const CallBase &Call) {
8524     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8525     if (IA->hasSideEffects())
8526       Flags |= InlineAsm::Extra_HasSideEffects;
8527     if (IA->isAlignStack())
8528       Flags |= InlineAsm::Extra_IsAlignStack;
8529     if (Call.isConvergent())
8530       Flags |= InlineAsm::Extra_IsConvergent;
8531     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8532   }
8533 
8534   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8535     // Ideally, we would only check against memory constraints.  However, the
8536     // meaning of an Other constraint can be target-specific and we can't easily
8537     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8538     // for Other constraints as well.
8539     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8540         OpInfo.ConstraintType == TargetLowering::C_Other) {
8541       if (OpInfo.Type == InlineAsm::isInput)
8542         Flags |= InlineAsm::Extra_MayLoad;
8543       else if (OpInfo.Type == InlineAsm::isOutput)
8544         Flags |= InlineAsm::Extra_MayStore;
8545       else if (OpInfo.Type == InlineAsm::isClobber)
8546         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8547     }
8548   }
8549 
8550   unsigned get() const { return Flags; }
8551 };
8552 
8553 } // end anonymous namespace
8554 
8555 /// visitInlineAsm - Handle a call to an InlineAsm object.
8556 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8557                                          const BasicBlock *EHPadBB) {
8558   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8559 
8560   /// ConstraintOperands - Information about all of the constraints.
8561   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8562 
8563   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8564   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8565       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8566 
8567   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8568   // AsmDialect, MayLoad, MayStore).
8569   bool HasSideEffect = IA->hasSideEffects();
8570   ExtraFlags ExtraInfo(Call);
8571 
8572   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8573   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8574   for (auto &T : TargetConstraints) {
8575     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8576     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8577 
8578     // Compute the value type for each operand.
8579     if (OpInfo.hasArg()) {
8580       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
8581       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8582       Type *ParamElemTy = Call.getAttributes().getParamElementType(ArgNo);
8583       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8584                                            DAG.getDataLayout(), ParamElemTy);
8585       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8586       ArgNo++;
8587     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8588       // The return value of the call is this value.  As such, there is no
8589       // corresponding argument.
8590       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8591       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8592         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8593             DAG.getDataLayout(), STy->getElementType(ResNo));
8594       } else {
8595         assert(ResNo == 0 && "Asm only has one result!");
8596         OpInfo.ConstraintVT = TLI.getAsmOperandValueType(
8597             DAG.getDataLayout(), Call.getType()).getSimpleVT();
8598       }
8599       ++ResNo;
8600     } else {
8601       OpInfo.ConstraintVT = MVT::Other;
8602     }
8603 
8604     if (!HasSideEffect)
8605       HasSideEffect = OpInfo.hasMemory(TLI);
8606 
8607     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8608     // FIXME: Could we compute this on OpInfo rather than T?
8609 
8610     // Compute the constraint code and ConstraintType to use.
8611     TLI.ComputeConstraintToUse(T, SDValue());
8612 
8613     if (T.ConstraintType == TargetLowering::C_Immediate &&
8614         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8615       // We've delayed emitting a diagnostic like the "n" constraint because
8616       // inlining could cause an integer showing up.
8617       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8618                                           "' expects an integer constant "
8619                                           "expression");
8620 
8621     ExtraInfo.update(T);
8622   }
8623 
8624   // We won't need to flush pending loads if this asm doesn't touch
8625   // memory and is nonvolatile.
8626   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8627 
8628   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8629   if (EmitEHLabels) {
8630     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8631   }
8632   bool IsCallBr = isa<CallBrInst>(Call);
8633 
8634   if (IsCallBr || EmitEHLabels) {
8635     // If this is a callbr or invoke we need to flush pending exports since
8636     // inlineasm_br and invoke are terminators.
8637     // We need to do this before nodes are glued to the inlineasm_br node.
8638     Chain = getControlRoot();
8639   }
8640 
8641   MCSymbol *BeginLabel = nullptr;
8642   if (EmitEHLabels) {
8643     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8644   }
8645 
8646   // Second pass over the constraints: compute which constraint option to use.
8647   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8648     // If this is an output operand with a matching input operand, look up the
8649     // matching input. If their types mismatch, e.g. one is an integer, the
8650     // other is floating point, or their sizes are different, flag it as an
8651     // error.
8652     if (OpInfo.hasMatchingInput()) {
8653       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8654       patchMatchingInput(OpInfo, Input, DAG);
8655     }
8656 
8657     // Compute the constraint code and ConstraintType to use.
8658     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8659 
8660     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8661         OpInfo.Type == InlineAsm::isClobber)
8662       continue;
8663 
8664     // If this is a memory input, and if the operand is not indirect, do what we
8665     // need to provide an address for the memory input.
8666     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8667         !OpInfo.isIndirect) {
8668       assert((OpInfo.isMultipleAlternative ||
8669               (OpInfo.Type == InlineAsm::isInput)) &&
8670              "Can only indirectify direct input operands!");
8671 
8672       // Memory operands really want the address of the value.
8673       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8674 
8675       // There is no longer a Value* corresponding to this operand.
8676       OpInfo.CallOperandVal = nullptr;
8677 
8678       // It is now an indirect operand.
8679       OpInfo.isIndirect = true;
8680     }
8681 
8682   }
8683 
8684   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8685   std::vector<SDValue> AsmNodeOperands;
8686   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8687   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8688       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8689 
8690   // If we have a !srcloc metadata node associated with it, we want to attach
8691   // this to the ultimately generated inline asm machineinstr.  To do this, we
8692   // pass in the third operand as this (potentially null) inline asm MDNode.
8693   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8694   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8695 
8696   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8697   // bits as operand 3.
8698   AsmNodeOperands.push_back(DAG.getTargetConstant(
8699       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8700 
8701   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8702   // this, assign virtual and physical registers for inputs and otput.
8703   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8704     // Assign Registers.
8705     SDISelAsmOperandInfo &RefOpInfo =
8706         OpInfo.isMatchingInputConstraint()
8707             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8708             : OpInfo;
8709     const auto RegError =
8710         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8711     if (RegError.hasValue()) {
8712       const MachineFunction &MF = DAG.getMachineFunction();
8713       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8714       const char *RegName = TRI.getName(RegError.getValue());
8715       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8716                                    "' allocated for constraint '" +
8717                                    Twine(OpInfo.ConstraintCode) +
8718                                    "' does not match required type");
8719       return;
8720     }
8721 
8722     auto DetectWriteToReservedRegister = [&]() {
8723       const MachineFunction &MF = DAG.getMachineFunction();
8724       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8725       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8726         if (Register::isPhysicalRegister(Reg) &&
8727             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8728           const char *RegName = TRI.getName(Reg);
8729           emitInlineAsmError(Call, "write to reserved register '" +
8730                                        Twine(RegName) + "'");
8731           return true;
8732         }
8733       }
8734       return false;
8735     };
8736 
8737     switch (OpInfo.Type) {
8738     case InlineAsm::isOutput:
8739       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8740         unsigned ConstraintID =
8741             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8742         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8743                "Failed to convert memory constraint code to constraint id.");
8744 
8745         // Add information to the INLINEASM node to know about this output.
8746         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8747         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8748         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8749                                                         MVT::i32));
8750         AsmNodeOperands.push_back(OpInfo.CallOperand);
8751       } else {
8752         // Otherwise, this outputs to a register (directly for C_Register /
8753         // C_RegisterClass, and a target-defined fashion for
8754         // C_Immediate/C_Other). Find a register that we can use.
8755         if (OpInfo.AssignedRegs.Regs.empty()) {
8756           emitInlineAsmError(
8757               Call, "couldn't allocate output register for constraint '" +
8758                         Twine(OpInfo.ConstraintCode) + "'");
8759           return;
8760         }
8761 
8762         if (DetectWriteToReservedRegister())
8763           return;
8764 
8765         // Add information to the INLINEASM node to know that this register is
8766         // set.
8767         OpInfo.AssignedRegs.AddInlineAsmOperands(
8768             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8769                                   : InlineAsm::Kind_RegDef,
8770             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8771       }
8772       break;
8773 
8774     case InlineAsm::isInput: {
8775       SDValue InOperandVal = OpInfo.CallOperand;
8776 
8777       if (OpInfo.isMatchingInputConstraint()) {
8778         // If this is required to match an output register we have already set,
8779         // just use its register.
8780         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8781                                                   AsmNodeOperands);
8782         unsigned OpFlag =
8783           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8784         if (InlineAsm::isRegDefKind(OpFlag) ||
8785             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8786           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8787           if (OpInfo.isIndirect) {
8788             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8789             emitInlineAsmError(Call, "inline asm not supported yet: "
8790                                      "don't know how to handle tied "
8791                                      "indirect register inputs");
8792             return;
8793           }
8794 
8795           SmallVector<unsigned, 4> Regs;
8796           MachineFunction &MF = DAG.getMachineFunction();
8797           MachineRegisterInfo &MRI = MF.getRegInfo();
8798           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8799           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8800           Register TiedReg = R->getReg();
8801           MVT RegVT = R->getSimpleValueType(0);
8802           const TargetRegisterClass *RC =
8803               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
8804               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
8805                                       : TRI.getMinimalPhysRegClass(TiedReg);
8806           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8807           for (unsigned i = 0; i != NumRegs; ++i)
8808             Regs.push_back(MRI.createVirtualRegister(RC));
8809 
8810           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8811 
8812           SDLoc dl = getCurSDLoc();
8813           // Use the produced MatchedRegs object to
8814           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8815           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8816                                            true, OpInfo.getMatchedOperand(), dl,
8817                                            DAG, AsmNodeOperands);
8818           break;
8819         }
8820 
8821         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8822         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8823                "Unexpected number of operands");
8824         // Add information to the INLINEASM node to know about this input.
8825         // See InlineAsm.h isUseOperandTiedToDef.
8826         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8827         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8828                                                     OpInfo.getMatchedOperand());
8829         AsmNodeOperands.push_back(DAG.getTargetConstant(
8830             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8831         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8832         break;
8833       }
8834 
8835       // Treat indirect 'X' constraint as memory.
8836       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8837           OpInfo.isIndirect)
8838         OpInfo.ConstraintType = TargetLowering::C_Memory;
8839 
8840       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8841           OpInfo.ConstraintType == TargetLowering::C_Other) {
8842         std::vector<SDValue> Ops;
8843         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8844                                           Ops, DAG);
8845         if (Ops.empty()) {
8846           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8847             if (isa<ConstantSDNode>(InOperandVal)) {
8848               emitInlineAsmError(Call, "value out of range for constraint '" +
8849                                            Twine(OpInfo.ConstraintCode) + "'");
8850               return;
8851             }
8852 
8853           emitInlineAsmError(Call,
8854                              "invalid operand for inline asm constraint '" +
8855                                  Twine(OpInfo.ConstraintCode) + "'");
8856           return;
8857         }
8858 
8859         // Add information to the INLINEASM node to know about this input.
8860         unsigned ResOpType =
8861           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8862         AsmNodeOperands.push_back(DAG.getTargetConstant(
8863             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8864         llvm::append_range(AsmNodeOperands, Ops);
8865         break;
8866       }
8867 
8868       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8869         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8870         assert(InOperandVal.getValueType() ==
8871                    TLI.getPointerTy(DAG.getDataLayout()) &&
8872                "Memory operands expect pointer values");
8873 
8874         unsigned ConstraintID =
8875             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8876         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8877                "Failed to convert memory constraint code to constraint id.");
8878 
8879         // Add information to the INLINEASM node to know about this input.
8880         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8881         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8882         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8883                                                         getCurSDLoc(),
8884                                                         MVT::i32));
8885         AsmNodeOperands.push_back(InOperandVal);
8886         break;
8887       }
8888 
8889       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8890               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8891              "Unknown constraint type!");
8892 
8893       // TODO: Support this.
8894       if (OpInfo.isIndirect) {
8895         emitInlineAsmError(
8896             Call, "Don't know how to handle indirect register inputs yet "
8897                   "for constraint '" +
8898                       Twine(OpInfo.ConstraintCode) + "'");
8899         return;
8900       }
8901 
8902       // Copy the input into the appropriate registers.
8903       if (OpInfo.AssignedRegs.Regs.empty()) {
8904         emitInlineAsmError(Call,
8905                            "couldn't allocate input reg for constraint '" +
8906                                Twine(OpInfo.ConstraintCode) + "'");
8907         return;
8908       }
8909 
8910       if (DetectWriteToReservedRegister())
8911         return;
8912 
8913       SDLoc dl = getCurSDLoc();
8914 
8915       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8916                                         &Call);
8917 
8918       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8919                                                dl, DAG, AsmNodeOperands);
8920       break;
8921     }
8922     case InlineAsm::isClobber:
8923       // Add the clobbered value to the operand list, so that the register
8924       // allocator is aware that the physreg got clobbered.
8925       if (!OpInfo.AssignedRegs.Regs.empty())
8926         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8927                                                  false, 0, getCurSDLoc(), DAG,
8928                                                  AsmNodeOperands);
8929       break;
8930     }
8931   }
8932 
8933   // Finish up input operands.  Set the input chain and add the flag last.
8934   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8935   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8936 
8937   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8938   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8939                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8940   Flag = Chain.getValue(1);
8941 
8942   // Do additional work to generate outputs.
8943 
8944   SmallVector<EVT, 1> ResultVTs;
8945   SmallVector<SDValue, 1> ResultValues;
8946   SmallVector<SDValue, 8> OutChains;
8947 
8948   llvm::Type *CallResultType = Call.getType();
8949   ArrayRef<Type *> ResultTypes;
8950   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8951     ResultTypes = StructResult->elements();
8952   else if (!CallResultType->isVoidTy())
8953     ResultTypes = makeArrayRef(CallResultType);
8954 
8955   auto CurResultType = ResultTypes.begin();
8956   auto handleRegAssign = [&](SDValue V) {
8957     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8958     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8959     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8960     ++CurResultType;
8961     // If the type of the inline asm call site return value is different but has
8962     // same size as the type of the asm output bitcast it.  One example of this
8963     // is for vectors with different width / number of elements.  This can
8964     // happen for register classes that can contain multiple different value
8965     // types.  The preg or vreg allocated may not have the same VT as was
8966     // expected.
8967     //
8968     // This can also happen for a return value that disagrees with the register
8969     // class it is put in, eg. a double in a general-purpose register on a
8970     // 32-bit machine.
8971     if (ResultVT != V.getValueType() &&
8972         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8973       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8974     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8975              V.getValueType().isInteger()) {
8976       // If a result value was tied to an input value, the computed result
8977       // may have a wider width than the expected result.  Extract the
8978       // relevant portion.
8979       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8980     }
8981     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8982     ResultVTs.push_back(ResultVT);
8983     ResultValues.push_back(V);
8984   };
8985 
8986   // Deal with output operands.
8987   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8988     if (OpInfo.Type == InlineAsm::isOutput) {
8989       SDValue Val;
8990       // Skip trivial output operands.
8991       if (OpInfo.AssignedRegs.Regs.empty())
8992         continue;
8993 
8994       switch (OpInfo.ConstraintType) {
8995       case TargetLowering::C_Register:
8996       case TargetLowering::C_RegisterClass:
8997         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8998                                                   Chain, &Flag, &Call);
8999         break;
9000       case TargetLowering::C_Immediate:
9001       case TargetLowering::C_Other:
9002         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9003                                               OpInfo, DAG);
9004         break;
9005       case TargetLowering::C_Memory:
9006         break; // Already handled.
9007       case TargetLowering::C_Unknown:
9008         assert(false && "Unexpected unknown constraint");
9009       }
9010 
9011       // Indirect output manifest as stores. Record output chains.
9012       if (OpInfo.isIndirect) {
9013         const Value *Ptr = OpInfo.CallOperandVal;
9014         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9015         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9016                                      MachinePointerInfo(Ptr));
9017         OutChains.push_back(Store);
9018       } else {
9019         // generate CopyFromRegs to associated registers.
9020         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9021         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9022           for (const SDValue &V : Val->op_values())
9023             handleRegAssign(V);
9024         } else
9025           handleRegAssign(Val);
9026       }
9027     }
9028   }
9029 
9030   // Set results.
9031   if (!ResultValues.empty()) {
9032     assert(CurResultType == ResultTypes.end() &&
9033            "Mismatch in number of ResultTypes");
9034     assert(ResultValues.size() == ResultTypes.size() &&
9035            "Mismatch in number of output operands in asm result");
9036 
9037     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9038                             DAG.getVTList(ResultVTs), ResultValues);
9039     setValue(&Call, V);
9040   }
9041 
9042   // Collect store chains.
9043   if (!OutChains.empty())
9044     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9045 
9046   if (EmitEHLabels) {
9047     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9048   }
9049 
9050   // Only Update Root if inline assembly has a memory effect.
9051   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9052       EmitEHLabels)
9053     DAG.setRoot(Chain);
9054 }
9055 
9056 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9057                                              const Twine &Message) {
9058   LLVMContext &Ctx = *DAG.getContext();
9059   Ctx.emitError(&Call, Message);
9060 
9061   // Make sure we leave the DAG in a valid state
9062   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9063   SmallVector<EVT, 1> ValueVTs;
9064   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9065 
9066   if (ValueVTs.empty())
9067     return;
9068 
9069   SmallVector<SDValue, 1> Ops;
9070   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9071     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9072 
9073   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9074 }
9075 
9076 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9077   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9078                           MVT::Other, getRoot(),
9079                           getValue(I.getArgOperand(0)),
9080                           DAG.getSrcValue(I.getArgOperand(0))));
9081 }
9082 
9083 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9085   const DataLayout &DL = DAG.getDataLayout();
9086   SDValue V = DAG.getVAArg(
9087       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9088       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9089       DL.getABITypeAlign(I.getType()).value());
9090   DAG.setRoot(V.getValue(1));
9091 
9092   if (I.getType()->isPointerTy())
9093     V = DAG.getPtrExtOrTrunc(
9094         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9095   setValue(&I, V);
9096 }
9097 
9098 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9099   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9100                           MVT::Other, getRoot(),
9101                           getValue(I.getArgOperand(0)),
9102                           DAG.getSrcValue(I.getArgOperand(0))));
9103 }
9104 
9105 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9106   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9107                           MVT::Other, getRoot(),
9108                           getValue(I.getArgOperand(0)),
9109                           getValue(I.getArgOperand(1)),
9110                           DAG.getSrcValue(I.getArgOperand(0)),
9111                           DAG.getSrcValue(I.getArgOperand(1))));
9112 }
9113 
9114 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9115                                                     const Instruction &I,
9116                                                     SDValue Op) {
9117   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9118   if (!Range)
9119     return Op;
9120 
9121   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9122   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9123     return Op;
9124 
9125   APInt Lo = CR.getUnsignedMin();
9126   if (!Lo.isMinValue())
9127     return Op;
9128 
9129   APInt Hi = CR.getUnsignedMax();
9130   unsigned Bits = std::max(Hi.getActiveBits(),
9131                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9132 
9133   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9134 
9135   SDLoc SL = getCurSDLoc();
9136 
9137   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9138                              DAG.getValueType(SmallVT));
9139   unsigned NumVals = Op.getNode()->getNumValues();
9140   if (NumVals == 1)
9141     return ZExt;
9142 
9143   SmallVector<SDValue, 4> Ops;
9144 
9145   Ops.push_back(ZExt);
9146   for (unsigned I = 1; I != NumVals; ++I)
9147     Ops.push_back(Op.getValue(I));
9148 
9149   return DAG.getMergeValues(Ops, SL);
9150 }
9151 
9152 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9153 /// the call being lowered.
9154 ///
9155 /// This is a helper for lowering intrinsics that follow a target calling
9156 /// convention or require stack pointer adjustment. Only a subset of the
9157 /// intrinsic's operands need to participate in the calling convention.
9158 void SelectionDAGBuilder::populateCallLoweringInfo(
9159     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9160     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9161     bool IsPatchPoint) {
9162   TargetLowering::ArgListTy Args;
9163   Args.reserve(NumArgs);
9164 
9165   // Populate the argument list.
9166   // Attributes for args start at offset 1, after the return attribute.
9167   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9168        ArgI != ArgE; ++ArgI) {
9169     const Value *V = Call->getOperand(ArgI);
9170 
9171     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9172 
9173     TargetLowering::ArgListEntry Entry;
9174     Entry.Node = getValue(V);
9175     Entry.Ty = V->getType();
9176     Entry.setAttributes(Call, ArgI);
9177     Args.push_back(Entry);
9178   }
9179 
9180   CLI.setDebugLoc(getCurSDLoc())
9181       .setChain(getRoot())
9182       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9183       .setDiscardResult(Call->use_empty())
9184       .setIsPatchPoint(IsPatchPoint)
9185       .setIsPreallocated(
9186           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9187 }
9188 
9189 /// Add a stack map intrinsic call's live variable operands to a stackmap
9190 /// or patchpoint target node's operand list.
9191 ///
9192 /// Constants are converted to TargetConstants purely as an optimization to
9193 /// avoid constant materialization and register allocation.
9194 ///
9195 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9196 /// generate addess computation nodes, and so FinalizeISel can convert the
9197 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9198 /// address materialization and register allocation, but may also be required
9199 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9200 /// alloca in the entry block, then the runtime may assume that the alloca's
9201 /// StackMap location can be read immediately after compilation and that the
9202 /// location is valid at any point during execution (this is similar to the
9203 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9204 /// only available in a register, then the runtime would need to trap when
9205 /// execution reaches the StackMap in order to read the alloca's location.
9206 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9207                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9208                                 SelectionDAGBuilder &Builder) {
9209   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
9210     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
9211     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
9212       Ops.push_back(
9213         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
9214       Ops.push_back(
9215         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
9216     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
9217       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
9218       Ops.push_back(Builder.DAG.getTargetFrameIndex(
9219           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
9220     } else
9221       Ops.push_back(OpVal);
9222   }
9223 }
9224 
9225 /// Lower llvm.experimental.stackmap directly to its target opcode.
9226 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9227   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
9228   //                                  [live variables...])
9229 
9230   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9231 
9232   SDValue Chain, InFlag, Callee, NullPtr;
9233   SmallVector<SDValue, 32> Ops;
9234 
9235   SDLoc DL = getCurSDLoc();
9236   Callee = getValue(CI.getCalledOperand());
9237   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9238 
9239   // The stackmap intrinsic only records the live variables (the arguments
9240   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9241   // intrinsic, this won't be lowered to a function call. This means we don't
9242   // have to worry about calling conventions and target specific lowering code.
9243   // Instead we perform the call lowering right here.
9244   //
9245   // chain, flag = CALLSEQ_START(chain, 0, 0)
9246   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9247   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9248   //
9249   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9250   InFlag = Chain.getValue(1);
9251 
9252   // Add the <id> and <numBytes> constants.
9253   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9254   Ops.push_back(DAG.getTargetConstant(
9255                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9256   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9257   Ops.push_back(DAG.getTargetConstant(
9258                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9259                   MVT::i32));
9260 
9261   // Push live variables for the stack map.
9262   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9263 
9264   // We are not pushing any register mask info here on the operands list,
9265   // because the stackmap doesn't clobber anything.
9266 
9267   // Push the chain and the glue flag.
9268   Ops.push_back(Chain);
9269   Ops.push_back(InFlag);
9270 
9271   // Create the STACKMAP node.
9272   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9273   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9274   Chain = SDValue(SM, 0);
9275   InFlag = Chain.getValue(1);
9276 
9277   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9278 
9279   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9280 
9281   // Set the root to the target-lowered call chain.
9282   DAG.setRoot(Chain);
9283 
9284   // Inform the Frame Information that we have a stackmap in this function.
9285   FuncInfo.MF->getFrameInfo().setHasStackMap();
9286 }
9287 
9288 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9289 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9290                                           const BasicBlock *EHPadBB) {
9291   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9292   //                                                 i32 <numBytes>,
9293   //                                                 i8* <target>,
9294   //                                                 i32 <numArgs>,
9295   //                                                 [Args...],
9296   //                                                 [live variables...])
9297 
9298   CallingConv::ID CC = CB.getCallingConv();
9299   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9300   bool HasDef = !CB.getType()->isVoidTy();
9301   SDLoc dl = getCurSDLoc();
9302   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9303 
9304   // Handle immediate and symbolic callees.
9305   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9306     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9307                                    /*isTarget=*/true);
9308   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9309     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9310                                          SDLoc(SymbolicCallee),
9311                                          SymbolicCallee->getValueType(0));
9312 
9313   // Get the real number of arguments participating in the call <numArgs>
9314   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9315   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9316 
9317   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9318   // Intrinsics include all meta-operands up to but not including CC.
9319   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9320   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9321          "Not enough arguments provided to the patchpoint intrinsic");
9322 
9323   // For AnyRegCC the arguments are lowered later on manually.
9324   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9325   Type *ReturnTy =
9326       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9327 
9328   TargetLowering::CallLoweringInfo CLI(DAG);
9329   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9330                            ReturnTy, true);
9331   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9332 
9333   SDNode *CallEnd = Result.second.getNode();
9334   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9335     CallEnd = CallEnd->getOperand(0).getNode();
9336 
9337   /// Get a call instruction from the call sequence chain.
9338   /// Tail calls are not allowed.
9339   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9340          "Expected a callseq node.");
9341   SDNode *Call = CallEnd->getOperand(0).getNode();
9342   bool HasGlue = Call->getGluedNode();
9343 
9344   // Replace the target specific call node with the patchable intrinsic.
9345   SmallVector<SDValue, 8> Ops;
9346 
9347   // Add the <id> and <numBytes> constants.
9348   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9349   Ops.push_back(DAG.getTargetConstant(
9350                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9351   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9352   Ops.push_back(DAG.getTargetConstant(
9353                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9354                   MVT::i32));
9355 
9356   // Add the callee.
9357   Ops.push_back(Callee);
9358 
9359   // Adjust <numArgs> to account for any arguments that have been passed on the
9360   // stack instead.
9361   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9362   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9363   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9364   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9365 
9366   // Add the calling convention
9367   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9368 
9369   // Add the arguments we omitted previously. The register allocator should
9370   // place these in any free register.
9371   if (IsAnyRegCC)
9372     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9373       Ops.push_back(getValue(CB.getArgOperand(i)));
9374 
9375   // Push the arguments from the call instruction up to the register mask.
9376   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9377   Ops.append(Call->op_begin() + 2, e);
9378 
9379   // Push live variables for the stack map.
9380   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9381 
9382   // Push the register mask info.
9383   if (HasGlue)
9384     Ops.push_back(*(Call->op_end()-2));
9385   else
9386     Ops.push_back(*(Call->op_end()-1));
9387 
9388   // Push the chain (this is originally the first operand of the call, but
9389   // becomes now the last or second to last operand).
9390   Ops.push_back(*(Call->op_begin()));
9391 
9392   // Push the glue flag (last operand).
9393   if (HasGlue)
9394     Ops.push_back(*(Call->op_end()-1));
9395 
9396   SDVTList NodeTys;
9397   if (IsAnyRegCC && HasDef) {
9398     // Create the return types based on the intrinsic definition
9399     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9400     SmallVector<EVT, 3> ValueVTs;
9401     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9402     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9403 
9404     // There is always a chain and a glue type at the end
9405     ValueVTs.push_back(MVT::Other);
9406     ValueVTs.push_back(MVT::Glue);
9407     NodeTys = DAG.getVTList(ValueVTs);
9408   } else
9409     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9410 
9411   // Replace the target specific call node with a PATCHPOINT node.
9412   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9413                                          dl, NodeTys, Ops);
9414 
9415   // Update the NodeMap.
9416   if (HasDef) {
9417     if (IsAnyRegCC)
9418       setValue(&CB, SDValue(MN, 0));
9419     else
9420       setValue(&CB, Result.first);
9421   }
9422 
9423   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9424   // call sequence. Furthermore the location of the chain and glue can change
9425   // when the AnyReg calling convention is used and the intrinsic returns a
9426   // value.
9427   if (IsAnyRegCC && HasDef) {
9428     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9429     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9430     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9431   } else
9432     DAG.ReplaceAllUsesWith(Call, MN);
9433   DAG.DeleteNode(Call);
9434 
9435   // Inform the Frame Information that we have a patchpoint in this function.
9436   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9437 }
9438 
9439 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9440                                             unsigned Intrinsic) {
9441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9442   SDValue Op1 = getValue(I.getArgOperand(0));
9443   SDValue Op2;
9444   if (I.arg_size() > 1)
9445     Op2 = getValue(I.getArgOperand(1));
9446   SDLoc dl = getCurSDLoc();
9447   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9448   SDValue Res;
9449   SDNodeFlags SDFlags;
9450   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9451     SDFlags.copyFMF(*FPMO);
9452 
9453   switch (Intrinsic) {
9454   case Intrinsic::vector_reduce_fadd:
9455     if (SDFlags.hasAllowReassociation())
9456       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9457                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9458                         SDFlags);
9459     else
9460       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9461     break;
9462   case Intrinsic::vector_reduce_fmul:
9463     if (SDFlags.hasAllowReassociation())
9464       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9465                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9466                         SDFlags);
9467     else
9468       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9469     break;
9470   case Intrinsic::vector_reduce_add:
9471     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9472     break;
9473   case Intrinsic::vector_reduce_mul:
9474     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9475     break;
9476   case Intrinsic::vector_reduce_and:
9477     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9478     break;
9479   case Intrinsic::vector_reduce_or:
9480     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9481     break;
9482   case Intrinsic::vector_reduce_xor:
9483     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9484     break;
9485   case Intrinsic::vector_reduce_smax:
9486     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9487     break;
9488   case Intrinsic::vector_reduce_smin:
9489     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9490     break;
9491   case Intrinsic::vector_reduce_umax:
9492     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9493     break;
9494   case Intrinsic::vector_reduce_umin:
9495     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9496     break;
9497   case Intrinsic::vector_reduce_fmax:
9498     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9499     break;
9500   case Intrinsic::vector_reduce_fmin:
9501     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9502     break;
9503   default:
9504     llvm_unreachable("Unhandled vector reduce intrinsic");
9505   }
9506   setValue(&I, Res);
9507 }
9508 
9509 /// Returns an AttributeList representing the attributes applied to the return
9510 /// value of the given call.
9511 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9512   SmallVector<Attribute::AttrKind, 2> Attrs;
9513   if (CLI.RetSExt)
9514     Attrs.push_back(Attribute::SExt);
9515   if (CLI.RetZExt)
9516     Attrs.push_back(Attribute::ZExt);
9517   if (CLI.IsInReg)
9518     Attrs.push_back(Attribute::InReg);
9519 
9520   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9521                             Attrs);
9522 }
9523 
9524 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9525 /// implementation, which just calls LowerCall.
9526 /// FIXME: When all targets are
9527 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9528 std::pair<SDValue, SDValue>
9529 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9530   // Handle the incoming return values from the call.
9531   CLI.Ins.clear();
9532   Type *OrigRetTy = CLI.RetTy;
9533   SmallVector<EVT, 4> RetTys;
9534   SmallVector<uint64_t, 4> Offsets;
9535   auto &DL = CLI.DAG.getDataLayout();
9536   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9537 
9538   if (CLI.IsPostTypeLegalization) {
9539     // If we are lowering a libcall after legalization, split the return type.
9540     SmallVector<EVT, 4> OldRetTys;
9541     SmallVector<uint64_t, 4> OldOffsets;
9542     RetTys.swap(OldRetTys);
9543     Offsets.swap(OldOffsets);
9544 
9545     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9546       EVT RetVT = OldRetTys[i];
9547       uint64_t Offset = OldOffsets[i];
9548       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9549       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9550       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9551       RetTys.append(NumRegs, RegisterVT);
9552       for (unsigned j = 0; j != NumRegs; ++j)
9553         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9554     }
9555   }
9556 
9557   SmallVector<ISD::OutputArg, 4> Outs;
9558   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9559 
9560   bool CanLowerReturn =
9561       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9562                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9563 
9564   SDValue DemoteStackSlot;
9565   int DemoteStackIdx = -100;
9566   if (!CanLowerReturn) {
9567     // FIXME: equivalent assert?
9568     // assert(!CS.hasInAllocaArgument() &&
9569     //        "sret demotion is incompatible with inalloca");
9570     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9571     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9572     MachineFunction &MF = CLI.DAG.getMachineFunction();
9573     DemoteStackIdx =
9574         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9575     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9576                                               DL.getAllocaAddrSpace());
9577 
9578     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9579     ArgListEntry Entry;
9580     Entry.Node = DemoteStackSlot;
9581     Entry.Ty = StackSlotPtrType;
9582     Entry.IsSExt = false;
9583     Entry.IsZExt = false;
9584     Entry.IsInReg = false;
9585     Entry.IsSRet = true;
9586     Entry.IsNest = false;
9587     Entry.IsByVal = false;
9588     Entry.IsByRef = false;
9589     Entry.IsReturned = false;
9590     Entry.IsSwiftSelf = false;
9591     Entry.IsSwiftAsync = false;
9592     Entry.IsSwiftError = false;
9593     Entry.IsCFGuardTarget = false;
9594     Entry.Alignment = Alignment;
9595     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9596     CLI.NumFixedArgs += 1;
9597     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9598 
9599     // sret demotion isn't compatible with tail-calls, since the sret argument
9600     // points into the callers stack frame.
9601     CLI.IsTailCall = false;
9602   } else {
9603     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9604         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9605     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9606       ISD::ArgFlagsTy Flags;
9607       if (NeedsRegBlock) {
9608         Flags.setInConsecutiveRegs();
9609         if (I == RetTys.size() - 1)
9610           Flags.setInConsecutiveRegsLast();
9611       }
9612       EVT VT = RetTys[I];
9613       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9614                                                      CLI.CallConv, VT);
9615       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9616                                                        CLI.CallConv, VT);
9617       for (unsigned i = 0; i != NumRegs; ++i) {
9618         ISD::InputArg MyFlags;
9619         MyFlags.Flags = Flags;
9620         MyFlags.VT = RegisterVT;
9621         MyFlags.ArgVT = VT;
9622         MyFlags.Used = CLI.IsReturnValueUsed;
9623         if (CLI.RetTy->isPointerTy()) {
9624           MyFlags.Flags.setPointer();
9625           MyFlags.Flags.setPointerAddrSpace(
9626               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9627         }
9628         if (CLI.RetSExt)
9629           MyFlags.Flags.setSExt();
9630         if (CLI.RetZExt)
9631           MyFlags.Flags.setZExt();
9632         if (CLI.IsInReg)
9633           MyFlags.Flags.setInReg();
9634         CLI.Ins.push_back(MyFlags);
9635       }
9636     }
9637   }
9638 
9639   // We push in swifterror return as the last element of CLI.Ins.
9640   ArgListTy &Args = CLI.getArgs();
9641   if (supportSwiftError()) {
9642     for (const ArgListEntry &Arg : Args) {
9643       if (Arg.IsSwiftError) {
9644         ISD::InputArg MyFlags;
9645         MyFlags.VT = getPointerTy(DL);
9646         MyFlags.ArgVT = EVT(getPointerTy(DL));
9647         MyFlags.Flags.setSwiftError();
9648         CLI.Ins.push_back(MyFlags);
9649       }
9650     }
9651   }
9652 
9653   // Handle all of the outgoing arguments.
9654   CLI.Outs.clear();
9655   CLI.OutVals.clear();
9656   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9657     SmallVector<EVT, 4> ValueVTs;
9658     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9659     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9660     Type *FinalType = Args[i].Ty;
9661     if (Args[i].IsByVal)
9662       FinalType = Args[i].IndirectType;
9663     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9664         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9665     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9666          ++Value) {
9667       EVT VT = ValueVTs[Value];
9668       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9669       SDValue Op = SDValue(Args[i].Node.getNode(),
9670                            Args[i].Node.getResNo() + Value);
9671       ISD::ArgFlagsTy Flags;
9672 
9673       // Certain targets (such as MIPS), may have a different ABI alignment
9674       // for a type depending on the context. Give the target a chance to
9675       // specify the alignment it wants.
9676       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9677       Flags.setOrigAlign(OriginalAlignment);
9678 
9679       if (Args[i].Ty->isPointerTy()) {
9680         Flags.setPointer();
9681         Flags.setPointerAddrSpace(
9682             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9683       }
9684       if (Args[i].IsZExt)
9685         Flags.setZExt();
9686       if (Args[i].IsSExt)
9687         Flags.setSExt();
9688       if (Args[i].IsInReg) {
9689         // If we are using vectorcall calling convention, a structure that is
9690         // passed InReg - is surely an HVA
9691         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9692             isa<StructType>(FinalType)) {
9693           // The first value of a structure is marked
9694           if (0 == Value)
9695             Flags.setHvaStart();
9696           Flags.setHva();
9697         }
9698         // Set InReg Flag
9699         Flags.setInReg();
9700       }
9701       if (Args[i].IsSRet)
9702         Flags.setSRet();
9703       if (Args[i].IsSwiftSelf)
9704         Flags.setSwiftSelf();
9705       if (Args[i].IsSwiftAsync)
9706         Flags.setSwiftAsync();
9707       if (Args[i].IsSwiftError)
9708         Flags.setSwiftError();
9709       if (Args[i].IsCFGuardTarget)
9710         Flags.setCFGuardTarget();
9711       if (Args[i].IsByVal)
9712         Flags.setByVal();
9713       if (Args[i].IsByRef)
9714         Flags.setByRef();
9715       if (Args[i].IsPreallocated) {
9716         Flags.setPreallocated();
9717         // Set the byval flag for CCAssignFn callbacks that don't know about
9718         // preallocated.  This way we can know how many bytes we should've
9719         // allocated and how many bytes a callee cleanup function will pop.  If
9720         // we port preallocated to more targets, we'll have to add custom
9721         // preallocated handling in the various CC lowering callbacks.
9722         Flags.setByVal();
9723       }
9724       if (Args[i].IsInAlloca) {
9725         Flags.setInAlloca();
9726         // Set the byval flag for CCAssignFn callbacks that don't know about
9727         // inalloca.  This way we can know how many bytes we should've allocated
9728         // and how many bytes a callee cleanup function will pop.  If we port
9729         // inalloca to more targets, we'll have to add custom inalloca handling
9730         // in the various CC lowering callbacks.
9731         Flags.setByVal();
9732       }
9733       Align MemAlign;
9734       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9735         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9736         Flags.setByValSize(FrameSize);
9737 
9738         // info is not there but there are cases it cannot get right.
9739         if (auto MA = Args[i].Alignment)
9740           MemAlign = *MA;
9741         else
9742           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9743       } else if (auto MA = Args[i].Alignment) {
9744         MemAlign = *MA;
9745       } else {
9746         MemAlign = OriginalAlignment;
9747       }
9748       Flags.setMemAlign(MemAlign);
9749       if (Args[i].IsNest)
9750         Flags.setNest();
9751       if (NeedsRegBlock)
9752         Flags.setInConsecutiveRegs();
9753 
9754       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9755                                                  CLI.CallConv, VT);
9756       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9757                                                         CLI.CallConv, VT);
9758       SmallVector<SDValue, 4> Parts(NumParts);
9759       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9760 
9761       if (Args[i].IsSExt)
9762         ExtendKind = ISD::SIGN_EXTEND;
9763       else if (Args[i].IsZExt)
9764         ExtendKind = ISD::ZERO_EXTEND;
9765 
9766       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9767       // for now.
9768       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9769           CanLowerReturn) {
9770         assert((CLI.RetTy == Args[i].Ty ||
9771                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9772                  CLI.RetTy->getPointerAddressSpace() ==
9773                      Args[i].Ty->getPointerAddressSpace())) &&
9774                RetTys.size() == NumValues && "unexpected use of 'returned'");
9775         // Before passing 'returned' to the target lowering code, ensure that
9776         // either the register MVT and the actual EVT are the same size or that
9777         // the return value and argument are extended in the same way; in these
9778         // cases it's safe to pass the argument register value unchanged as the
9779         // return register value (although it's at the target's option whether
9780         // to do so)
9781         // TODO: allow code generation to take advantage of partially preserved
9782         // registers rather than clobbering the entire register when the
9783         // parameter extension method is not compatible with the return
9784         // extension method
9785         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9786             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9787              CLI.RetZExt == Args[i].IsZExt))
9788           Flags.setReturned();
9789       }
9790 
9791       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9792                      CLI.CallConv, ExtendKind);
9793 
9794       for (unsigned j = 0; j != NumParts; ++j) {
9795         // if it isn't first piece, alignment must be 1
9796         // For scalable vectors the scalable part is currently handled
9797         // by individual targets, so we just use the known minimum size here.
9798         ISD::OutputArg MyFlags(
9799             Flags, Parts[j].getValueType().getSimpleVT(), VT,
9800             i < CLI.NumFixedArgs, i,
9801             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
9802         if (NumParts > 1 && j == 0)
9803           MyFlags.Flags.setSplit();
9804         else if (j != 0) {
9805           MyFlags.Flags.setOrigAlign(Align(1));
9806           if (j == NumParts - 1)
9807             MyFlags.Flags.setSplitEnd();
9808         }
9809 
9810         CLI.Outs.push_back(MyFlags);
9811         CLI.OutVals.push_back(Parts[j]);
9812       }
9813 
9814       if (NeedsRegBlock && Value == NumValues - 1)
9815         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9816     }
9817   }
9818 
9819   SmallVector<SDValue, 4> InVals;
9820   CLI.Chain = LowerCall(CLI, InVals);
9821 
9822   // Update CLI.InVals to use outside of this function.
9823   CLI.InVals = InVals;
9824 
9825   // Verify that the target's LowerCall behaved as expected.
9826   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9827          "LowerCall didn't return a valid chain!");
9828   assert((!CLI.IsTailCall || InVals.empty()) &&
9829          "LowerCall emitted a return value for a tail call!");
9830   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9831          "LowerCall didn't emit the correct number of values!");
9832 
9833   // For a tail call, the return value is merely live-out and there aren't
9834   // any nodes in the DAG representing it. Return a special value to
9835   // indicate that a tail call has been emitted and no more Instructions
9836   // should be processed in the current block.
9837   if (CLI.IsTailCall) {
9838     CLI.DAG.setRoot(CLI.Chain);
9839     return std::make_pair(SDValue(), SDValue());
9840   }
9841 
9842 #ifndef NDEBUG
9843   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9844     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9845     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9846            "LowerCall emitted a value with the wrong type!");
9847   }
9848 #endif
9849 
9850   SmallVector<SDValue, 4> ReturnValues;
9851   if (!CanLowerReturn) {
9852     // The instruction result is the result of loading from the
9853     // hidden sret parameter.
9854     SmallVector<EVT, 1> PVTs;
9855     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9856 
9857     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9858     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9859     EVT PtrVT = PVTs[0];
9860 
9861     unsigned NumValues = RetTys.size();
9862     ReturnValues.resize(NumValues);
9863     SmallVector<SDValue, 4> Chains(NumValues);
9864 
9865     // An aggregate return value cannot wrap around the address space, so
9866     // offsets to its parts don't wrap either.
9867     SDNodeFlags Flags;
9868     Flags.setNoUnsignedWrap(true);
9869 
9870     MachineFunction &MF = CLI.DAG.getMachineFunction();
9871     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9872     for (unsigned i = 0; i < NumValues; ++i) {
9873       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9874                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9875                                                         PtrVT), Flags);
9876       SDValue L = CLI.DAG.getLoad(
9877           RetTys[i], CLI.DL, CLI.Chain, Add,
9878           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9879                                             DemoteStackIdx, Offsets[i]),
9880           HiddenSRetAlign);
9881       ReturnValues[i] = L;
9882       Chains[i] = L.getValue(1);
9883     }
9884 
9885     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9886   } else {
9887     // Collect the legal value parts into potentially illegal values
9888     // that correspond to the original function's return values.
9889     Optional<ISD::NodeType> AssertOp;
9890     if (CLI.RetSExt)
9891       AssertOp = ISD::AssertSext;
9892     else if (CLI.RetZExt)
9893       AssertOp = ISD::AssertZext;
9894     unsigned CurReg = 0;
9895     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9896       EVT VT = RetTys[I];
9897       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9898                                                      CLI.CallConv, VT);
9899       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9900                                                        CLI.CallConv, VT);
9901 
9902       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9903                                               NumRegs, RegisterVT, VT, nullptr,
9904                                               CLI.CallConv, AssertOp));
9905       CurReg += NumRegs;
9906     }
9907 
9908     // For a function returning void, there is no return value. We can't create
9909     // such a node, so we just return a null return value in that case. In
9910     // that case, nothing will actually look at the value.
9911     if (ReturnValues.empty())
9912       return std::make_pair(SDValue(), CLI.Chain);
9913   }
9914 
9915   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9916                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9917   return std::make_pair(Res, CLI.Chain);
9918 }
9919 
9920 /// Places new result values for the node in Results (their number
9921 /// and types must exactly match those of the original return values of
9922 /// the node), or leaves Results empty, which indicates that the node is not
9923 /// to be custom lowered after all.
9924 void TargetLowering::LowerOperationWrapper(SDNode *N,
9925                                            SmallVectorImpl<SDValue> &Results,
9926                                            SelectionDAG &DAG) const {
9927   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9928 
9929   if (!Res.getNode())
9930     return;
9931 
9932   // If the original node has one result, take the return value from
9933   // LowerOperation as is. It might not be result number 0.
9934   if (N->getNumValues() == 1) {
9935     Results.push_back(Res);
9936     return;
9937   }
9938 
9939   // If the original node has multiple results, then the return node should
9940   // have the same number of results.
9941   assert((N->getNumValues() == Res->getNumValues()) &&
9942       "Lowering returned the wrong number of results!");
9943 
9944   // Places new result values base on N result number.
9945   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9946     Results.push_back(Res.getValue(I));
9947 }
9948 
9949 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9950   llvm_unreachable("LowerOperation not implemented for this target!");
9951 }
9952 
9953 void
9954 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9955   SDValue Op = getNonRegisterValue(V);
9956   assert((Op.getOpcode() != ISD::CopyFromReg ||
9957           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9958          "Copy from a reg to the same reg!");
9959   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9960 
9961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9962   // If this is an InlineAsm we have to match the registers required, not the
9963   // notional registers required by the type.
9964 
9965   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9966                    None); // This is not an ABI copy.
9967   SDValue Chain = DAG.getEntryNode();
9968 
9969   ISD::NodeType ExtendType = ISD::ANY_EXTEND;
9970   auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
9971   if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
9972     ExtendType = PreferredExtendIt->second;
9973   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9974   PendingExports.push_back(Chain);
9975 }
9976 
9977 #include "llvm/CodeGen/SelectionDAGISel.h"
9978 
9979 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9980 /// entry block, return true.  This includes arguments used by switches, since
9981 /// the switch may expand into multiple basic blocks.
9982 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9983   // With FastISel active, we may be splitting blocks, so force creation
9984   // of virtual registers for all non-dead arguments.
9985   if (FastISel)
9986     return A->use_empty();
9987 
9988   const BasicBlock &Entry = A->getParent()->front();
9989   for (const User *U : A->users())
9990     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9991       return false;  // Use not in entry block.
9992 
9993   return true;
9994 }
9995 
9996 using ArgCopyElisionMapTy =
9997     DenseMap<const Argument *,
9998              std::pair<const AllocaInst *, const StoreInst *>>;
9999 
10000 /// Scan the entry block of the function in FuncInfo for arguments that look
10001 /// like copies into a local alloca. Record any copied arguments in
10002 /// ArgCopyElisionCandidates.
10003 static void
10004 findArgumentCopyElisionCandidates(const DataLayout &DL,
10005                                   FunctionLoweringInfo *FuncInfo,
10006                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10007   // Record the state of every static alloca used in the entry block. Argument
10008   // allocas are all used in the entry block, so we need approximately as many
10009   // entries as we have arguments.
10010   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10011   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10012   unsigned NumArgs = FuncInfo->Fn->arg_size();
10013   StaticAllocas.reserve(NumArgs * 2);
10014 
10015   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10016     if (!V)
10017       return nullptr;
10018     V = V->stripPointerCasts();
10019     const auto *AI = dyn_cast<AllocaInst>(V);
10020     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10021       return nullptr;
10022     auto Iter = StaticAllocas.insert({AI, Unknown});
10023     return &Iter.first->second;
10024   };
10025 
10026   // Look for stores of arguments to static allocas. Look through bitcasts and
10027   // GEPs to handle type coercions, as long as the alloca is fully initialized
10028   // by the store. Any non-store use of an alloca escapes it and any subsequent
10029   // unanalyzed store might write it.
10030   // FIXME: Handle structs initialized with multiple stores.
10031   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10032     // Look for stores, and handle non-store uses conservatively.
10033     const auto *SI = dyn_cast<StoreInst>(&I);
10034     if (!SI) {
10035       // We will look through cast uses, so ignore them completely.
10036       if (I.isCast())
10037         continue;
10038       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10039       // to allocas.
10040       if (I.isDebugOrPseudoInst())
10041         continue;
10042       // This is an unknown instruction. Assume it escapes or writes to all
10043       // static alloca operands.
10044       for (const Use &U : I.operands()) {
10045         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10046           *Info = StaticAllocaInfo::Clobbered;
10047       }
10048       continue;
10049     }
10050 
10051     // If the stored value is a static alloca, mark it as escaped.
10052     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10053       *Info = StaticAllocaInfo::Clobbered;
10054 
10055     // Check if the destination is a static alloca.
10056     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10057     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10058     if (!Info)
10059       continue;
10060     const AllocaInst *AI = cast<AllocaInst>(Dst);
10061 
10062     // Skip allocas that have been initialized or clobbered.
10063     if (*Info != StaticAllocaInfo::Unknown)
10064       continue;
10065 
10066     // Check if the stored value is an argument, and that this store fully
10067     // initializes the alloca.
10068     // If the argument type has padding bits we can't directly forward a pointer
10069     // as the upper bits may contain garbage.
10070     // Don't elide copies from the same argument twice.
10071     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10072     const auto *Arg = dyn_cast<Argument>(Val);
10073     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10074         Arg->getType()->isEmptyTy() ||
10075         DL.getTypeStoreSize(Arg->getType()) !=
10076             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10077         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10078         ArgCopyElisionCandidates.count(Arg)) {
10079       *Info = StaticAllocaInfo::Clobbered;
10080       continue;
10081     }
10082 
10083     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10084                       << '\n');
10085 
10086     // Mark this alloca and store for argument copy elision.
10087     *Info = StaticAllocaInfo::Elidable;
10088     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10089 
10090     // Stop scanning if we've seen all arguments. This will happen early in -O0
10091     // builds, which is useful, because -O0 builds have large entry blocks and
10092     // many allocas.
10093     if (ArgCopyElisionCandidates.size() == NumArgs)
10094       break;
10095   }
10096 }
10097 
10098 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10099 /// ArgVal is a load from a suitable fixed stack object.
10100 static void tryToElideArgumentCopy(
10101     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10102     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10103     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10104     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10105     SDValue ArgVal, bool &ArgHasUses) {
10106   // Check if this is a load from a fixed stack object.
10107   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10108   if (!LNode)
10109     return;
10110   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10111   if (!FINode)
10112     return;
10113 
10114   // Check that the fixed stack object is the right size and alignment.
10115   // Look at the alignment that the user wrote on the alloca instead of looking
10116   // at the stack object.
10117   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10118   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10119   const AllocaInst *AI = ArgCopyIter->second.first;
10120   int FixedIndex = FINode->getIndex();
10121   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10122   int OldIndex = AllocaIndex;
10123   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10124   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10125     LLVM_DEBUG(
10126         dbgs() << "  argument copy elision failed due to bad fixed stack "
10127                   "object size\n");
10128     return;
10129   }
10130   Align RequiredAlignment = AI->getAlign();
10131   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10132     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10133                          "greater than stack argument alignment ("
10134                       << DebugStr(RequiredAlignment) << " vs "
10135                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10136     return;
10137   }
10138 
10139   // Perform the elision. Delete the old stack object and replace its only use
10140   // in the variable info map. Mark the stack object as mutable.
10141   LLVM_DEBUG({
10142     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10143            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10144            << '\n';
10145   });
10146   MFI.RemoveStackObject(OldIndex);
10147   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10148   AllocaIndex = FixedIndex;
10149   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10150   Chains.push_back(ArgVal.getValue(1));
10151 
10152   // Avoid emitting code for the store implementing the copy.
10153   const StoreInst *SI = ArgCopyIter->second.second;
10154   ElidedArgCopyInstrs.insert(SI);
10155 
10156   // Check for uses of the argument again so that we can avoid exporting ArgVal
10157   // if it is't used by anything other than the store.
10158   for (const Value *U : Arg.users()) {
10159     if (U != SI) {
10160       ArgHasUses = true;
10161       break;
10162     }
10163   }
10164 }
10165 
10166 void SelectionDAGISel::LowerArguments(const Function &F) {
10167   SelectionDAG &DAG = SDB->DAG;
10168   SDLoc dl = SDB->getCurSDLoc();
10169   const DataLayout &DL = DAG.getDataLayout();
10170   SmallVector<ISD::InputArg, 16> Ins;
10171 
10172   // In Naked functions we aren't going to save any registers.
10173   if (F.hasFnAttribute(Attribute::Naked))
10174     return;
10175 
10176   if (!FuncInfo->CanLowerReturn) {
10177     // Put in an sret pointer parameter before all the other parameters.
10178     SmallVector<EVT, 1> ValueVTs;
10179     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10180                     F.getReturnType()->getPointerTo(
10181                         DAG.getDataLayout().getAllocaAddrSpace()),
10182                     ValueVTs);
10183 
10184     // NOTE: Assuming that a pointer will never break down to more than one VT
10185     // or one register.
10186     ISD::ArgFlagsTy Flags;
10187     Flags.setSRet();
10188     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10189     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10190                          ISD::InputArg::NoArgIndex, 0);
10191     Ins.push_back(RetArg);
10192   }
10193 
10194   // Look for stores of arguments to static allocas. Mark such arguments with a
10195   // flag to ask the target to give us the memory location of that argument if
10196   // available.
10197   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10198   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10199                                     ArgCopyElisionCandidates);
10200 
10201   // Set up the incoming argument description vector.
10202   for (const Argument &Arg : F.args()) {
10203     unsigned ArgNo = Arg.getArgNo();
10204     SmallVector<EVT, 4> ValueVTs;
10205     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10206     bool isArgValueUsed = !Arg.use_empty();
10207     unsigned PartBase = 0;
10208     Type *FinalType = Arg.getType();
10209     if (Arg.hasAttribute(Attribute::ByVal))
10210       FinalType = Arg.getParamByValType();
10211     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10212         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10213     for (unsigned Value = 0, NumValues = ValueVTs.size();
10214          Value != NumValues; ++Value) {
10215       EVT VT = ValueVTs[Value];
10216       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10217       ISD::ArgFlagsTy Flags;
10218 
10219 
10220       if (Arg.getType()->isPointerTy()) {
10221         Flags.setPointer();
10222         Flags.setPointerAddrSpace(
10223             cast<PointerType>(Arg.getType())->getAddressSpace());
10224       }
10225       if (Arg.hasAttribute(Attribute::ZExt))
10226         Flags.setZExt();
10227       if (Arg.hasAttribute(Attribute::SExt))
10228         Flags.setSExt();
10229       if (Arg.hasAttribute(Attribute::InReg)) {
10230         // If we are using vectorcall calling convention, a structure that is
10231         // passed InReg - is surely an HVA
10232         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10233             isa<StructType>(Arg.getType())) {
10234           // The first value of a structure is marked
10235           if (0 == Value)
10236             Flags.setHvaStart();
10237           Flags.setHva();
10238         }
10239         // Set InReg Flag
10240         Flags.setInReg();
10241       }
10242       if (Arg.hasAttribute(Attribute::StructRet))
10243         Flags.setSRet();
10244       if (Arg.hasAttribute(Attribute::SwiftSelf))
10245         Flags.setSwiftSelf();
10246       if (Arg.hasAttribute(Attribute::SwiftAsync))
10247         Flags.setSwiftAsync();
10248       if (Arg.hasAttribute(Attribute::SwiftError))
10249         Flags.setSwiftError();
10250       if (Arg.hasAttribute(Attribute::ByVal))
10251         Flags.setByVal();
10252       if (Arg.hasAttribute(Attribute::ByRef))
10253         Flags.setByRef();
10254       if (Arg.hasAttribute(Attribute::InAlloca)) {
10255         Flags.setInAlloca();
10256         // Set the byval flag for CCAssignFn callbacks that don't know about
10257         // inalloca.  This way we can know how many bytes we should've allocated
10258         // and how many bytes a callee cleanup function will pop.  If we port
10259         // inalloca to more targets, we'll have to add custom inalloca handling
10260         // in the various CC lowering callbacks.
10261         Flags.setByVal();
10262       }
10263       if (Arg.hasAttribute(Attribute::Preallocated)) {
10264         Flags.setPreallocated();
10265         // Set the byval flag for CCAssignFn callbacks that don't know about
10266         // preallocated.  This way we can know how many bytes we should've
10267         // allocated and how many bytes a callee cleanup function will pop.  If
10268         // we port preallocated to more targets, we'll have to add custom
10269         // preallocated handling in the various CC lowering callbacks.
10270         Flags.setByVal();
10271       }
10272 
10273       // Certain targets (such as MIPS), may have a different ABI alignment
10274       // for a type depending on the context. Give the target a chance to
10275       // specify the alignment it wants.
10276       const Align OriginalAlignment(
10277           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10278       Flags.setOrigAlign(OriginalAlignment);
10279 
10280       Align MemAlign;
10281       Type *ArgMemTy = nullptr;
10282       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10283           Flags.isByRef()) {
10284         if (!ArgMemTy)
10285           ArgMemTy = Arg.getPointeeInMemoryValueType();
10286 
10287         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10288 
10289         // For in-memory arguments, size and alignment should be passed from FE.
10290         // BE will guess if this info is not there but there are cases it cannot
10291         // get right.
10292         if (auto ParamAlign = Arg.getParamStackAlign())
10293           MemAlign = *ParamAlign;
10294         else if ((ParamAlign = Arg.getParamAlign()))
10295           MemAlign = *ParamAlign;
10296         else
10297           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10298         if (Flags.isByRef())
10299           Flags.setByRefSize(MemSize);
10300         else
10301           Flags.setByValSize(MemSize);
10302       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10303         MemAlign = *ParamAlign;
10304       } else {
10305         MemAlign = OriginalAlignment;
10306       }
10307       Flags.setMemAlign(MemAlign);
10308 
10309       if (Arg.hasAttribute(Attribute::Nest))
10310         Flags.setNest();
10311       if (NeedsRegBlock)
10312         Flags.setInConsecutiveRegs();
10313       if (ArgCopyElisionCandidates.count(&Arg))
10314         Flags.setCopyElisionCandidate();
10315       if (Arg.hasAttribute(Attribute::Returned))
10316         Flags.setReturned();
10317 
10318       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10319           *CurDAG->getContext(), F.getCallingConv(), VT);
10320       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10321           *CurDAG->getContext(), F.getCallingConv(), VT);
10322       for (unsigned i = 0; i != NumRegs; ++i) {
10323         // For scalable vectors, use the minimum size; individual targets
10324         // are responsible for handling scalable vector arguments and
10325         // return values.
10326         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10327                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10328         if (NumRegs > 1 && i == 0)
10329           MyFlags.Flags.setSplit();
10330         // if it isn't first piece, alignment must be 1
10331         else if (i > 0) {
10332           MyFlags.Flags.setOrigAlign(Align(1));
10333           if (i == NumRegs - 1)
10334             MyFlags.Flags.setSplitEnd();
10335         }
10336         Ins.push_back(MyFlags);
10337       }
10338       if (NeedsRegBlock && Value == NumValues - 1)
10339         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10340       PartBase += VT.getStoreSize().getKnownMinSize();
10341     }
10342   }
10343 
10344   // Call the target to set up the argument values.
10345   SmallVector<SDValue, 8> InVals;
10346   SDValue NewRoot = TLI->LowerFormalArguments(
10347       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10348 
10349   // Verify that the target's LowerFormalArguments behaved as expected.
10350   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10351          "LowerFormalArguments didn't return a valid chain!");
10352   assert(InVals.size() == Ins.size() &&
10353          "LowerFormalArguments didn't emit the correct number of values!");
10354   LLVM_DEBUG({
10355     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10356       assert(InVals[i].getNode() &&
10357              "LowerFormalArguments emitted a null value!");
10358       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10359              "LowerFormalArguments emitted a value with the wrong type!");
10360     }
10361   });
10362 
10363   // Update the DAG with the new chain value resulting from argument lowering.
10364   DAG.setRoot(NewRoot);
10365 
10366   // Set up the argument values.
10367   unsigned i = 0;
10368   if (!FuncInfo->CanLowerReturn) {
10369     // Create a virtual register for the sret pointer, and put in a copy
10370     // from the sret argument into it.
10371     SmallVector<EVT, 1> ValueVTs;
10372     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10373                     F.getReturnType()->getPointerTo(
10374                         DAG.getDataLayout().getAllocaAddrSpace()),
10375                     ValueVTs);
10376     MVT VT = ValueVTs[0].getSimpleVT();
10377     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10378     Optional<ISD::NodeType> AssertOp = None;
10379     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10380                                         nullptr, F.getCallingConv(), AssertOp);
10381 
10382     MachineFunction& MF = SDB->DAG.getMachineFunction();
10383     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10384     Register SRetReg =
10385         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10386     FuncInfo->DemoteRegister = SRetReg;
10387     NewRoot =
10388         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10389     DAG.setRoot(NewRoot);
10390 
10391     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10392     ++i;
10393   }
10394 
10395   SmallVector<SDValue, 4> Chains;
10396   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10397   for (const Argument &Arg : F.args()) {
10398     SmallVector<SDValue, 4> ArgValues;
10399     SmallVector<EVT, 4> ValueVTs;
10400     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10401     unsigned NumValues = ValueVTs.size();
10402     if (NumValues == 0)
10403       continue;
10404 
10405     bool ArgHasUses = !Arg.use_empty();
10406 
10407     // Elide the copying store if the target loaded this argument from a
10408     // suitable fixed stack object.
10409     if (Ins[i].Flags.isCopyElisionCandidate()) {
10410       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10411                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10412                              InVals[i], ArgHasUses);
10413     }
10414 
10415     // If this argument is unused then remember its value. It is used to generate
10416     // debugging information.
10417     bool isSwiftErrorArg =
10418         TLI->supportSwiftError() &&
10419         Arg.hasAttribute(Attribute::SwiftError);
10420     if (!ArgHasUses && !isSwiftErrorArg) {
10421       SDB->setUnusedArgValue(&Arg, InVals[i]);
10422 
10423       // Also remember any frame index for use in FastISel.
10424       if (FrameIndexSDNode *FI =
10425           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10426         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10427     }
10428 
10429     for (unsigned Val = 0; Val != NumValues; ++Val) {
10430       EVT VT = ValueVTs[Val];
10431       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10432                                                       F.getCallingConv(), VT);
10433       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10434           *CurDAG->getContext(), F.getCallingConv(), VT);
10435 
10436       // Even an apparent 'unused' swifterror argument needs to be returned. So
10437       // we do generate a copy for it that can be used on return from the
10438       // function.
10439       if (ArgHasUses || isSwiftErrorArg) {
10440         Optional<ISD::NodeType> AssertOp;
10441         if (Arg.hasAttribute(Attribute::SExt))
10442           AssertOp = ISD::AssertSext;
10443         else if (Arg.hasAttribute(Attribute::ZExt))
10444           AssertOp = ISD::AssertZext;
10445 
10446         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10447                                              PartVT, VT, nullptr,
10448                                              F.getCallingConv(), AssertOp));
10449       }
10450 
10451       i += NumParts;
10452     }
10453 
10454     // We don't need to do anything else for unused arguments.
10455     if (ArgValues.empty())
10456       continue;
10457 
10458     // Note down frame index.
10459     if (FrameIndexSDNode *FI =
10460         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10461       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10462 
10463     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10464                                      SDB->getCurSDLoc());
10465 
10466     SDB->setValue(&Arg, Res);
10467     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10468       // We want to associate the argument with the frame index, among
10469       // involved operands, that correspond to the lowest address. The
10470       // getCopyFromParts function, called earlier, is swapping the order of
10471       // the operands to BUILD_PAIR depending on endianness. The result of
10472       // that swapping is that the least significant bits of the argument will
10473       // be in the first operand of the BUILD_PAIR node, and the most
10474       // significant bits will be in the second operand.
10475       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10476       if (LoadSDNode *LNode =
10477           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10478         if (FrameIndexSDNode *FI =
10479             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10480           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10481     }
10482 
10483     // Analyses past this point are naive and don't expect an assertion.
10484     if (Res.getOpcode() == ISD::AssertZext)
10485       Res = Res.getOperand(0);
10486 
10487     // Update the SwiftErrorVRegDefMap.
10488     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10489       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10490       if (Register::isVirtualRegister(Reg))
10491         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10492                                    Reg);
10493     }
10494 
10495     // If this argument is live outside of the entry block, insert a copy from
10496     // wherever we got it to the vreg that other BB's will reference it as.
10497     if (Res.getOpcode() == ISD::CopyFromReg) {
10498       // If we can, though, try to skip creating an unnecessary vreg.
10499       // FIXME: This isn't very clean... it would be nice to make this more
10500       // general.
10501       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10502       if (Register::isVirtualRegister(Reg)) {
10503         FuncInfo->ValueMap[&Arg] = Reg;
10504         continue;
10505       }
10506     }
10507     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10508       FuncInfo->InitializeRegForValue(&Arg);
10509       SDB->CopyToExportRegsIfNeeded(&Arg);
10510     }
10511   }
10512 
10513   if (!Chains.empty()) {
10514     Chains.push_back(NewRoot);
10515     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10516   }
10517 
10518   DAG.setRoot(NewRoot);
10519 
10520   assert(i == InVals.size() && "Argument register count mismatch!");
10521 
10522   // If any argument copy elisions occurred and we have debug info, update the
10523   // stale frame indices used in the dbg.declare variable info table.
10524   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10525   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10526     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10527       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10528       if (I != ArgCopyElisionFrameIndexMap.end())
10529         VI.Slot = I->second;
10530     }
10531   }
10532 
10533   // Finally, if the target has anything special to do, allow it to do so.
10534   emitFunctionEntryCode();
10535 }
10536 
10537 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10538 /// ensure constants are generated when needed.  Remember the virtual registers
10539 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10540 /// directly add them, because expansion might result in multiple MBB's for one
10541 /// BB.  As such, the start of the BB might correspond to a different MBB than
10542 /// the end.
10543 void
10544 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10545   const Instruction *TI = LLVMBB->getTerminator();
10546 
10547   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10548 
10549   // Check PHI nodes in successors that expect a value to be available from this
10550   // block.
10551   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10552     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10553     if (!isa<PHINode>(SuccBB->begin())) continue;
10554     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10555 
10556     // If this terminator has multiple identical successors (common for
10557     // switches), only handle each succ once.
10558     if (!SuccsHandled.insert(SuccMBB).second)
10559       continue;
10560 
10561     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10562 
10563     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10564     // nodes and Machine PHI nodes, but the incoming operands have not been
10565     // emitted yet.
10566     for (const PHINode &PN : SuccBB->phis()) {
10567       // Ignore dead phi's.
10568       if (PN.use_empty())
10569         continue;
10570 
10571       // Skip empty types
10572       if (PN.getType()->isEmptyTy())
10573         continue;
10574 
10575       unsigned Reg;
10576       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10577 
10578       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10579         unsigned &RegOut = ConstantsOut[C];
10580         if (RegOut == 0) {
10581           RegOut = FuncInfo.CreateRegs(C);
10582           CopyValueToVirtualRegister(C, RegOut);
10583         }
10584         Reg = RegOut;
10585       } else {
10586         DenseMap<const Value *, Register>::iterator I =
10587           FuncInfo.ValueMap.find(PHIOp);
10588         if (I != FuncInfo.ValueMap.end())
10589           Reg = I->second;
10590         else {
10591           assert(isa<AllocaInst>(PHIOp) &&
10592                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10593                  "Didn't codegen value into a register!??");
10594           Reg = FuncInfo.CreateRegs(PHIOp);
10595           CopyValueToVirtualRegister(PHIOp, Reg);
10596         }
10597       }
10598 
10599       // Remember that this register needs to added to the machine PHI node as
10600       // the input for this MBB.
10601       SmallVector<EVT, 4> ValueVTs;
10602       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10603       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10604       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10605         EVT VT = ValueVTs[vti];
10606         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10607         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10608           FuncInfo.PHINodesToUpdate.push_back(
10609               std::make_pair(&*MBBI++, Reg + i));
10610         Reg += NumRegisters;
10611       }
10612     }
10613   }
10614 
10615   ConstantsOut.clear();
10616 }
10617 
10618 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10619   MachineFunction::iterator I(MBB);
10620   if (++I == FuncInfo.MF->end())
10621     return nullptr;
10622   return &*I;
10623 }
10624 
10625 /// During lowering new call nodes can be created (such as memset, etc.).
10626 /// Those will become new roots of the current DAG, but complications arise
10627 /// when they are tail calls. In such cases, the call lowering will update
10628 /// the root, but the builder still needs to know that a tail call has been
10629 /// lowered in order to avoid generating an additional return.
10630 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10631   // If the node is null, we do have a tail call.
10632   if (MaybeTC.getNode() != nullptr)
10633     DAG.setRoot(MaybeTC);
10634   else
10635     HasTailCall = true;
10636 }
10637 
10638 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10639                                         MachineBasicBlock *SwitchMBB,
10640                                         MachineBasicBlock *DefaultMBB) {
10641   MachineFunction *CurMF = FuncInfo.MF;
10642   MachineBasicBlock *NextMBB = nullptr;
10643   MachineFunction::iterator BBI(W.MBB);
10644   if (++BBI != FuncInfo.MF->end())
10645     NextMBB = &*BBI;
10646 
10647   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10648 
10649   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10650 
10651   if (Size == 2 && W.MBB == SwitchMBB) {
10652     // If any two of the cases has the same destination, and if one value
10653     // is the same as the other, but has one bit unset that the other has set,
10654     // use bit manipulation to do two compares at once.  For example:
10655     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10656     // TODO: This could be extended to merge any 2 cases in switches with 3
10657     // cases.
10658     // TODO: Handle cases where W.CaseBB != SwitchBB.
10659     CaseCluster &Small = *W.FirstCluster;
10660     CaseCluster &Big = *W.LastCluster;
10661 
10662     if (Small.Low == Small.High && Big.Low == Big.High &&
10663         Small.MBB == Big.MBB) {
10664       const APInt &SmallValue = Small.Low->getValue();
10665       const APInt &BigValue = Big.Low->getValue();
10666 
10667       // Check that there is only one bit different.
10668       APInt CommonBit = BigValue ^ SmallValue;
10669       if (CommonBit.isPowerOf2()) {
10670         SDValue CondLHS = getValue(Cond);
10671         EVT VT = CondLHS.getValueType();
10672         SDLoc DL = getCurSDLoc();
10673 
10674         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10675                                  DAG.getConstant(CommonBit, DL, VT));
10676         SDValue Cond = DAG.getSetCC(
10677             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10678             ISD::SETEQ);
10679 
10680         // Update successor info.
10681         // Both Small and Big will jump to Small.BB, so we sum up the
10682         // probabilities.
10683         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10684         if (BPI)
10685           addSuccessorWithProb(
10686               SwitchMBB, DefaultMBB,
10687               // The default destination is the first successor in IR.
10688               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10689         else
10690           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10691 
10692         // Insert the true branch.
10693         SDValue BrCond =
10694             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10695                         DAG.getBasicBlock(Small.MBB));
10696         // Insert the false branch.
10697         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10698                              DAG.getBasicBlock(DefaultMBB));
10699 
10700         DAG.setRoot(BrCond);
10701         return;
10702       }
10703     }
10704   }
10705 
10706   if (TM.getOptLevel() != CodeGenOpt::None) {
10707     // Here, we order cases by probability so the most likely case will be
10708     // checked first. However, two clusters can have the same probability in
10709     // which case their relative ordering is non-deterministic. So we use Low
10710     // as a tie-breaker as clusters are guaranteed to never overlap.
10711     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10712                [](const CaseCluster &a, const CaseCluster &b) {
10713       return a.Prob != b.Prob ?
10714              a.Prob > b.Prob :
10715              a.Low->getValue().slt(b.Low->getValue());
10716     });
10717 
10718     // Rearrange the case blocks so that the last one falls through if possible
10719     // without changing the order of probabilities.
10720     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10721       --I;
10722       if (I->Prob > W.LastCluster->Prob)
10723         break;
10724       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10725         std::swap(*I, *W.LastCluster);
10726         break;
10727       }
10728     }
10729   }
10730 
10731   // Compute total probability.
10732   BranchProbability DefaultProb = W.DefaultProb;
10733   BranchProbability UnhandledProbs = DefaultProb;
10734   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10735     UnhandledProbs += I->Prob;
10736 
10737   MachineBasicBlock *CurMBB = W.MBB;
10738   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10739     bool FallthroughUnreachable = false;
10740     MachineBasicBlock *Fallthrough;
10741     if (I == W.LastCluster) {
10742       // For the last cluster, fall through to the default destination.
10743       Fallthrough = DefaultMBB;
10744       FallthroughUnreachable = isa<UnreachableInst>(
10745           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10746     } else {
10747       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10748       CurMF->insert(BBI, Fallthrough);
10749       // Put Cond in a virtual register to make it available from the new blocks.
10750       ExportFromCurrentBlock(Cond);
10751     }
10752     UnhandledProbs -= I->Prob;
10753 
10754     switch (I->Kind) {
10755       case CC_JumpTable: {
10756         // FIXME: Optimize away range check based on pivot comparisons.
10757         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10758         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10759 
10760         // The jump block hasn't been inserted yet; insert it here.
10761         MachineBasicBlock *JumpMBB = JT->MBB;
10762         CurMF->insert(BBI, JumpMBB);
10763 
10764         auto JumpProb = I->Prob;
10765         auto FallthroughProb = UnhandledProbs;
10766 
10767         // If the default statement is a target of the jump table, we evenly
10768         // distribute the default probability to successors of CurMBB. Also
10769         // update the probability on the edge from JumpMBB to Fallthrough.
10770         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10771                                               SE = JumpMBB->succ_end();
10772              SI != SE; ++SI) {
10773           if (*SI == DefaultMBB) {
10774             JumpProb += DefaultProb / 2;
10775             FallthroughProb -= DefaultProb / 2;
10776             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10777             JumpMBB->normalizeSuccProbs();
10778             break;
10779           }
10780         }
10781 
10782         if (FallthroughUnreachable)
10783           JTH->FallthroughUnreachable = true;
10784 
10785         if (!JTH->FallthroughUnreachable)
10786           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10787         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10788         CurMBB->normalizeSuccProbs();
10789 
10790         // The jump table header will be inserted in our current block, do the
10791         // range check, and fall through to our fallthrough block.
10792         JTH->HeaderBB = CurMBB;
10793         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10794 
10795         // If we're in the right place, emit the jump table header right now.
10796         if (CurMBB == SwitchMBB) {
10797           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10798           JTH->Emitted = true;
10799         }
10800         break;
10801       }
10802       case CC_BitTests: {
10803         // FIXME: Optimize away range check based on pivot comparisons.
10804         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10805 
10806         // The bit test blocks haven't been inserted yet; insert them here.
10807         for (BitTestCase &BTC : BTB->Cases)
10808           CurMF->insert(BBI, BTC.ThisBB);
10809 
10810         // Fill in fields of the BitTestBlock.
10811         BTB->Parent = CurMBB;
10812         BTB->Default = Fallthrough;
10813 
10814         BTB->DefaultProb = UnhandledProbs;
10815         // If the cases in bit test don't form a contiguous range, we evenly
10816         // distribute the probability on the edge to Fallthrough to two
10817         // successors of CurMBB.
10818         if (!BTB->ContiguousRange) {
10819           BTB->Prob += DefaultProb / 2;
10820           BTB->DefaultProb -= DefaultProb / 2;
10821         }
10822 
10823         if (FallthroughUnreachable)
10824           BTB->FallthroughUnreachable = true;
10825 
10826         // If we're in the right place, emit the bit test header right now.
10827         if (CurMBB == SwitchMBB) {
10828           visitBitTestHeader(*BTB, SwitchMBB);
10829           BTB->Emitted = true;
10830         }
10831         break;
10832       }
10833       case CC_Range: {
10834         const Value *RHS, *LHS, *MHS;
10835         ISD::CondCode CC;
10836         if (I->Low == I->High) {
10837           // Check Cond == I->Low.
10838           CC = ISD::SETEQ;
10839           LHS = Cond;
10840           RHS=I->Low;
10841           MHS = nullptr;
10842         } else {
10843           // Check I->Low <= Cond <= I->High.
10844           CC = ISD::SETLE;
10845           LHS = I->Low;
10846           MHS = Cond;
10847           RHS = I->High;
10848         }
10849 
10850         // If Fallthrough is unreachable, fold away the comparison.
10851         if (FallthroughUnreachable)
10852           CC = ISD::SETTRUE;
10853 
10854         // The false probability is the sum of all unhandled cases.
10855         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10856                      getCurSDLoc(), I->Prob, UnhandledProbs);
10857 
10858         if (CurMBB == SwitchMBB)
10859           visitSwitchCase(CB, SwitchMBB);
10860         else
10861           SL->SwitchCases.push_back(CB);
10862 
10863         break;
10864       }
10865     }
10866     CurMBB = Fallthrough;
10867   }
10868 }
10869 
10870 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10871                                               CaseClusterIt First,
10872                                               CaseClusterIt Last) {
10873   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10874     if (X.Prob != CC.Prob)
10875       return X.Prob > CC.Prob;
10876 
10877     // Ties are broken by comparing the case value.
10878     return X.Low->getValue().slt(CC.Low->getValue());
10879   });
10880 }
10881 
10882 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10883                                         const SwitchWorkListItem &W,
10884                                         Value *Cond,
10885                                         MachineBasicBlock *SwitchMBB) {
10886   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10887          "Clusters not sorted?");
10888 
10889   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10890 
10891   // Balance the tree based on branch probabilities to create a near-optimal (in
10892   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10893   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10894   CaseClusterIt LastLeft = W.FirstCluster;
10895   CaseClusterIt FirstRight = W.LastCluster;
10896   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10897   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10898 
10899   // Move LastLeft and FirstRight towards each other from opposite directions to
10900   // find a partitioning of the clusters which balances the probability on both
10901   // sides. If LeftProb and RightProb are equal, alternate which side is
10902   // taken to ensure 0-probability nodes are distributed evenly.
10903   unsigned I = 0;
10904   while (LastLeft + 1 < FirstRight) {
10905     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10906       LeftProb += (++LastLeft)->Prob;
10907     else
10908       RightProb += (--FirstRight)->Prob;
10909     I++;
10910   }
10911 
10912   while (true) {
10913     // Our binary search tree differs from a typical BST in that ours can have up
10914     // to three values in each leaf. The pivot selection above doesn't take that
10915     // into account, which means the tree might require more nodes and be less
10916     // efficient. We compensate for this here.
10917 
10918     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10919     unsigned NumRight = W.LastCluster - FirstRight + 1;
10920 
10921     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10922       // If one side has less than 3 clusters, and the other has more than 3,
10923       // consider taking a cluster from the other side.
10924 
10925       if (NumLeft < NumRight) {
10926         // Consider moving the first cluster on the right to the left side.
10927         CaseCluster &CC = *FirstRight;
10928         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10929         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10930         if (LeftSideRank <= RightSideRank) {
10931           // Moving the cluster to the left does not demote it.
10932           ++LastLeft;
10933           ++FirstRight;
10934           continue;
10935         }
10936       } else {
10937         assert(NumRight < NumLeft);
10938         // Consider moving the last element on the left to the right side.
10939         CaseCluster &CC = *LastLeft;
10940         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10941         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10942         if (RightSideRank <= LeftSideRank) {
10943           // Moving the cluster to the right does not demot it.
10944           --LastLeft;
10945           --FirstRight;
10946           continue;
10947         }
10948       }
10949     }
10950     break;
10951   }
10952 
10953   assert(LastLeft + 1 == FirstRight);
10954   assert(LastLeft >= W.FirstCluster);
10955   assert(FirstRight <= W.LastCluster);
10956 
10957   // Use the first element on the right as pivot since we will make less-than
10958   // comparisons against it.
10959   CaseClusterIt PivotCluster = FirstRight;
10960   assert(PivotCluster > W.FirstCluster);
10961   assert(PivotCluster <= W.LastCluster);
10962 
10963   CaseClusterIt FirstLeft = W.FirstCluster;
10964   CaseClusterIt LastRight = W.LastCluster;
10965 
10966   const ConstantInt *Pivot = PivotCluster->Low;
10967 
10968   // New blocks will be inserted immediately after the current one.
10969   MachineFunction::iterator BBI(W.MBB);
10970   ++BBI;
10971 
10972   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10973   // we can branch to its destination directly if it's squeezed exactly in
10974   // between the known lower bound and Pivot - 1.
10975   MachineBasicBlock *LeftMBB;
10976   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10977       FirstLeft->Low == W.GE &&
10978       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10979     LeftMBB = FirstLeft->MBB;
10980   } else {
10981     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10982     FuncInfo.MF->insert(BBI, LeftMBB);
10983     WorkList.push_back(
10984         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10985     // Put Cond in a virtual register to make it available from the new blocks.
10986     ExportFromCurrentBlock(Cond);
10987   }
10988 
10989   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10990   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10991   // directly if RHS.High equals the current upper bound.
10992   MachineBasicBlock *RightMBB;
10993   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10994       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10995     RightMBB = FirstRight->MBB;
10996   } else {
10997     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10998     FuncInfo.MF->insert(BBI, RightMBB);
10999     WorkList.push_back(
11000         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11001     // Put Cond in a virtual register to make it available from the new blocks.
11002     ExportFromCurrentBlock(Cond);
11003   }
11004 
11005   // Create the CaseBlock record that will be used to lower the branch.
11006   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11007                getCurSDLoc(), LeftProb, RightProb);
11008 
11009   if (W.MBB == SwitchMBB)
11010     visitSwitchCase(CB, SwitchMBB);
11011   else
11012     SL->SwitchCases.push_back(CB);
11013 }
11014 
11015 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11016 // from the swith statement.
11017 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11018                                             BranchProbability PeeledCaseProb) {
11019   if (PeeledCaseProb == BranchProbability::getOne())
11020     return BranchProbability::getZero();
11021   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11022 
11023   uint32_t Numerator = CaseProb.getNumerator();
11024   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11025   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11026 }
11027 
11028 // Try to peel the top probability case if it exceeds the threshold.
11029 // Return current MachineBasicBlock for the switch statement if the peeling
11030 // does not occur.
11031 // If the peeling is performed, return the newly created MachineBasicBlock
11032 // for the peeled switch statement. Also update Clusters to remove the peeled
11033 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11034 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11035     const SwitchInst &SI, CaseClusterVector &Clusters,
11036     BranchProbability &PeeledCaseProb) {
11037   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11038   // Don't perform if there is only one cluster or optimizing for size.
11039   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11040       TM.getOptLevel() == CodeGenOpt::None ||
11041       SwitchMBB->getParent()->getFunction().hasMinSize())
11042     return SwitchMBB;
11043 
11044   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11045   unsigned PeeledCaseIndex = 0;
11046   bool SwitchPeeled = false;
11047   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11048     CaseCluster &CC = Clusters[Index];
11049     if (CC.Prob < TopCaseProb)
11050       continue;
11051     TopCaseProb = CC.Prob;
11052     PeeledCaseIndex = Index;
11053     SwitchPeeled = true;
11054   }
11055   if (!SwitchPeeled)
11056     return SwitchMBB;
11057 
11058   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11059                     << TopCaseProb << "\n");
11060 
11061   // Record the MBB for the peeled switch statement.
11062   MachineFunction::iterator BBI(SwitchMBB);
11063   ++BBI;
11064   MachineBasicBlock *PeeledSwitchMBB =
11065       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11066   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11067 
11068   ExportFromCurrentBlock(SI.getCondition());
11069   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11070   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11071                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11072   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11073 
11074   Clusters.erase(PeeledCaseIt);
11075   for (CaseCluster &CC : Clusters) {
11076     LLVM_DEBUG(
11077         dbgs() << "Scale the probablity for one cluster, before scaling: "
11078                << CC.Prob << "\n");
11079     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11080     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11081   }
11082   PeeledCaseProb = TopCaseProb;
11083   return PeeledSwitchMBB;
11084 }
11085 
11086 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11087   // Extract cases from the switch.
11088   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11089   CaseClusterVector Clusters;
11090   Clusters.reserve(SI.getNumCases());
11091   for (auto I : SI.cases()) {
11092     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11093     const ConstantInt *CaseVal = I.getCaseValue();
11094     BranchProbability Prob =
11095         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11096             : BranchProbability(1, SI.getNumCases() + 1);
11097     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11098   }
11099 
11100   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11101 
11102   // Cluster adjacent cases with the same destination. We do this at all
11103   // optimization levels because it's cheap to do and will make codegen faster
11104   // if there are many clusters.
11105   sortAndRangeify(Clusters);
11106 
11107   // The branch probablity of the peeled case.
11108   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11109   MachineBasicBlock *PeeledSwitchMBB =
11110       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11111 
11112   // If there is only the default destination, jump there directly.
11113   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11114   if (Clusters.empty()) {
11115     assert(PeeledSwitchMBB == SwitchMBB);
11116     SwitchMBB->addSuccessor(DefaultMBB);
11117     if (DefaultMBB != NextBlock(SwitchMBB)) {
11118       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11119                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11120     }
11121     return;
11122   }
11123 
11124   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11125   SL->findBitTestClusters(Clusters, &SI);
11126 
11127   LLVM_DEBUG({
11128     dbgs() << "Case clusters: ";
11129     for (const CaseCluster &C : Clusters) {
11130       if (C.Kind == CC_JumpTable)
11131         dbgs() << "JT:";
11132       if (C.Kind == CC_BitTests)
11133         dbgs() << "BT:";
11134 
11135       C.Low->getValue().print(dbgs(), true);
11136       if (C.Low != C.High) {
11137         dbgs() << '-';
11138         C.High->getValue().print(dbgs(), true);
11139       }
11140       dbgs() << ' ';
11141     }
11142     dbgs() << '\n';
11143   });
11144 
11145   assert(!Clusters.empty());
11146   SwitchWorkList WorkList;
11147   CaseClusterIt First = Clusters.begin();
11148   CaseClusterIt Last = Clusters.end() - 1;
11149   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11150   // Scale the branchprobability for DefaultMBB if the peel occurs and
11151   // DefaultMBB is not replaced.
11152   if (PeeledCaseProb != BranchProbability::getZero() &&
11153       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11154     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11155   WorkList.push_back(
11156       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11157 
11158   while (!WorkList.empty()) {
11159     SwitchWorkListItem W = WorkList.pop_back_val();
11160     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11161 
11162     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11163         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11164       // For optimized builds, lower large range as a balanced binary tree.
11165       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11166       continue;
11167     }
11168 
11169     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11170   }
11171 }
11172 
11173 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11175   auto DL = getCurSDLoc();
11176   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11177   setValue(&I, DAG.getStepVector(DL, ResultVT));
11178 }
11179 
11180 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11182   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11183 
11184   SDLoc DL = getCurSDLoc();
11185   SDValue V = getValue(I.getOperand(0));
11186   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11187 
11188   if (VT.isScalableVector()) {
11189     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11190     return;
11191   }
11192 
11193   // Use VECTOR_SHUFFLE for the fixed-length vector
11194   // to maintain existing behavior.
11195   SmallVector<int, 8> Mask;
11196   unsigned NumElts = VT.getVectorMinNumElements();
11197   for (unsigned i = 0; i != NumElts; ++i)
11198     Mask.push_back(NumElts - 1 - i);
11199 
11200   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11201 }
11202 
11203 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11204   SmallVector<EVT, 4> ValueVTs;
11205   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11206                   ValueVTs);
11207   unsigned NumValues = ValueVTs.size();
11208   if (NumValues == 0) return;
11209 
11210   SmallVector<SDValue, 4> Values(NumValues);
11211   SDValue Op = getValue(I.getOperand(0));
11212 
11213   for (unsigned i = 0; i != NumValues; ++i)
11214     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11215                             SDValue(Op.getNode(), Op.getResNo() + i));
11216 
11217   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11218                            DAG.getVTList(ValueVTs), Values));
11219 }
11220 
11221 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11222   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11223   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11224 
11225   SDLoc DL = getCurSDLoc();
11226   SDValue V1 = getValue(I.getOperand(0));
11227   SDValue V2 = getValue(I.getOperand(1));
11228   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11229 
11230   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11231   if (VT.isScalableVector()) {
11232     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11233     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11234                              DAG.getConstant(Imm, DL, IdxVT)));
11235     return;
11236   }
11237 
11238   unsigned NumElts = VT.getVectorNumElements();
11239 
11240   uint64_t Idx = (NumElts + Imm) % NumElts;
11241 
11242   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11243   SmallVector<int, 8> Mask;
11244   for (unsigned i = 0; i < NumElts; ++i)
11245     Mask.push_back(Idx + i);
11246   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11247 }
11248