xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 979274465094aac11e33901b7aa4887d9751fc55)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/MemoryLocation.h"
32 #include "llvm/Analysis/TargetLibraryInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CodeGenCommonISel.h"
36 #include "llvm/CodeGen/FunctionLoweringInfo.h"
37 #include "llvm/CodeGen/GCMetadata.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/RuntimeLibcalls.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50 #include "llvm/CodeGen/StackMaps.h"
51 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
52 #include "llvm/CodeGen/TargetFrameLowering.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetOpcodes.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/CodeGen/WinEHFuncInfo.h"
58 #include "llvm/IR/Argument.h"
59 #include "llvm/IR/Attributes.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/ConstantRange.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DebugInfoMetadata.h"
68 #include "llvm/IR/DerivedTypes.h"
69 #include "llvm/IR/DiagnosticInfo.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/GetElementPtrTypeIterator.h"
72 #include "llvm/IR/InlineAsm.h"
73 #include "llvm/IR/InstrTypes.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/Intrinsics.h"
77 #include "llvm/IR/IntrinsicsAArch64.h"
78 #include "llvm/IR/IntrinsicsWebAssembly.h"
79 #include "llvm/IR/LLVMContext.h"
80 #include "llvm/IR/Metadata.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/Operator.h"
83 #include "llvm/IR/PatternMatch.h"
84 #include "llvm/IR/Statepoint.h"
85 #include "llvm/IR/Type.h"
86 #include "llvm/IR/User.h"
87 #include "llvm/IR/Value.h"
88 #include "llvm/MC/MCContext.h"
89 #include "llvm/Support/AtomicOrdering.h"
90 #include "llvm/Support/Casting.h"
91 #include "llvm/Support/CommandLine.h"
92 #include "llvm/Support/Compiler.h"
93 #include "llvm/Support/Debug.h"
94 #include "llvm/Support/MathExtras.h"
95 #include "llvm/Support/raw_ostream.h"
96 #include "llvm/Target/TargetIntrinsicInfo.h"
97 #include "llvm/Target/TargetMachine.h"
98 #include "llvm/Target/TargetOptions.h"
99 #include "llvm/Transforms/Utils/Local.h"
100 #include <cstddef>
101 #include <iterator>
102 #include <limits>
103 #include <tuple>
104 
105 using namespace llvm;
106 using namespace PatternMatch;
107 using namespace SwitchCG;
108 
109 #define DEBUG_TYPE "isel"
110 
111 /// LimitFloatPrecision - Generate low-precision inline sequences for
112 /// some float libcalls (6, 8 or 12 bits).
113 static unsigned LimitFloatPrecision;
114 
115 static cl::opt<bool>
116     InsertAssertAlign("insert-assert-align", cl::init(true),
117                       cl::desc("Insert the experimental `assertalign` node."),
118                       cl::ReallyHidden);
119 
120 static cl::opt<unsigned, true>
121     LimitFPPrecision("limit-float-precision",
122                      cl::desc("Generate low-precision inline sequences "
123                               "for some float libcalls"),
124                      cl::location(LimitFloatPrecision), cl::Hidden,
125                      cl::init(0));
126 
127 static cl::opt<unsigned> SwitchPeelThreshold(
128     "switch-peel-threshold", cl::Hidden, cl::init(66),
129     cl::desc("Set the case probability threshold for peeling the case from a "
130              "switch statement. A value greater than 100 will void this "
131              "optimization"));
132 
133 // Limit the width of DAG chains. This is important in general to prevent
134 // DAG-based analysis from blowing up. For example, alias analysis and
135 // load clustering may not complete in reasonable time. It is difficult to
136 // recognize and avoid this situation within each individual analysis, and
137 // future analyses are likely to have the same behavior. Limiting DAG width is
138 // the safe approach and will be especially important with global DAGs.
139 //
140 // MaxParallelChains default is arbitrarily high to avoid affecting
141 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
142 // sequence over this should have been converted to llvm.memcpy by the
143 // frontend. It is easy to induce this behavior with .ll code such as:
144 // %buffer = alloca [4096 x i8]
145 // %data = load [4096 x i8]* %argPtr
146 // store [4096 x i8] %data, [4096 x i8]* %buffer
147 static const unsigned MaxParallelChains = 64;
148 
149 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
150                                       const SDValue *Parts, unsigned NumParts,
151                                       MVT PartVT, EVT ValueVT, const Value *V,
152                                       Optional<CallingConv::ID> CC);
153 
154 /// getCopyFromParts - Create a value that contains the specified legal parts
155 /// combined into the value they represent.  If the parts combine to a type
156 /// larger than ValueVT then AssertOp can be used to specify whether the extra
157 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
158 /// (ISD::AssertSext).
159 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
160                                 const SDValue *Parts, unsigned NumParts,
161                                 MVT PartVT, EVT ValueVT, const Value *V,
162                                 Optional<CallingConv::ID> CC = None,
163                                 Optional<ISD::NodeType> AssertOp = None) {
164   // Let the target assemble the parts if it wants to
165   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
166   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
167                                                    PartVT, ValueVT, CC))
168     return Val;
169 
170   if (ValueVT.isVector())
171     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
172                                   CC);
173 
174   assert(NumParts > 0 && "No parts to assemble!");
175   SDValue Val = Parts[0];
176 
177   if (NumParts > 1) {
178     // Assemble the value from multiple parts.
179     if (ValueVT.isInteger()) {
180       unsigned PartBits = PartVT.getSizeInBits();
181       unsigned ValueBits = ValueVT.getSizeInBits();
182 
183       // Assemble the power of 2 part.
184       unsigned RoundParts =
185           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
186       unsigned RoundBits = PartBits * RoundParts;
187       EVT RoundVT = RoundBits == ValueBits ?
188         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
189       SDValue Lo, Hi;
190 
191       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
192 
193       if (RoundParts > 2) {
194         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
195                               PartVT, HalfVT, V);
196         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
197                               RoundParts / 2, PartVT, HalfVT, V);
198       } else {
199         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
200         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
201       }
202 
203       if (DAG.getDataLayout().isBigEndian())
204         std::swap(Lo, Hi);
205 
206       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
207 
208       if (RoundParts < NumParts) {
209         // Assemble the trailing non-power-of-2 part.
210         unsigned OddParts = NumParts - RoundParts;
211         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
212         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
213                               OddVT, V, CC);
214 
215         // Combine the round and odd parts.
216         Lo = Val;
217         if (DAG.getDataLayout().isBigEndian())
218           std::swap(Lo, Hi);
219         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
220         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
221         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
222                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
223                                          TLI.getShiftAmountTy(
224                                              TotalVT, DAG.getDataLayout())));
225         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
226         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
227       }
228     } else if (PartVT.isFloatingPoint()) {
229       // FP split into multiple FP parts (for ppcf128)
230       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
231              "Unexpected split");
232       SDValue Lo, Hi;
233       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
234       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
235       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
236         std::swap(Lo, Hi);
237       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
238     } else {
239       // FP split into integer parts (soft fp)
240       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
241              !PartVT.isVector() && "Unexpected split");
242       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
243       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
244     }
245   }
246 
247   // There is now one part, held in Val.  Correct it to match ValueVT.
248   // PartEVT is the type of the register class that holds the value.
249   // ValueVT is the type of the inline asm operation.
250   EVT PartEVT = Val.getValueType();
251 
252   if (PartEVT == ValueVT)
253     return Val;
254 
255   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
256       ValueVT.bitsLT(PartEVT)) {
257     // For an FP value in an integer part, we need to truncate to the right
258     // width first.
259     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
260     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
261   }
262 
263   // Handle types that have the same size.
264   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
265     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
266 
267   // Handle types with different sizes.
268   if (PartEVT.isInteger() && ValueVT.isInteger()) {
269     if (ValueVT.bitsLT(PartEVT)) {
270       // For a truncate, see if we have any information to
271       // indicate whether the truncated bits will always be
272       // zero or sign-extension.
273       if (AssertOp)
274         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
275                           DAG.getValueType(ValueVT));
276       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
277     }
278     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
279   }
280 
281   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
282     // FP_ROUND's are always exact here.
283     if (ValueVT.bitsLT(Val.getValueType()))
284       return DAG.getNode(
285           ISD::FP_ROUND, DL, ValueVT, Val,
286           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
287 
288     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
289   }
290 
291   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
292   // then truncating.
293   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
294       ValueVT.bitsLT(PartEVT)) {
295     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
296     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
297   }
298 
299   report_fatal_error("Unknown mismatch in getCopyFromParts!");
300 }
301 
302 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
303                                               const Twine &ErrMsg) {
304   const Instruction *I = dyn_cast_or_null<Instruction>(V);
305   if (!V)
306     return Ctx.emitError(ErrMsg);
307 
308   const char *AsmError = ", possible invalid constraint for vector type";
309   if (const CallInst *CI = dyn_cast<CallInst>(I))
310     if (CI->isInlineAsm())
311       return Ctx.emitError(I, ErrMsg + AsmError);
312 
313   return Ctx.emitError(I, ErrMsg);
314 }
315 
316 /// getCopyFromPartsVector - Create a value that contains the specified legal
317 /// parts combined into the value they represent.  If the parts combine to a
318 /// type larger than ValueVT then AssertOp can be used to specify whether the
319 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
320 /// ValueVT (ISD::AssertSext).
321 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
322                                       const SDValue *Parts, unsigned NumParts,
323                                       MVT PartVT, EVT ValueVT, const Value *V,
324                                       Optional<CallingConv::ID> CallConv) {
325   assert(ValueVT.isVector() && "Not a vector value");
326   assert(NumParts > 0 && "No parts to assemble!");
327   const bool IsABIRegCopy = CallConv.has_value();
328 
329   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
330   SDValue Val = Parts[0];
331 
332   // Handle a multi-element vector.
333   if (NumParts > 1) {
334     EVT IntermediateVT;
335     MVT RegisterVT;
336     unsigned NumIntermediates;
337     unsigned NumRegs;
338 
339     if (IsABIRegCopy) {
340       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
341           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
342           NumIntermediates, RegisterVT);
343     } else {
344       NumRegs =
345           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
346                                      NumIntermediates, RegisterVT);
347     }
348 
349     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
350     NumParts = NumRegs; // Silence a compiler warning.
351     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
352     assert(RegisterVT.getSizeInBits() ==
353            Parts[0].getSimpleValueType().getSizeInBits() &&
354            "Part type sizes don't match!");
355 
356     // Assemble the parts into intermediate operands.
357     SmallVector<SDValue, 8> Ops(NumIntermediates);
358     if (NumIntermediates == NumParts) {
359       // If the register was not expanded, truncate or copy the value,
360       // as appropriate.
361       for (unsigned i = 0; i != NumParts; ++i)
362         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
363                                   PartVT, IntermediateVT, V, CallConv);
364     } else if (NumParts > 0) {
365       // If the intermediate type was expanded, build the intermediate
366       // operands from the parts.
367       assert(NumParts % NumIntermediates == 0 &&
368              "Must expand into a divisible number of parts!");
369       unsigned Factor = NumParts / NumIntermediates;
370       for (unsigned i = 0; i != NumIntermediates; ++i)
371         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
372                                   PartVT, IntermediateVT, V, CallConv);
373     }
374 
375     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
376     // intermediate operands.
377     EVT BuiltVectorTy =
378         IntermediateVT.isVector()
379             ? EVT::getVectorVT(
380                   *DAG.getContext(), IntermediateVT.getScalarType(),
381                   IntermediateVT.getVectorElementCount() * NumParts)
382             : EVT::getVectorVT(*DAG.getContext(),
383                                IntermediateVT.getScalarType(),
384                                NumIntermediates);
385     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
386                                                 : ISD::BUILD_VECTOR,
387                       DL, BuiltVectorTy, Ops);
388   }
389 
390   // There is now one part, held in Val.  Correct it to match ValueVT.
391   EVT PartEVT = Val.getValueType();
392 
393   if (PartEVT == ValueVT)
394     return Val;
395 
396   if (PartEVT.isVector()) {
397     // Vector/Vector bitcast.
398     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
399       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
400 
401     // If the parts vector has more elements than the value vector, then we
402     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
403     // Extract the elements we want.
404     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
405       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
406               ValueVT.getVectorElementCount().getKnownMinValue()) &&
407              (PartEVT.getVectorElementCount().isScalable() ==
408               ValueVT.getVectorElementCount().isScalable()) &&
409              "Cannot narrow, it would be a lossy transformation");
410       PartEVT =
411           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
412                            ValueVT.getVectorElementCount());
413       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
414                         DAG.getVectorIdxConstant(0, DL));
415       if (PartEVT == ValueVT)
416         return Val;
417       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
418         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419     }
420 
421     // Promoted vector extract
422     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
423   }
424 
425   // Trivial bitcast if the types are the same size and the destination
426   // vector type is legal.
427   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
428       TLI.isTypeLegal(ValueVT))
429     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
430 
431   if (ValueVT.getVectorNumElements() != 1) {
432      // Certain ABIs require that vectors are passed as integers. For vectors
433      // are the same size, this is an obvious bitcast.
434      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
435        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
436      } else if (ValueVT.bitsLT(PartEVT)) {
437        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
438        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
439        // Drop the extra bits.
440        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
441        return DAG.getBitcast(ValueVT, Val);
442      }
443 
444      diagnosePossiblyInvalidConstraint(
445          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
446      return DAG.getUNDEF(ValueVT);
447   }
448 
449   // Handle cases such as i8 -> <1 x i1>
450   EVT ValueSVT = ValueVT.getVectorElementType();
451   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
452     unsigned ValueSize = ValueSVT.getSizeInBits();
453     if (ValueSize == PartEVT.getSizeInBits()) {
454       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
455     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
456       // It's possible a scalar floating point type gets softened to integer and
457       // then promoted to a larger integer. If PartEVT is the larger integer
458       // we need to truncate it and then bitcast to the FP type.
459       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
460       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
461       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
462       Val = DAG.getBitcast(ValueSVT, Val);
463     } else {
464       Val = ValueVT.isFloatingPoint()
465                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
466                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
467     }
468   }
469 
470   return DAG.getBuildVector(ValueVT, DL, Val);
471 }
472 
473 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
474                                  SDValue Val, SDValue *Parts, unsigned NumParts,
475                                  MVT PartVT, const Value *V,
476                                  Optional<CallingConv::ID> CallConv);
477 
478 /// getCopyToParts - Create a series of nodes that contain the specified value
479 /// split into legal parts.  If the parts contain more bits than Val, then, for
480 /// integers, ExtendKind can be used to specify how to generate the extra bits.
481 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
482                            SDValue *Parts, unsigned NumParts, MVT PartVT,
483                            const Value *V,
484                            Optional<CallingConv::ID> CallConv = None,
485                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
486   // Let the target split the parts if it wants to
487   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
488   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
489                                       CallConv))
490     return;
491   EVT ValueVT = Val.getValueType();
492 
493   // Handle the vector case separately.
494   if (ValueVT.isVector())
495     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
496                                 CallConv);
497 
498   unsigned PartBits = PartVT.getSizeInBits();
499   unsigned OrigNumParts = NumParts;
500   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
501          "Copying to an illegal type!");
502 
503   if (NumParts == 0)
504     return;
505 
506   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
507   EVT PartEVT = PartVT;
508   if (PartEVT == ValueVT) {
509     assert(NumParts == 1 && "No-op copy with multiple parts!");
510     Parts[0] = Val;
511     return;
512   }
513 
514   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
515     // If the parts cover more bits than the value has, promote the value.
516     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
517       assert(NumParts == 1 && "Do not know what to promote to!");
518       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
519     } else {
520       if (ValueVT.isFloatingPoint()) {
521         // FP values need to be bitcast, then extended if they are being put
522         // into a larger container.
523         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
524         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
525       }
526       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
527              ValueVT.isInteger() &&
528              "Unknown mismatch!");
529       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
530       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
531       if (PartVT == MVT::x86mmx)
532         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
533     }
534   } else if (PartBits == ValueVT.getSizeInBits()) {
535     // Different types of the same size.
536     assert(NumParts == 1 && PartEVT != ValueVT);
537     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
538   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
539     // If the parts cover less bits than value has, truncate the value.
540     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
541            ValueVT.isInteger() &&
542            "Unknown mismatch!");
543     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
544     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
545     if (PartVT == MVT::x86mmx)
546       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
547   }
548 
549   // The value may have changed - recompute ValueVT.
550   ValueVT = Val.getValueType();
551   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
552          "Failed to tile the value with PartVT!");
553 
554   if (NumParts == 1) {
555     if (PartEVT != ValueVT) {
556       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
557                                         "scalar-to-vector conversion failed");
558       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
559     }
560 
561     Parts[0] = Val;
562     return;
563   }
564 
565   // Expand the value into multiple parts.
566   if (NumParts & (NumParts - 1)) {
567     // The number of parts is not a power of 2.  Split off and copy the tail.
568     assert(PartVT.isInteger() && ValueVT.isInteger() &&
569            "Do not know what to expand to!");
570     unsigned RoundParts = 1 << Log2_32(NumParts);
571     unsigned RoundBits = RoundParts * PartBits;
572     unsigned OddParts = NumParts - RoundParts;
573     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
574       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
575 
576     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
577                    CallConv);
578 
579     if (DAG.getDataLayout().isBigEndian())
580       // The odd parts were reversed by getCopyToParts - unreverse them.
581       std::reverse(Parts + RoundParts, Parts + NumParts);
582 
583     NumParts = RoundParts;
584     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
585     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
586   }
587 
588   // The number of parts is a power of 2.  Repeatedly bisect the value using
589   // EXTRACT_ELEMENT.
590   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
591                          EVT::getIntegerVT(*DAG.getContext(),
592                                            ValueVT.getSizeInBits()),
593                          Val);
594 
595   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
596     for (unsigned i = 0; i < NumParts; i += StepSize) {
597       unsigned ThisBits = StepSize * PartBits / 2;
598       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
599       SDValue &Part0 = Parts[i];
600       SDValue &Part1 = Parts[i+StepSize/2];
601 
602       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
603                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
604       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
605                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
606 
607       if (ThisBits == PartBits && ThisVT != PartVT) {
608         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
609         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
610       }
611     }
612   }
613 
614   if (DAG.getDataLayout().isBigEndian())
615     std::reverse(Parts, Parts + OrigNumParts);
616 }
617 
618 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
619                                      const SDLoc &DL, EVT PartVT) {
620   if (!PartVT.isVector())
621     return SDValue();
622 
623   EVT ValueVT = Val.getValueType();
624   ElementCount PartNumElts = PartVT.getVectorElementCount();
625   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
626 
627   // We only support widening vectors with equivalent element types and
628   // fixed/scalable properties. If a target needs to widen a fixed-length type
629   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
630   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
631       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
632       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
633     return SDValue();
634 
635   // Widening a scalable vector to another scalable vector is done by inserting
636   // the vector into a larger undef one.
637   if (PartNumElts.isScalable())
638     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
639                        Val, DAG.getVectorIdxConstant(0, DL));
640 
641   EVT ElementVT = PartVT.getVectorElementType();
642   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
643   // undef elements.
644   SmallVector<SDValue, 16> Ops;
645   DAG.ExtractVectorElements(Val, Ops);
646   SDValue EltUndef = DAG.getUNDEF(ElementVT);
647   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
648 
649   // FIXME: Use CONCAT for 2x -> 4x.
650   return DAG.getBuildVector(PartVT, DL, Ops);
651 }
652 
653 /// getCopyToPartsVector - Create a series of nodes that contain the specified
654 /// value split into legal parts.
655 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
656                                  SDValue Val, SDValue *Parts, unsigned NumParts,
657                                  MVT PartVT, const Value *V,
658                                  Optional<CallingConv::ID> CallConv) {
659   EVT ValueVT = Val.getValueType();
660   assert(ValueVT.isVector() && "Not a vector");
661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
662   const bool IsABIRegCopy = CallConv.has_value();
663 
664   if (NumParts == 1) {
665     EVT PartEVT = PartVT;
666     if (PartEVT == ValueVT) {
667       // Nothing to do.
668     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
669       // Bitconvert vector->vector case.
670       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
671     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
672       Val = Widened;
673     } else if (PartVT.isVector() &&
674                PartEVT.getVectorElementType().bitsGE(
675                    ValueVT.getVectorElementType()) &&
676                PartEVT.getVectorElementCount() ==
677                    ValueVT.getVectorElementCount()) {
678 
679       // Promoted vector extract
680       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
681     } else if (PartEVT.isVector() &&
682                PartEVT.getVectorElementType() !=
683                    ValueVT.getVectorElementType() &&
684                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
685                    TargetLowering::TypeWidenVector) {
686       // Combination of widening and promotion.
687       EVT WidenVT =
688           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
689                            PartVT.getVectorElementCount());
690       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
691       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
692     } else {
693       // Don't extract an integer from a float vector. This can happen if the
694       // FP type gets softened to integer and then promoted. The promotion
695       // prevents it from being picked up by the earlier bitcast case.
696       if (ValueVT.getVectorElementCount().isScalar() &&
697           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
698         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
699                           DAG.getVectorIdxConstant(0, DL));
700       } else {
701         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
702         assert(PartVT.getFixedSizeInBits() > ValueSize &&
703                "lossy conversion of vector to scalar type");
704         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
705         Val = DAG.getBitcast(IntermediateType, Val);
706         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
707       }
708     }
709 
710     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
711     Parts[0] = Val;
712     return;
713   }
714 
715   // Handle a multi-element vector.
716   EVT IntermediateVT;
717   MVT RegisterVT;
718   unsigned NumIntermediates;
719   unsigned NumRegs;
720   if (IsABIRegCopy) {
721     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
722         *DAG.getContext(), CallConv.value(), ValueVT, IntermediateVT,
723         NumIntermediates, RegisterVT);
724   } else {
725     NumRegs =
726         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
727                                    NumIntermediates, RegisterVT);
728   }
729 
730   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
731   NumParts = NumRegs; // Silence a compiler warning.
732   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
733 
734   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
735          "Mixing scalable and fixed vectors when copying in parts");
736 
737   Optional<ElementCount> DestEltCnt;
738 
739   if (IntermediateVT.isVector())
740     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
741   else
742     DestEltCnt = ElementCount::getFixed(NumIntermediates);
743 
744   EVT BuiltVectorTy = EVT::getVectorVT(
745       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
746 
747   if (ValueVT == BuiltVectorTy) {
748     // Nothing to do.
749   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
750     // Bitconvert vector->vector case.
751     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
752   } else {
753     if (BuiltVectorTy.getVectorElementType().bitsGT(
754             ValueVT.getVectorElementType())) {
755       // Integer promotion.
756       ValueVT = EVT::getVectorVT(*DAG.getContext(),
757                                  BuiltVectorTy.getVectorElementType(),
758                                  ValueVT.getVectorElementCount());
759       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
760     }
761 
762     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
763       Val = Widened;
764     }
765   }
766 
767   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
768 
769   // Split the vector into intermediate operands.
770   SmallVector<SDValue, 8> Ops(NumIntermediates);
771   for (unsigned i = 0; i != NumIntermediates; ++i) {
772     if (IntermediateVT.isVector()) {
773       // This does something sensible for scalable vectors - see the
774       // definition of EXTRACT_SUBVECTOR for further details.
775       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
776       Ops[i] =
777           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
778                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
779     } else {
780       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
781                            DAG.getVectorIdxConstant(i, DL));
782     }
783   }
784 
785   // Split the intermediate operands into legal parts.
786   if (NumParts == NumIntermediates) {
787     // If the register was not expanded, promote or copy the value,
788     // as appropriate.
789     for (unsigned i = 0; i != NumParts; ++i)
790       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
791   } else if (NumParts > 0) {
792     // If the intermediate type was expanded, split each the value into
793     // legal parts.
794     assert(NumIntermediates != 0 && "division by zero");
795     assert(NumParts % NumIntermediates == 0 &&
796            "Must expand into a divisible number of parts!");
797     unsigned Factor = NumParts / NumIntermediates;
798     for (unsigned i = 0; i != NumIntermediates; ++i)
799       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
800                      CallConv);
801   }
802 }
803 
804 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
805                            EVT valuevt, Optional<CallingConv::ID> CC)
806     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
807       RegCount(1, regs.size()), CallConv(CC) {}
808 
809 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
810                            const DataLayout &DL, unsigned Reg, Type *Ty,
811                            Optional<CallingConv::ID> CC) {
812   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
813 
814   CallConv = CC;
815 
816   for (EVT ValueVT : ValueVTs) {
817     unsigned NumRegs =
818         isABIMangled()
819             ? TLI.getNumRegistersForCallingConv(Context, CC.value(), ValueVT)
820             : TLI.getNumRegisters(Context, ValueVT);
821     MVT RegisterVT =
822         isABIMangled()
823             ? TLI.getRegisterTypeForCallingConv(Context, CC.value(), ValueVT)
824             : TLI.getRegisterType(Context, ValueVT);
825     for (unsigned i = 0; i != NumRegs; ++i)
826       Regs.push_back(Reg + i);
827     RegVTs.push_back(RegisterVT);
828     RegCount.push_back(NumRegs);
829     Reg += NumRegs;
830   }
831 }
832 
833 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
834                                       FunctionLoweringInfo &FuncInfo,
835                                       const SDLoc &dl, SDValue &Chain,
836                                       SDValue *Flag, const Value *V) const {
837   // A Value with type {} or [0 x %t] needs no registers.
838   if (ValueVTs.empty())
839     return SDValue();
840 
841   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
842 
843   // Assemble the legal parts into the final values.
844   SmallVector<SDValue, 4> Values(ValueVTs.size());
845   SmallVector<SDValue, 8> Parts;
846   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
847     // Copy the legal parts from the registers.
848     EVT ValueVT = ValueVTs[Value];
849     unsigned NumRegs = RegCount[Value];
850     MVT RegisterVT =
851         isABIMangled() ? TLI.getRegisterTypeForCallingConv(
852                              *DAG.getContext(), CallConv.value(), RegVTs[Value])
853                        : RegVTs[Value];
854 
855     Parts.resize(NumRegs);
856     for (unsigned i = 0; i != NumRegs; ++i) {
857       SDValue P;
858       if (!Flag) {
859         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
860       } else {
861         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
862         *Flag = P.getValue(2);
863       }
864 
865       Chain = P.getValue(1);
866       Parts[i] = P;
867 
868       // If the source register was virtual and if we know something about it,
869       // add an assert node.
870       if (!Register::isVirtualRegister(Regs[Part + i]) ||
871           !RegisterVT.isInteger())
872         continue;
873 
874       const FunctionLoweringInfo::LiveOutInfo *LOI =
875         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
876       if (!LOI)
877         continue;
878 
879       unsigned RegSize = RegisterVT.getScalarSizeInBits();
880       unsigned NumSignBits = LOI->NumSignBits;
881       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
882 
883       if (NumZeroBits == RegSize) {
884         // The current value is a zero.
885         // Explicitly express that as it would be easier for
886         // optimizations to kick in.
887         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
888         continue;
889       }
890 
891       // FIXME: We capture more information than the dag can represent.  For
892       // now, just use the tightest assertzext/assertsext possible.
893       bool isSExt;
894       EVT FromVT(MVT::Other);
895       if (NumZeroBits) {
896         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
897         isSExt = false;
898       } else if (NumSignBits > 1) {
899         FromVT =
900             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
901         isSExt = true;
902       } else {
903         continue;
904       }
905       // Add an assertion node.
906       assert(FromVT != MVT::Other);
907       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
908                              RegisterVT, P, DAG.getValueType(FromVT));
909     }
910 
911     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
912                                      RegisterVT, ValueVT, V, CallConv);
913     Part += NumRegs;
914     Parts.clear();
915   }
916 
917   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
918 }
919 
920 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
921                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
922                                  const Value *V,
923                                  ISD::NodeType PreferredExtendType) const {
924   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
925   ISD::NodeType ExtendKind = PreferredExtendType;
926 
927   // Get the list of the values's legal parts.
928   unsigned NumRegs = Regs.size();
929   SmallVector<SDValue, 8> Parts(NumRegs);
930   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
931     unsigned NumParts = RegCount[Value];
932 
933     MVT RegisterVT =
934         isABIMangled() ? TLI.getRegisterTypeForCallingConv(
935                              *DAG.getContext(), CallConv.value(), RegVTs[Value])
936                        : RegVTs[Value];
937 
938     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
939       ExtendKind = ISD::ZERO_EXTEND;
940 
941     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
942                    NumParts, RegisterVT, V, CallConv, ExtendKind);
943     Part += NumParts;
944   }
945 
946   // Copy the parts into the registers.
947   SmallVector<SDValue, 8> Chains(NumRegs);
948   for (unsigned i = 0; i != NumRegs; ++i) {
949     SDValue Part;
950     if (!Flag) {
951       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
952     } else {
953       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
954       *Flag = Part.getValue(1);
955     }
956 
957     Chains[i] = Part.getValue(0);
958   }
959 
960   if (NumRegs == 1 || Flag)
961     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
962     // flagged to it. That is the CopyToReg nodes and the user are considered
963     // a single scheduling unit. If we create a TokenFactor and return it as
964     // chain, then the TokenFactor is both a predecessor (operand) of the
965     // user as well as a successor (the TF operands are flagged to the user).
966     // c1, f1 = CopyToReg
967     // c2, f2 = CopyToReg
968     // c3     = TokenFactor c1, c2
969     // ...
970     //        = op c3, ..., f2
971     Chain = Chains[NumRegs-1];
972   else
973     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
974 }
975 
976 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
977                                         unsigned MatchingIdx, const SDLoc &dl,
978                                         SelectionDAG &DAG,
979                                         std::vector<SDValue> &Ops) const {
980   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
981 
982   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
983   if (HasMatching)
984     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
985   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
986     // Put the register class of the virtual registers in the flag word.  That
987     // way, later passes can recompute register class constraints for inline
988     // assembly as well as normal instructions.
989     // Don't do this for tied operands that can use the regclass information
990     // from the def.
991     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
992     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
993     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
994   }
995 
996   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
997   Ops.push_back(Res);
998 
999   if (Code == InlineAsm::Kind_Clobber) {
1000     // Clobbers should always have a 1:1 mapping with registers, and may
1001     // reference registers that have illegal (e.g. vector) types. Hence, we
1002     // shouldn't try to apply any sort of splitting logic to them.
1003     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1004            "No 1:1 mapping from clobbers to regs?");
1005     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1006     (void)SP;
1007     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1008       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1009       assert(
1010           (Regs[I] != SP ||
1011            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1012           "If we clobbered the stack pointer, MFI should know about it.");
1013     }
1014     return;
1015   }
1016 
1017   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1018     MVT RegisterVT = RegVTs[Value];
1019     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1020                                            RegisterVT);
1021     for (unsigned i = 0; i != NumRegs; ++i) {
1022       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1023       unsigned TheReg = Regs[Reg++];
1024       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1025     }
1026   }
1027 }
1028 
1029 SmallVector<std::pair<unsigned, TypeSize>, 4>
1030 RegsForValue::getRegsAndSizes() const {
1031   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1032   unsigned I = 0;
1033   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1034     unsigned RegCount = std::get<0>(CountAndVT);
1035     MVT RegisterVT = std::get<1>(CountAndVT);
1036     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1037     for (unsigned E = I + RegCount; I != E; ++I)
1038       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1039   }
1040   return OutVec;
1041 }
1042 
1043 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1044                                AssumptionCache *ac,
1045                                const TargetLibraryInfo *li) {
1046   AA = aa;
1047   AC = ac;
1048   GFI = gfi;
1049   LibInfo = li;
1050   Context = DAG.getContext();
1051   LPadToCallSiteMap.clear();
1052   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1053 }
1054 
1055 void SelectionDAGBuilder::clear() {
1056   NodeMap.clear();
1057   UnusedArgNodeMap.clear();
1058   PendingLoads.clear();
1059   PendingExports.clear();
1060   PendingConstrainedFP.clear();
1061   PendingConstrainedFPStrict.clear();
1062   CurInst = nullptr;
1063   HasTailCall = false;
1064   SDNodeOrder = LowestSDNodeOrder;
1065   StatepointLowering.clear();
1066 }
1067 
1068 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1069   DanglingDebugInfoMap.clear();
1070 }
1071 
1072 // Update DAG root to include dependencies on Pending chains.
1073 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1074   SDValue Root = DAG.getRoot();
1075 
1076   if (Pending.empty())
1077     return Root;
1078 
1079   // Add current root to PendingChains, unless we already indirectly
1080   // depend on it.
1081   if (Root.getOpcode() != ISD::EntryToken) {
1082     unsigned i = 0, e = Pending.size();
1083     for (; i != e; ++i) {
1084       assert(Pending[i].getNode()->getNumOperands() > 1);
1085       if (Pending[i].getNode()->getOperand(0) == Root)
1086         break;  // Don't add the root if we already indirectly depend on it.
1087     }
1088 
1089     if (i == e)
1090       Pending.push_back(Root);
1091   }
1092 
1093   if (Pending.size() == 1)
1094     Root = Pending[0];
1095   else
1096     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1097 
1098   DAG.setRoot(Root);
1099   Pending.clear();
1100   return Root;
1101 }
1102 
1103 SDValue SelectionDAGBuilder::getMemoryRoot() {
1104   return updateRoot(PendingLoads);
1105 }
1106 
1107 SDValue SelectionDAGBuilder::getRoot() {
1108   // Chain up all pending constrained intrinsics together with all
1109   // pending loads, by simply appending them to PendingLoads and
1110   // then calling getMemoryRoot().
1111   PendingLoads.reserve(PendingLoads.size() +
1112                        PendingConstrainedFP.size() +
1113                        PendingConstrainedFPStrict.size());
1114   PendingLoads.append(PendingConstrainedFP.begin(),
1115                       PendingConstrainedFP.end());
1116   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1117                       PendingConstrainedFPStrict.end());
1118   PendingConstrainedFP.clear();
1119   PendingConstrainedFPStrict.clear();
1120   return getMemoryRoot();
1121 }
1122 
1123 SDValue SelectionDAGBuilder::getControlRoot() {
1124   // We need to emit pending fpexcept.strict constrained intrinsics,
1125   // so append them to the PendingExports list.
1126   PendingExports.append(PendingConstrainedFPStrict.begin(),
1127                         PendingConstrainedFPStrict.end());
1128   PendingConstrainedFPStrict.clear();
1129   return updateRoot(PendingExports);
1130 }
1131 
1132 void SelectionDAGBuilder::visit(const Instruction &I) {
1133   // Set up outgoing PHI node register values before emitting the terminator.
1134   if (I.isTerminator()) {
1135     HandlePHINodesInSuccessorBlocks(I.getParent());
1136   }
1137 
1138   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1139   if (!isa<DbgInfoIntrinsic>(I))
1140     ++SDNodeOrder;
1141 
1142   CurInst = &I;
1143 
1144   // Set inserted listener only if required.
1145   bool NodeInserted = false;
1146   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1147   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1148   if (PCSectionsMD) {
1149     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1150         DAG, [&](SDNode *) { NodeInserted = true; });
1151   }
1152 
1153   visit(I.getOpcode(), I);
1154 
1155   if (!I.isTerminator() && !HasTailCall &&
1156       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1157     CopyToExportRegsIfNeeded(&I);
1158 
1159   // Handle metadata.
1160   if (PCSectionsMD) {
1161     auto It = NodeMap.find(&I);
1162     if (It != NodeMap.end()) {
1163       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1164     } else if (NodeInserted) {
1165       // This should not happen; if it does, don't let it go unnoticed so we can
1166       // fix it. Relevant visit*() function is probably missing a setValue().
1167       errs() << "warning: loosing !pcsections metadata ["
1168              << I.getModule()->getName() << "]\n";
1169       LLVM_DEBUG(I.dump());
1170       assert(false);
1171     }
1172   }
1173 
1174   CurInst = nullptr;
1175 }
1176 
1177 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1178   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1179 }
1180 
1181 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1182   // Note: this doesn't use InstVisitor, because it has to work with
1183   // ConstantExpr's in addition to instructions.
1184   switch (Opcode) {
1185   default: llvm_unreachable("Unknown instruction type encountered!");
1186     // Build the switch statement using the Instruction.def file.
1187 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1188     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1189 #include "llvm/IR/Instruction.def"
1190   }
1191 }
1192 
1193 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1194                                                DebugLoc DL, unsigned Order) {
1195   // We treat variadic dbg_values differently at this stage.
1196   if (DI->hasArgList()) {
1197     // For variadic dbg_values we will now insert an undef.
1198     // FIXME: We can potentially recover these!
1199     SmallVector<SDDbgOperand, 2> Locs;
1200     for (const Value *V : DI->getValues()) {
1201       auto Undef = UndefValue::get(V->getType());
1202       Locs.push_back(SDDbgOperand::fromConst(Undef));
1203     }
1204     SDDbgValue *SDV = DAG.getDbgValueList(
1205         DI->getVariable(), DI->getExpression(), Locs, {},
1206         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1207     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1208   } else {
1209     // TODO: Dangling debug info will eventually either be resolved or produce
1210     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1211     // between the original dbg.value location and its resolved DBG_VALUE,
1212     // which we should ideally fill with an extra Undef DBG_VALUE.
1213     assert(DI->getNumVariableLocationOps() == 1 &&
1214            "DbgValueInst without an ArgList should have a single location "
1215            "operand.");
1216     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1217   }
1218 }
1219 
1220 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1221                                                 const DIExpression *Expr) {
1222   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1223     const DbgValueInst *DI = DDI.getDI();
1224     DIVariable *DanglingVariable = DI->getVariable();
1225     DIExpression *DanglingExpr = DI->getExpression();
1226     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1227       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1228       return true;
1229     }
1230     return false;
1231   };
1232 
1233   for (auto &DDIMI : DanglingDebugInfoMap) {
1234     DanglingDebugInfoVector &DDIV = DDIMI.second;
1235 
1236     // If debug info is to be dropped, run it through final checks to see
1237     // whether it can be salvaged.
1238     for (auto &DDI : DDIV)
1239       if (isMatchingDbgValue(DDI))
1240         salvageUnresolvedDbgValue(DDI);
1241 
1242     erase_if(DDIV, isMatchingDbgValue);
1243   }
1244 }
1245 
1246 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1247 // generate the debug data structures now that we've seen its definition.
1248 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1249                                                    SDValue Val) {
1250   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1251   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1252     return;
1253 
1254   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1255   for (auto &DDI : DDIV) {
1256     const DbgValueInst *DI = DDI.getDI();
1257     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1258     assert(DI && "Ill-formed DanglingDebugInfo");
1259     DebugLoc dl = DDI.getdl();
1260     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1261     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1262     DILocalVariable *Variable = DI->getVariable();
1263     DIExpression *Expr = DI->getExpression();
1264     assert(Variable->isValidLocationForIntrinsic(dl) &&
1265            "Expected inlined-at fields to agree");
1266     SDDbgValue *SDV;
1267     if (Val.getNode()) {
1268       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1269       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1270       // we couldn't resolve it directly when examining the DbgValue intrinsic
1271       // in the first place we should not be more successful here). Unless we
1272       // have some test case that prove this to be correct we should avoid
1273       // calling EmitFuncArgumentDbgValue here.
1274       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl,
1275                                     FuncArgumentDbgValueKind::Value, Val)) {
1276         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1277                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1278         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1279         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1280         // inserted after the definition of Val when emitting the instructions
1281         // after ISel. An alternative could be to teach
1282         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1283         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1284                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1285                    << ValSDNodeOrder << "\n");
1286         SDV = getDbgValue(Val, Variable, Expr, dl,
1287                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1288         DAG.AddDbgValue(SDV, false);
1289       } else
1290         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1291                           << "in EmitFuncArgumentDbgValue\n");
1292     } else {
1293       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1294       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1295       auto SDV =
1296           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1297       DAG.AddDbgValue(SDV, false);
1298     }
1299   }
1300   DDIV.clear();
1301 }
1302 
1303 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1304   // TODO: For the variadic implementation, instead of only checking the fail
1305   // state of `handleDebugValue`, we need know specifically which values were
1306   // invalid, so that we attempt to salvage only those values when processing
1307   // a DIArgList.
1308   assert(!DDI.getDI()->hasArgList() &&
1309          "Not implemented for variadic dbg_values");
1310   Value *V = DDI.getDI()->getValue(0);
1311   DILocalVariable *Var = DDI.getDI()->getVariable();
1312   DIExpression *Expr = DDI.getDI()->getExpression();
1313   DebugLoc DL = DDI.getdl();
1314   unsigned SDOrder = DDI.getSDNodeOrder();
1315   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1316   // that DW_OP_stack_value is desired.
1317   assert(isa<DbgValueInst>(DDI.getDI()));
1318   bool StackValue = true;
1319 
1320   // Can this Value can be encoded without any further work?
1321   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1322     return;
1323 
1324   // Attempt to salvage back through as many instructions as possible. Bail if
1325   // a non-instruction is seen, such as a constant expression or global
1326   // variable. FIXME: Further work could recover those too.
1327   while (isa<Instruction>(V)) {
1328     Instruction &VAsInst = *cast<Instruction>(V);
1329     // Temporary "0", awaiting real implementation.
1330     SmallVector<uint64_t, 16> Ops;
1331     SmallVector<Value *, 4> AdditionalValues;
1332     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1333                              AdditionalValues);
1334     // If we cannot salvage any further, and haven't yet found a suitable debug
1335     // expression, bail out.
1336     if (!V)
1337       break;
1338 
1339     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1340     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1341     // here for variadic dbg_values, remove that condition.
1342     if (!AdditionalValues.empty())
1343       break;
1344 
1345     // New value and expr now represent this debuginfo.
1346     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1347 
1348     // Some kind of simplification occurred: check whether the operand of the
1349     // salvaged debug expression can be encoded in this DAG.
1350     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1351       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1352                         << *DDI.getDI() << "\nBy stripping back to:\n  " << *V);
1353       return;
1354     }
1355   }
1356 
1357   // This was the final opportunity to salvage this debug information, and it
1358   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1359   // any earlier variable location.
1360   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1361   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1362   DAG.AddDbgValue(SDV, false);
1363 
1364   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << *DDI.getDI()
1365                     << "\n");
1366   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1367                     << "\n");
1368 }
1369 
1370 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1371                                            DILocalVariable *Var,
1372                                            DIExpression *Expr, DebugLoc DbgLoc,
1373                                            unsigned Order, bool IsVariadic) {
1374   if (Values.empty())
1375     return true;
1376   SmallVector<SDDbgOperand> LocationOps;
1377   SmallVector<SDNode *> Dependencies;
1378   for (const Value *V : Values) {
1379     // Constant value.
1380     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1381         isa<ConstantPointerNull>(V)) {
1382       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1383       continue;
1384     }
1385 
1386     // Look through IntToPtr constants.
1387     if (auto *CE = dyn_cast<ConstantExpr>(V))
1388       if (CE->getOpcode() == Instruction::IntToPtr) {
1389         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1390         continue;
1391       }
1392 
1393     // If the Value is a frame index, we can create a FrameIndex debug value
1394     // without relying on the DAG at all.
1395     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1396       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1397       if (SI != FuncInfo.StaticAllocaMap.end()) {
1398         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1399         continue;
1400       }
1401     }
1402 
1403     // Do not use getValue() in here; we don't want to generate code at
1404     // this point if it hasn't been done yet.
1405     SDValue N = NodeMap[V];
1406     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1407       N = UnusedArgNodeMap[V];
1408     if (N.getNode()) {
1409       // Only emit func arg dbg value for non-variadic dbg.values for now.
1410       if (!IsVariadic &&
1411           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1412                                    FuncArgumentDbgValueKind::Value, N))
1413         return true;
1414       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1415         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1416         // describe stack slot locations.
1417         //
1418         // Consider "int x = 0; int *px = &x;". There are two kinds of
1419         // interesting debug values here after optimization:
1420         //
1421         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1422         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1423         //
1424         // Both describe the direct values of their associated variables.
1425         Dependencies.push_back(N.getNode());
1426         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1427         continue;
1428       }
1429       LocationOps.emplace_back(
1430           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1431       continue;
1432     }
1433 
1434     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1435     // Special rules apply for the first dbg.values of parameter variables in a
1436     // function. Identify them by the fact they reference Argument Values, that
1437     // they're parameters, and they are parameters of the current function. We
1438     // need to let them dangle until they get an SDNode.
1439     bool IsParamOfFunc =
1440         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1441     if (IsParamOfFunc)
1442       return false;
1443 
1444     // The value is not used in this block yet (or it would have an SDNode).
1445     // We still want the value to appear for the user if possible -- if it has
1446     // an associated VReg, we can refer to that instead.
1447     auto VMI = FuncInfo.ValueMap.find(V);
1448     if (VMI != FuncInfo.ValueMap.end()) {
1449       unsigned Reg = VMI->second;
1450       // If this is a PHI node, it may be split up into several MI PHI nodes
1451       // (in FunctionLoweringInfo::set).
1452       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1453                        V->getType(), None);
1454       if (RFV.occupiesMultipleRegs()) {
1455         // FIXME: We could potentially support variadic dbg_values here.
1456         if (IsVariadic)
1457           return false;
1458         unsigned Offset = 0;
1459         unsigned BitsToDescribe = 0;
1460         if (auto VarSize = Var->getSizeInBits())
1461           BitsToDescribe = *VarSize;
1462         if (auto Fragment = Expr->getFragmentInfo())
1463           BitsToDescribe = Fragment->SizeInBits;
1464         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1465           // Bail out if all bits are described already.
1466           if (Offset >= BitsToDescribe)
1467             break;
1468           // TODO: handle scalable vectors.
1469           unsigned RegisterSize = RegAndSize.second;
1470           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1471                                       ? BitsToDescribe - Offset
1472                                       : RegisterSize;
1473           auto FragmentExpr = DIExpression::createFragmentExpression(
1474               Expr, Offset, FragmentSize);
1475           if (!FragmentExpr)
1476             continue;
1477           SDDbgValue *SDV = DAG.getVRegDbgValue(
1478               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1479           DAG.AddDbgValue(SDV, false);
1480           Offset += RegisterSize;
1481         }
1482         return true;
1483       }
1484       // We can use simple vreg locations for variadic dbg_values as well.
1485       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1486       continue;
1487     }
1488     // We failed to create a SDDbgOperand for V.
1489     return false;
1490   }
1491 
1492   // We have created a SDDbgOperand for each Value in Values.
1493   // Should use Order instead of SDNodeOrder?
1494   assert(!LocationOps.empty());
1495   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1496                                         /*IsIndirect=*/false, DbgLoc,
1497                                         SDNodeOrder, IsVariadic);
1498   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1499   return true;
1500 }
1501 
1502 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1503   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1504   for (auto &Pair : DanglingDebugInfoMap)
1505     for (auto &DDI : Pair.second)
1506       salvageUnresolvedDbgValue(DDI);
1507   clearDanglingDebugInfo();
1508 }
1509 
1510 /// getCopyFromRegs - If there was virtual register allocated for the value V
1511 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1512 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1513   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1514   SDValue Result;
1515 
1516   if (It != FuncInfo.ValueMap.end()) {
1517     Register InReg = It->second;
1518 
1519     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1520                      DAG.getDataLayout(), InReg, Ty,
1521                      None); // This is not an ABI copy.
1522     SDValue Chain = DAG.getEntryNode();
1523     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1524                                  V);
1525     resolveDanglingDebugInfo(V, Result);
1526   }
1527 
1528   return Result;
1529 }
1530 
1531 /// getValue - Return an SDValue for the given Value.
1532 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1533   // If we already have an SDValue for this value, use it. It's important
1534   // to do this first, so that we don't create a CopyFromReg if we already
1535   // have a regular SDValue.
1536   SDValue &N = NodeMap[V];
1537   if (N.getNode()) return N;
1538 
1539   // If there's a virtual register allocated and initialized for this
1540   // value, use it.
1541   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1542     return copyFromReg;
1543 
1544   // Otherwise create a new SDValue and remember it.
1545   SDValue Val = getValueImpl(V);
1546   NodeMap[V] = Val;
1547   resolveDanglingDebugInfo(V, Val);
1548   return Val;
1549 }
1550 
1551 /// getNonRegisterValue - Return an SDValue for the given Value, but
1552 /// don't look in FuncInfo.ValueMap for a virtual register.
1553 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1554   // If we already have an SDValue for this value, use it.
1555   SDValue &N = NodeMap[V];
1556   if (N.getNode()) {
1557     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1558       // Remove the debug location from the node as the node is about to be used
1559       // in a location which may differ from the original debug location.  This
1560       // is relevant to Constant and ConstantFP nodes because they can appear
1561       // as constant expressions inside PHI nodes.
1562       N->setDebugLoc(DebugLoc());
1563     }
1564     return N;
1565   }
1566 
1567   // Otherwise create a new SDValue and remember it.
1568   SDValue Val = getValueImpl(V);
1569   NodeMap[V] = Val;
1570   resolveDanglingDebugInfo(V, Val);
1571   return Val;
1572 }
1573 
1574 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1575 /// Create an SDValue for the given value.
1576 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1578 
1579   if (const Constant *C = dyn_cast<Constant>(V)) {
1580     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1581 
1582     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1583       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1584 
1585     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1586       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1587 
1588     if (isa<ConstantPointerNull>(C)) {
1589       unsigned AS = V->getType()->getPointerAddressSpace();
1590       return DAG.getConstant(0, getCurSDLoc(),
1591                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1592     }
1593 
1594     if (match(C, m_VScale(DAG.getDataLayout())))
1595       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1596 
1597     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1598       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1599 
1600     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1601       return DAG.getUNDEF(VT);
1602 
1603     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1604       visit(CE->getOpcode(), *CE);
1605       SDValue N1 = NodeMap[V];
1606       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1607       return N1;
1608     }
1609 
1610     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1611       SmallVector<SDValue, 4> Constants;
1612       for (const Use &U : C->operands()) {
1613         SDNode *Val = getValue(U).getNode();
1614         // If the operand is an empty aggregate, there are no values.
1615         if (!Val) continue;
1616         // Add each leaf value from the operand to the Constants list
1617         // to form a flattened list of all the values.
1618         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1619           Constants.push_back(SDValue(Val, i));
1620       }
1621 
1622       return DAG.getMergeValues(Constants, getCurSDLoc());
1623     }
1624 
1625     if (const ConstantDataSequential *CDS =
1626           dyn_cast<ConstantDataSequential>(C)) {
1627       SmallVector<SDValue, 4> Ops;
1628       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1629         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1630         // Add each leaf value from the operand to the Constants list
1631         // to form a flattened list of all the values.
1632         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1633           Ops.push_back(SDValue(Val, i));
1634       }
1635 
1636       if (isa<ArrayType>(CDS->getType()))
1637         return DAG.getMergeValues(Ops, getCurSDLoc());
1638       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1639     }
1640 
1641     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1642       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1643              "Unknown struct or array constant!");
1644 
1645       SmallVector<EVT, 4> ValueVTs;
1646       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1647       unsigned NumElts = ValueVTs.size();
1648       if (NumElts == 0)
1649         return SDValue(); // empty struct
1650       SmallVector<SDValue, 4> Constants(NumElts);
1651       for (unsigned i = 0; i != NumElts; ++i) {
1652         EVT EltVT = ValueVTs[i];
1653         if (isa<UndefValue>(C))
1654           Constants[i] = DAG.getUNDEF(EltVT);
1655         else if (EltVT.isFloatingPoint())
1656           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1657         else
1658           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1659       }
1660 
1661       return DAG.getMergeValues(Constants, getCurSDLoc());
1662     }
1663 
1664     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1665       return DAG.getBlockAddress(BA, VT);
1666 
1667     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1668       return getValue(Equiv->getGlobalValue());
1669 
1670     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1671       return getValue(NC->getGlobalValue());
1672 
1673     VectorType *VecTy = cast<VectorType>(V->getType());
1674 
1675     // Now that we know the number and type of the elements, get that number of
1676     // elements into the Ops array based on what kind of constant it is.
1677     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1678       SmallVector<SDValue, 16> Ops;
1679       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1680       for (unsigned i = 0; i != NumElements; ++i)
1681         Ops.push_back(getValue(CV->getOperand(i)));
1682 
1683       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1684     }
1685 
1686     if (isa<ConstantAggregateZero>(C)) {
1687       EVT EltVT =
1688           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1689 
1690       SDValue Op;
1691       if (EltVT.isFloatingPoint())
1692         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1693       else
1694         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1695 
1696       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1697     }
1698 
1699     llvm_unreachable("Unknown vector constant");
1700   }
1701 
1702   // If this is a static alloca, generate it as the frameindex instead of
1703   // computation.
1704   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1705     DenseMap<const AllocaInst*, int>::iterator SI =
1706       FuncInfo.StaticAllocaMap.find(AI);
1707     if (SI != FuncInfo.StaticAllocaMap.end())
1708       return DAG.getFrameIndex(SI->second,
1709                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1710   }
1711 
1712   // If this is an instruction which fast-isel has deferred, select it now.
1713   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1714     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1715 
1716     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1717                      Inst->getType(), None);
1718     SDValue Chain = DAG.getEntryNode();
1719     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1720   }
1721 
1722   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1723     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1724 
1725   if (const auto *BB = dyn_cast<BasicBlock>(V))
1726     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1727 
1728   llvm_unreachable("Can't get register for value!");
1729 }
1730 
1731 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1732   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1733   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1734   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1735   bool IsSEH = isAsynchronousEHPersonality(Pers);
1736   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1737   if (!IsSEH)
1738     CatchPadMBB->setIsEHScopeEntry();
1739   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1740   if (IsMSVCCXX || IsCoreCLR)
1741     CatchPadMBB->setIsEHFuncletEntry();
1742 }
1743 
1744 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1745   // Update machine-CFG edge.
1746   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1747   FuncInfo.MBB->addSuccessor(TargetMBB);
1748   TargetMBB->setIsEHCatchretTarget(true);
1749   DAG.getMachineFunction().setHasEHCatchret(true);
1750 
1751   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1752   bool IsSEH = isAsynchronousEHPersonality(Pers);
1753   if (IsSEH) {
1754     // If this is not a fall-through branch or optimizations are switched off,
1755     // emit the branch.
1756     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1757         TM.getOptLevel() == CodeGenOpt::None)
1758       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1759                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1760     return;
1761   }
1762 
1763   // Figure out the funclet membership for the catchret's successor.
1764   // This will be used by the FuncletLayout pass to determine how to order the
1765   // BB's.
1766   // A 'catchret' returns to the outer scope's color.
1767   Value *ParentPad = I.getCatchSwitchParentPad();
1768   const BasicBlock *SuccessorColor;
1769   if (isa<ConstantTokenNone>(ParentPad))
1770     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1771   else
1772     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1773   assert(SuccessorColor && "No parent funclet for catchret!");
1774   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1775   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1776 
1777   // Create the terminator node.
1778   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1779                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1780                             DAG.getBasicBlock(SuccessorColorMBB));
1781   DAG.setRoot(Ret);
1782 }
1783 
1784 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1785   // Don't emit any special code for the cleanuppad instruction. It just marks
1786   // the start of an EH scope/funclet.
1787   FuncInfo.MBB->setIsEHScopeEntry();
1788   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1789   if (Pers != EHPersonality::Wasm_CXX) {
1790     FuncInfo.MBB->setIsEHFuncletEntry();
1791     FuncInfo.MBB->setIsCleanupFuncletEntry();
1792   }
1793 }
1794 
1795 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1796 // not match, it is OK to add only the first unwind destination catchpad to the
1797 // successors, because there will be at least one invoke instruction within the
1798 // catch scope that points to the next unwind destination, if one exists, so
1799 // CFGSort cannot mess up with BB sorting order.
1800 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1801 // call within them, and catchpads only consisting of 'catch (...)' have a
1802 // '__cxa_end_catch' call within them, both of which generate invokes in case
1803 // the next unwind destination exists, i.e., the next unwind destination is not
1804 // the caller.)
1805 //
1806 // Having at most one EH pad successor is also simpler and helps later
1807 // transformations.
1808 //
1809 // For example,
1810 // current:
1811 //   invoke void @foo to ... unwind label %catch.dispatch
1812 // catch.dispatch:
1813 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1814 // catch.start:
1815 //   ...
1816 //   ... in this BB or some other child BB dominated by this BB there will be an
1817 //   invoke that points to 'next' BB as an unwind destination
1818 //
1819 // next: ; We don't need to add this to 'current' BB's successor
1820 //   ...
1821 static void findWasmUnwindDestinations(
1822     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1823     BranchProbability Prob,
1824     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1825         &UnwindDests) {
1826   while (EHPadBB) {
1827     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1828     if (isa<CleanupPadInst>(Pad)) {
1829       // Stop on cleanup pads.
1830       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1831       UnwindDests.back().first->setIsEHScopeEntry();
1832       break;
1833     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1834       // Add the catchpad handlers to the possible destinations. We don't
1835       // continue to the unwind destination of the catchswitch for wasm.
1836       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1837         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1838         UnwindDests.back().first->setIsEHScopeEntry();
1839       }
1840       break;
1841     } else {
1842       continue;
1843     }
1844   }
1845 }
1846 
1847 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1848 /// many places it could ultimately go. In the IR, we have a single unwind
1849 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1850 /// This function skips over imaginary basic blocks that hold catchswitch
1851 /// instructions, and finds all the "real" machine
1852 /// basic block destinations. As those destinations may not be successors of
1853 /// EHPadBB, here we also calculate the edge probability to those destinations.
1854 /// The passed-in Prob is the edge probability to EHPadBB.
1855 static void findUnwindDestinations(
1856     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1857     BranchProbability Prob,
1858     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1859         &UnwindDests) {
1860   EHPersonality Personality =
1861     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1862   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1863   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1864   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1865   bool IsSEH = isAsynchronousEHPersonality(Personality);
1866 
1867   if (IsWasmCXX) {
1868     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1869     assert(UnwindDests.size() <= 1 &&
1870            "There should be at most one unwind destination for wasm");
1871     return;
1872   }
1873 
1874   while (EHPadBB) {
1875     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1876     BasicBlock *NewEHPadBB = nullptr;
1877     if (isa<LandingPadInst>(Pad)) {
1878       // Stop on landingpads. They are not funclets.
1879       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1880       break;
1881     } else if (isa<CleanupPadInst>(Pad)) {
1882       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1883       // personalities.
1884       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1885       UnwindDests.back().first->setIsEHScopeEntry();
1886       UnwindDests.back().first->setIsEHFuncletEntry();
1887       break;
1888     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1889       // Add the catchpad handlers to the possible destinations.
1890       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1891         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1892         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1893         if (IsMSVCCXX || IsCoreCLR)
1894           UnwindDests.back().first->setIsEHFuncletEntry();
1895         if (!IsSEH)
1896           UnwindDests.back().first->setIsEHScopeEntry();
1897       }
1898       NewEHPadBB = CatchSwitch->getUnwindDest();
1899     } else {
1900       continue;
1901     }
1902 
1903     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1904     if (BPI && NewEHPadBB)
1905       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1906     EHPadBB = NewEHPadBB;
1907   }
1908 }
1909 
1910 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1911   // Update successor info.
1912   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1913   auto UnwindDest = I.getUnwindDest();
1914   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1915   BranchProbability UnwindDestProb =
1916       (BPI && UnwindDest)
1917           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1918           : BranchProbability::getZero();
1919   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1920   for (auto &UnwindDest : UnwindDests) {
1921     UnwindDest.first->setIsEHPad();
1922     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1923   }
1924   FuncInfo.MBB->normalizeSuccProbs();
1925 
1926   // Create the terminator node.
1927   SDValue Ret =
1928       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1929   DAG.setRoot(Ret);
1930 }
1931 
1932 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1933   report_fatal_error("visitCatchSwitch not yet implemented!");
1934 }
1935 
1936 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1937   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1938   auto &DL = DAG.getDataLayout();
1939   SDValue Chain = getControlRoot();
1940   SmallVector<ISD::OutputArg, 8> Outs;
1941   SmallVector<SDValue, 8> OutVals;
1942 
1943   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1944   // lower
1945   //
1946   //   %val = call <ty> @llvm.experimental.deoptimize()
1947   //   ret <ty> %val
1948   //
1949   // differently.
1950   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1951     LowerDeoptimizingReturn();
1952     return;
1953   }
1954 
1955   if (!FuncInfo.CanLowerReturn) {
1956     unsigned DemoteReg = FuncInfo.DemoteRegister;
1957     const Function *F = I.getParent()->getParent();
1958 
1959     // Emit a store of the return value through the virtual register.
1960     // Leave Outs empty so that LowerReturn won't try to load return
1961     // registers the usual way.
1962     SmallVector<EVT, 1> PtrValueVTs;
1963     ComputeValueVTs(TLI, DL,
1964                     F->getReturnType()->getPointerTo(
1965                         DAG.getDataLayout().getAllocaAddrSpace()),
1966                     PtrValueVTs);
1967 
1968     SDValue RetPtr =
1969         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1970     SDValue RetOp = getValue(I.getOperand(0));
1971 
1972     SmallVector<EVT, 4> ValueVTs, MemVTs;
1973     SmallVector<uint64_t, 4> Offsets;
1974     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1975                     &Offsets);
1976     unsigned NumValues = ValueVTs.size();
1977 
1978     SmallVector<SDValue, 4> Chains(NumValues);
1979     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1980     for (unsigned i = 0; i != NumValues; ++i) {
1981       // An aggregate return value cannot wrap around the address space, so
1982       // offsets to its parts don't wrap either.
1983       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1984                                            TypeSize::Fixed(Offsets[i]));
1985 
1986       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1987       if (MemVTs[i] != ValueVTs[i])
1988         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1989       Chains[i] = DAG.getStore(
1990           Chain, getCurSDLoc(), Val,
1991           // FIXME: better loc info would be nice.
1992           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1993           commonAlignment(BaseAlign, Offsets[i]));
1994     }
1995 
1996     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1997                         MVT::Other, Chains);
1998   } else if (I.getNumOperands() != 0) {
1999     SmallVector<EVT, 4> ValueVTs;
2000     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2001     unsigned NumValues = ValueVTs.size();
2002     if (NumValues) {
2003       SDValue RetOp = getValue(I.getOperand(0));
2004 
2005       const Function *F = I.getParent()->getParent();
2006 
2007       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2008           I.getOperand(0)->getType(), F->getCallingConv(),
2009           /*IsVarArg*/ false, DL);
2010 
2011       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2012       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2013         ExtendKind = ISD::SIGN_EXTEND;
2014       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2015         ExtendKind = ISD::ZERO_EXTEND;
2016 
2017       LLVMContext &Context = F->getContext();
2018       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2019 
2020       for (unsigned j = 0; j != NumValues; ++j) {
2021         EVT VT = ValueVTs[j];
2022 
2023         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2024           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2025 
2026         CallingConv::ID CC = F->getCallingConv();
2027 
2028         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2029         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2030         SmallVector<SDValue, 4> Parts(NumParts);
2031         getCopyToParts(DAG, getCurSDLoc(),
2032                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2033                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2034 
2035         // 'inreg' on function refers to return value
2036         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2037         if (RetInReg)
2038           Flags.setInReg();
2039 
2040         if (I.getOperand(0)->getType()->isPointerTy()) {
2041           Flags.setPointer();
2042           Flags.setPointerAddrSpace(
2043               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2044         }
2045 
2046         if (NeedsRegBlock) {
2047           Flags.setInConsecutiveRegs();
2048           if (j == NumValues - 1)
2049             Flags.setInConsecutiveRegsLast();
2050         }
2051 
2052         // Propagate extension type if any
2053         if (ExtendKind == ISD::SIGN_EXTEND)
2054           Flags.setSExt();
2055         else if (ExtendKind == ISD::ZERO_EXTEND)
2056           Flags.setZExt();
2057 
2058         for (unsigned i = 0; i < NumParts; ++i) {
2059           Outs.push_back(ISD::OutputArg(Flags,
2060                                         Parts[i].getValueType().getSimpleVT(),
2061                                         VT, /*isfixed=*/true, 0, 0));
2062           OutVals.push_back(Parts[i]);
2063         }
2064       }
2065     }
2066   }
2067 
2068   // Push in swifterror virtual register as the last element of Outs. This makes
2069   // sure swifterror virtual register will be returned in the swifterror
2070   // physical register.
2071   const Function *F = I.getParent()->getParent();
2072   if (TLI.supportSwiftError() &&
2073       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2074     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2075     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2076     Flags.setSwiftError();
2077     Outs.push_back(ISD::OutputArg(
2078         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2079         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2080     // Create SDNode for the swifterror virtual register.
2081     OutVals.push_back(
2082         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2083                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2084                         EVT(TLI.getPointerTy(DL))));
2085   }
2086 
2087   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2088   CallingConv::ID CallConv =
2089     DAG.getMachineFunction().getFunction().getCallingConv();
2090   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2091       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2092 
2093   // Verify that the target's LowerReturn behaved as expected.
2094   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2095          "LowerReturn didn't return a valid chain!");
2096 
2097   // Update the DAG with the new chain value resulting from return lowering.
2098   DAG.setRoot(Chain);
2099 }
2100 
2101 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2102 /// created for it, emit nodes to copy the value into the virtual
2103 /// registers.
2104 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2105   // Skip empty types
2106   if (V->getType()->isEmptyTy())
2107     return;
2108 
2109   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2110   if (VMI != FuncInfo.ValueMap.end()) {
2111     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2112     CopyValueToVirtualRegister(V, VMI->second);
2113   }
2114 }
2115 
2116 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2117 /// the current basic block, add it to ValueMap now so that we'll get a
2118 /// CopyTo/FromReg.
2119 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2120   // No need to export constants.
2121   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2122 
2123   // Already exported?
2124   if (FuncInfo.isExportedInst(V)) return;
2125 
2126   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2127   CopyValueToVirtualRegister(V, Reg);
2128 }
2129 
2130 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2131                                                      const BasicBlock *FromBB) {
2132   // The operands of the setcc have to be in this block.  We don't know
2133   // how to export them from some other block.
2134   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2135     // Can export from current BB.
2136     if (VI->getParent() == FromBB)
2137       return true;
2138 
2139     // Is already exported, noop.
2140     return FuncInfo.isExportedInst(V);
2141   }
2142 
2143   // If this is an argument, we can export it if the BB is the entry block or
2144   // if it is already exported.
2145   if (isa<Argument>(V)) {
2146     if (FromBB->isEntryBlock())
2147       return true;
2148 
2149     // Otherwise, can only export this if it is already exported.
2150     return FuncInfo.isExportedInst(V);
2151   }
2152 
2153   // Otherwise, constants can always be exported.
2154   return true;
2155 }
2156 
2157 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2158 BranchProbability
2159 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2160                                         const MachineBasicBlock *Dst) const {
2161   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2162   const BasicBlock *SrcBB = Src->getBasicBlock();
2163   const BasicBlock *DstBB = Dst->getBasicBlock();
2164   if (!BPI) {
2165     // If BPI is not available, set the default probability as 1 / N, where N is
2166     // the number of successors.
2167     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2168     return BranchProbability(1, SuccSize);
2169   }
2170   return BPI->getEdgeProbability(SrcBB, DstBB);
2171 }
2172 
2173 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2174                                                MachineBasicBlock *Dst,
2175                                                BranchProbability Prob) {
2176   if (!FuncInfo.BPI)
2177     Src->addSuccessorWithoutProb(Dst);
2178   else {
2179     if (Prob.isUnknown())
2180       Prob = getEdgeProbability(Src, Dst);
2181     Src->addSuccessor(Dst, Prob);
2182   }
2183 }
2184 
2185 static bool InBlock(const Value *V, const BasicBlock *BB) {
2186   if (const Instruction *I = dyn_cast<Instruction>(V))
2187     return I->getParent() == BB;
2188   return true;
2189 }
2190 
2191 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2192 /// This function emits a branch and is used at the leaves of an OR or an
2193 /// AND operator tree.
2194 void
2195 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2196                                                   MachineBasicBlock *TBB,
2197                                                   MachineBasicBlock *FBB,
2198                                                   MachineBasicBlock *CurBB,
2199                                                   MachineBasicBlock *SwitchBB,
2200                                                   BranchProbability TProb,
2201                                                   BranchProbability FProb,
2202                                                   bool InvertCond) {
2203   const BasicBlock *BB = CurBB->getBasicBlock();
2204 
2205   // If the leaf of the tree is a comparison, merge the condition into
2206   // the caseblock.
2207   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2208     // The operands of the cmp have to be in this block.  We don't know
2209     // how to export them from some other block.  If this is the first block
2210     // of the sequence, no exporting is needed.
2211     if (CurBB == SwitchBB ||
2212         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2213          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2214       ISD::CondCode Condition;
2215       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2216         ICmpInst::Predicate Pred =
2217             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2218         Condition = getICmpCondCode(Pred);
2219       } else {
2220         const FCmpInst *FC = cast<FCmpInst>(Cond);
2221         FCmpInst::Predicate Pred =
2222             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2223         Condition = getFCmpCondCode(Pred);
2224         if (TM.Options.NoNaNsFPMath)
2225           Condition = getFCmpCodeWithoutNaN(Condition);
2226       }
2227 
2228       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2229                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2230       SL->SwitchCases.push_back(CB);
2231       return;
2232     }
2233   }
2234 
2235   // Create a CaseBlock record representing this branch.
2236   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2237   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2238                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2239   SL->SwitchCases.push_back(CB);
2240 }
2241 
2242 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2243                                                MachineBasicBlock *TBB,
2244                                                MachineBasicBlock *FBB,
2245                                                MachineBasicBlock *CurBB,
2246                                                MachineBasicBlock *SwitchBB,
2247                                                Instruction::BinaryOps Opc,
2248                                                BranchProbability TProb,
2249                                                BranchProbability FProb,
2250                                                bool InvertCond) {
2251   // Skip over not part of the tree and remember to invert op and operands at
2252   // next level.
2253   Value *NotCond;
2254   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2255       InBlock(NotCond, CurBB->getBasicBlock())) {
2256     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2257                          !InvertCond);
2258     return;
2259   }
2260 
2261   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2262   const Value *BOpOp0, *BOpOp1;
2263   // Compute the effective opcode for Cond, taking into account whether it needs
2264   // to be inverted, e.g.
2265   //   and (not (or A, B)), C
2266   // gets lowered as
2267   //   and (and (not A, not B), C)
2268   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2269   if (BOp) {
2270     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2271                ? Instruction::And
2272                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2273                       ? Instruction::Or
2274                       : (Instruction::BinaryOps)0);
2275     if (InvertCond) {
2276       if (BOpc == Instruction::And)
2277         BOpc = Instruction::Or;
2278       else if (BOpc == Instruction::Or)
2279         BOpc = Instruction::And;
2280     }
2281   }
2282 
2283   // If this node is not part of the or/and tree, emit it as a branch.
2284   // Note that all nodes in the tree should have same opcode.
2285   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2286   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2287       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2288       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2289     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2290                                  TProb, FProb, InvertCond);
2291     return;
2292   }
2293 
2294   //  Create TmpBB after CurBB.
2295   MachineFunction::iterator BBI(CurBB);
2296   MachineFunction &MF = DAG.getMachineFunction();
2297   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2298   CurBB->getParent()->insert(++BBI, TmpBB);
2299 
2300   if (Opc == Instruction::Or) {
2301     // Codegen X | Y as:
2302     // BB1:
2303     //   jmp_if_X TBB
2304     //   jmp TmpBB
2305     // TmpBB:
2306     //   jmp_if_Y TBB
2307     //   jmp FBB
2308     //
2309 
2310     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2311     // The requirement is that
2312     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2313     //     = TrueProb for original BB.
2314     // Assuming the original probabilities are A and B, one choice is to set
2315     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2316     // A/(1+B) and 2B/(1+B). This choice assumes that
2317     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2318     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2319     // TmpBB, but the math is more complicated.
2320 
2321     auto NewTrueProb = TProb / 2;
2322     auto NewFalseProb = TProb / 2 + FProb;
2323     // Emit the LHS condition.
2324     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2325                          NewFalseProb, InvertCond);
2326 
2327     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2328     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2329     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2330     // Emit the RHS condition into TmpBB.
2331     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2332                          Probs[1], InvertCond);
2333   } else {
2334     assert(Opc == Instruction::And && "Unknown merge op!");
2335     // Codegen X & Y as:
2336     // BB1:
2337     //   jmp_if_X TmpBB
2338     //   jmp FBB
2339     // TmpBB:
2340     //   jmp_if_Y TBB
2341     //   jmp FBB
2342     //
2343     //  This requires creation of TmpBB after CurBB.
2344 
2345     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2346     // The requirement is that
2347     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2348     //     = FalseProb for original BB.
2349     // Assuming the original probabilities are A and B, one choice is to set
2350     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2351     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2352     // TrueProb for BB1 * FalseProb for TmpBB.
2353 
2354     auto NewTrueProb = TProb + FProb / 2;
2355     auto NewFalseProb = FProb / 2;
2356     // Emit the LHS condition.
2357     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2358                          NewFalseProb, InvertCond);
2359 
2360     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2361     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2362     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2363     // Emit the RHS condition into TmpBB.
2364     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2365                          Probs[1], InvertCond);
2366   }
2367 }
2368 
2369 /// If the set of cases should be emitted as a series of branches, return true.
2370 /// If we should emit this as a bunch of and/or'd together conditions, return
2371 /// false.
2372 bool
2373 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2374   if (Cases.size() != 2) return true;
2375 
2376   // If this is two comparisons of the same values or'd or and'd together, they
2377   // will get folded into a single comparison, so don't emit two blocks.
2378   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2379        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2380       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2381        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2382     return false;
2383   }
2384 
2385   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2386   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2387   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2388       Cases[0].CC == Cases[1].CC &&
2389       isa<Constant>(Cases[0].CmpRHS) &&
2390       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2391     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2392       return false;
2393     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2394       return false;
2395   }
2396 
2397   return true;
2398 }
2399 
2400 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2401   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2402 
2403   // Update machine-CFG edges.
2404   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2405 
2406   if (I.isUnconditional()) {
2407     // Update machine-CFG edges.
2408     BrMBB->addSuccessor(Succ0MBB);
2409 
2410     // If this is not a fall-through branch or optimizations are switched off,
2411     // emit the branch.
2412     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2413       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2414                               MVT::Other, getControlRoot(),
2415                               DAG.getBasicBlock(Succ0MBB)));
2416 
2417     return;
2418   }
2419 
2420   // If this condition is one of the special cases we handle, do special stuff
2421   // now.
2422   const Value *CondVal = I.getCondition();
2423   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2424 
2425   // If this is a series of conditions that are or'd or and'd together, emit
2426   // this as a sequence of branches instead of setcc's with and/or operations.
2427   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2428   // unpredictable branches, and vector extracts because those jumps are likely
2429   // expensive for any target), this should improve performance.
2430   // For example, instead of something like:
2431   //     cmp A, B
2432   //     C = seteq
2433   //     cmp D, E
2434   //     F = setle
2435   //     or C, F
2436   //     jnz foo
2437   // Emit:
2438   //     cmp A, B
2439   //     je foo
2440   //     cmp D, E
2441   //     jle foo
2442   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2443   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2444       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2445     Value *Vec;
2446     const Value *BOp0, *BOp1;
2447     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2448     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2449       Opcode = Instruction::And;
2450     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2451       Opcode = Instruction::Or;
2452 
2453     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2454                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2455       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2456                            getEdgeProbability(BrMBB, Succ0MBB),
2457                            getEdgeProbability(BrMBB, Succ1MBB),
2458                            /*InvertCond=*/false);
2459       // If the compares in later blocks need to use values not currently
2460       // exported from this block, export them now.  This block should always
2461       // be the first entry.
2462       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2463 
2464       // Allow some cases to be rejected.
2465       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2466         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2467           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2468           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2469         }
2470 
2471         // Emit the branch for this block.
2472         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2473         SL->SwitchCases.erase(SL->SwitchCases.begin());
2474         return;
2475       }
2476 
2477       // Okay, we decided not to do this, remove any inserted MBB's and clear
2478       // SwitchCases.
2479       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2480         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2481 
2482       SL->SwitchCases.clear();
2483     }
2484   }
2485 
2486   // Create a CaseBlock record representing this branch.
2487   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2488                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2489 
2490   // Use visitSwitchCase to actually insert the fast branch sequence for this
2491   // cond branch.
2492   visitSwitchCase(CB, BrMBB);
2493 }
2494 
2495 /// visitSwitchCase - Emits the necessary code to represent a single node in
2496 /// the binary search tree resulting from lowering a switch instruction.
2497 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2498                                           MachineBasicBlock *SwitchBB) {
2499   SDValue Cond;
2500   SDValue CondLHS = getValue(CB.CmpLHS);
2501   SDLoc dl = CB.DL;
2502 
2503   if (CB.CC == ISD::SETTRUE) {
2504     // Branch or fall through to TrueBB.
2505     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2506     SwitchBB->normalizeSuccProbs();
2507     if (CB.TrueBB != NextBlock(SwitchBB)) {
2508       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2509                               DAG.getBasicBlock(CB.TrueBB)));
2510     }
2511     return;
2512   }
2513 
2514   auto &TLI = DAG.getTargetLoweringInfo();
2515   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2516 
2517   // Build the setcc now.
2518   if (!CB.CmpMHS) {
2519     // Fold "(X == true)" to X and "(X == false)" to !X to
2520     // handle common cases produced by branch lowering.
2521     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2522         CB.CC == ISD::SETEQ)
2523       Cond = CondLHS;
2524     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2525              CB.CC == ISD::SETEQ) {
2526       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2527       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2528     } else {
2529       SDValue CondRHS = getValue(CB.CmpRHS);
2530 
2531       // If a pointer's DAG type is larger than its memory type then the DAG
2532       // values are zero-extended. This breaks signed comparisons so truncate
2533       // back to the underlying type before doing the compare.
2534       if (CondLHS.getValueType() != MemVT) {
2535         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2536         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2537       }
2538       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2539     }
2540   } else {
2541     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2542 
2543     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2544     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2545 
2546     SDValue CmpOp = getValue(CB.CmpMHS);
2547     EVT VT = CmpOp.getValueType();
2548 
2549     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2550       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2551                           ISD::SETLE);
2552     } else {
2553       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2554                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2555       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2556                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2557     }
2558   }
2559 
2560   // Update successor info
2561   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2562   // TrueBB and FalseBB are always different unless the incoming IR is
2563   // degenerate. This only happens when running llc on weird IR.
2564   if (CB.TrueBB != CB.FalseBB)
2565     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2566   SwitchBB->normalizeSuccProbs();
2567 
2568   // If the lhs block is the next block, invert the condition so that we can
2569   // fall through to the lhs instead of the rhs block.
2570   if (CB.TrueBB == NextBlock(SwitchBB)) {
2571     std::swap(CB.TrueBB, CB.FalseBB);
2572     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2573     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2574   }
2575 
2576   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2577                                MVT::Other, getControlRoot(), Cond,
2578                                DAG.getBasicBlock(CB.TrueBB));
2579 
2580   setValue(CurInst, BrCond);
2581 
2582   // Insert the false branch. Do this even if it's a fall through branch,
2583   // this makes it easier to do DAG optimizations which require inverting
2584   // the branch condition.
2585   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2586                        DAG.getBasicBlock(CB.FalseBB));
2587 
2588   DAG.setRoot(BrCond);
2589 }
2590 
2591 /// visitJumpTable - Emit JumpTable node in the current MBB
2592 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2593   // Emit the code for the jump table
2594   assert(JT.Reg != -1U && "Should lower JT Header first!");
2595   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2596   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2597                                      JT.Reg, PTy);
2598   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2599   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2600                                     MVT::Other, Index.getValue(1),
2601                                     Table, Index);
2602   DAG.setRoot(BrJumpTable);
2603 }
2604 
2605 /// visitJumpTableHeader - This function emits necessary code to produce index
2606 /// in the JumpTable from switch case.
2607 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2608                                                JumpTableHeader &JTH,
2609                                                MachineBasicBlock *SwitchBB) {
2610   SDLoc dl = getCurSDLoc();
2611 
2612   // Subtract the lowest switch case value from the value being switched on.
2613   SDValue SwitchOp = getValue(JTH.SValue);
2614   EVT VT = SwitchOp.getValueType();
2615   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2616                             DAG.getConstant(JTH.First, dl, VT));
2617 
2618   // The SDNode we just created, which holds the value being switched on minus
2619   // the smallest case value, needs to be copied to a virtual register so it
2620   // can be used as an index into the jump table in a subsequent basic block.
2621   // This value may be smaller or larger than the target's pointer type, and
2622   // therefore require extension or truncating.
2623   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2624   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2625 
2626   unsigned JumpTableReg =
2627       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2628   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2629                                     JumpTableReg, SwitchOp);
2630   JT.Reg = JumpTableReg;
2631 
2632   if (!JTH.FallthroughUnreachable) {
2633     // Emit the range check for the jump table, and branch to the default block
2634     // for the switch statement if the value being switched on exceeds the
2635     // largest case in the switch.
2636     SDValue CMP = DAG.getSetCC(
2637         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2638                                    Sub.getValueType()),
2639         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2640 
2641     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2642                                  MVT::Other, CopyTo, CMP,
2643                                  DAG.getBasicBlock(JT.Default));
2644 
2645     // Avoid emitting unnecessary branches to the next block.
2646     if (JT.MBB != NextBlock(SwitchBB))
2647       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2648                            DAG.getBasicBlock(JT.MBB));
2649 
2650     DAG.setRoot(BrCond);
2651   } else {
2652     // Avoid emitting unnecessary branches to the next block.
2653     if (JT.MBB != NextBlock(SwitchBB))
2654       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2655                               DAG.getBasicBlock(JT.MBB)));
2656     else
2657       DAG.setRoot(CopyTo);
2658   }
2659 }
2660 
2661 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2662 /// variable if there exists one.
2663 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2664                                  SDValue &Chain) {
2665   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2666   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2667   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2668   MachineFunction &MF = DAG.getMachineFunction();
2669   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2670   MachineSDNode *Node =
2671       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2672   if (Global) {
2673     MachinePointerInfo MPInfo(Global);
2674     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2675                  MachineMemOperand::MODereferenceable;
2676     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2677         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2678     DAG.setNodeMemRefs(Node, {MemRef});
2679   }
2680   if (PtrTy != PtrMemTy)
2681     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2682   return SDValue(Node, 0);
2683 }
2684 
2685 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2686 /// tail spliced into a stack protector check success bb.
2687 ///
2688 /// For a high level explanation of how this fits into the stack protector
2689 /// generation see the comment on the declaration of class
2690 /// StackProtectorDescriptor.
2691 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2692                                                   MachineBasicBlock *ParentBB) {
2693 
2694   // First create the loads to the guard/stack slot for the comparison.
2695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2696   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2697   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2698 
2699   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2700   int FI = MFI.getStackProtectorIndex();
2701 
2702   SDValue Guard;
2703   SDLoc dl = getCurSDLoc();
2704   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2705   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2706   Align Align =
2707       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2708 
2709   // Generate code to load the content of the guard slot.
2710   SDValue GuardVal = DAG.getLoad(
2711       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2712       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2713       MachineMemOperand::MOVolatile);
2714 
2715   if (TLI.useStackGuardXorFP())
2716     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2717 
2718   // Retrieve guard check function, nullptr if instrumentation is inlined.
2719   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2720     // The target provides a guard check function to validate the guard value.
2721     // Generate a call to that function with the content of the guard slot as
2722     // argument.
2723     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2724     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2725 
2726     TargetLowering::ArgListTy Args;
2727     TargetLowering::ArgListEntry Entry;
2728     Entry.Node = GuardVal;
2729     Entry.Ty = FnTy->getParamType(0);
2730     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2731       Entry.IsInReg = true;
2732     Args.push_back(Entry);
2733 
2734     TargetLowering::CallLoweringInfo CLI(DAG);
2735     CLI.setDebugLoc(getCurSDLoc())
2736         .setChain(DAG.getEntryNode())
2737         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2738                    getValue(GuardCheckFn), std::move(Args));
2739 
2740     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2741     DAG.setRoot(Result.second);
2742     return;
2743   }
2744 
2745   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2746   // Otherwise, emit a volatile load to retrieve the stack guard value.
2747   SDValue Chain = DAG.getEntryNode();
2748   if (TLI.useLoadStackGuardNode()) {
2749     Guard = getLoadStackGuard(DAG, dl, Chain);
2750   } else {
2751     const Value *IRGuard = TLI.getSDagStackGuard(M);
2752     SDValue GuardPtr = getValue(IRGuard);
2753 
2754     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2755                         MachinePointerInfo(IRGuard, 0), Align,
2756                         MachineMemOperand::MOVolatile);
2757   }
2758 
2759   // Perform the comparison via a getsetcc.
2760   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2761                                                         *DAG.getContext(),
2762                                                         Guard.getValueType()),
2763                              Guard, GuardVal, ISD::SETNE);
2764 
2765   // If the guard/stackslot do not equal, branch to failure MBB.
2766   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2767                                MVT::Other, GuardVal.getOperand(0),
2768                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2769   // Otherwise branch to success MBB.
2770   SDValue Br = DAG.getNode(ISD::BR, dl,
2771                            MVT::Other, BrCond,
2772                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2773 
2774   DAG.setRoot(Br);
2775 }
2776 
2777 /// Codegen the failure basic block for a stack protector check.
2778 ///
2779 /// A failure stack protector machine basic block consists simply of a call to
2780 /// __stack_chk_fail().
2781 ///
2782 /// For a high level explanation of how this fits into the stack protector
2783 /// generation see the comment on the declaration of class
2784 /// StackProtectorDescriptor.
2785 void
2786 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2787   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2788   TargetLowering::MakeLibCallOptions CallOptions;
2789   CallOptions.setDiscardResult(true);
2790   SDValue Chain =
2791       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2792                       None, CallOptions, getCurSDLoc()).second;
2793   // On PS4/PS5, the "return address" must still be within the calling
2794   // function, even if it's at the very end, so emit an explicit TRAP here.
2795   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2796   if (TM.getTargetTriple().isPS())
2797     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2798   // WebAssembly needs an unreachable instruction after a non-returning call,
2799   // because the function return type can be different from __stack_chk_fail's
2800   // return type (void).
2801   if (TM.getTargetTriple().isWasm())
2802     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2803 
2804   DAG.setRoot(Chain);
2805 }
2806 
2807 /// visitBitTestHeader - This function emits necessary code to produce value
2808 /// suitable for "bit tests"
2809 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2810                                              MachineBasicBlock *SwitchBB) {
2811   SDLoc dl = getCurSDLoc();
2812 
2813   // Subtract the minimum value.
2814   SDValue SwitchOp = getValue(B.SValue);
2815   EVT VT = SwitchOp.getValueType();
2816   SDValue RangeSub =
2817       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2818 
2819   // Determine the type of the test operands.
2820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2821   bool UsePtrType = false;
2822   if (!TLI.isTypeLegal(VT)) {
2823     UsePtrType = true;
2824   } else {
2825     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2826       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2827         // Switch table case range are encoded into series of masks.
2828         // Just use pointer type, it's guaranteed to fit.
2829         UsePtrType = true;
2830         break;
2831       }
2832   }
2833   SDValue Sub = RangeSub;
2834   if (UsePtrType) {
2835     VT = TLI.getPointerTy(DAG.getDataLayout());
2836     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2837   }
2838 
2839   B.RegVT = VT.getSimpleVT();
2840   B.Reg = FuncInfo.CreateReg(B.RegVT);
2841   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2842 
2843   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2844 
2845   if (!B.FallthroughUnreachable)
2846     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2847   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2848   SwitchBB->normalizeSuccProbs();
2849 
2850   SDValue Root = CopyTo;
2851   if (!B.FallthroughUnreachable) {
2852     // Conditional branch to the default block.
2853     SDValue RangeCmp = DAG.getSetCC(dl,
2854         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2855                                RangeSub.getValueType()),
2856         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2857         ISD::SETUGT);
2858 
2859     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2860                        DAG.getBasicBlock(B.Default));
2861   }
2862 
2863   // Avoid emitting unnecessary branches to the next block.
2864   if (MBB != NextBlock(SwitchBB))
2865     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2866 
2867   DAG.setRoot(Root);
2868 }
2869 
2870 /// visitBitTestCase - this function produces one "bit test"
2871 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2872                                            MachineBasicBlock* NextMBB,
2873                                            BranchProbability BranchProbToNext,
2874                                            unsigned Reg,
2875                                            BitTestCase &B,
2876                                            MachineBasicBlock *SwitchBB) {
2877   SDLoc dl = getCurSDLoc();
2878   MVT VT = BB.RegVT;
2879   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2880   SDValue Cmp;
2881   unsigned PopCount = countPopulation(B.Mask);
2882   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2883   if (PopCount == 1) {
2884     // Testing for a single bit; just compare the shift count with what it
2885     // would need to be to shift a 1 bit in that position.
2886     Cmp = DAG.getSetCC(
2887         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2888         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2889         ISD::SETEQ);
2890   } else if (PopCount == BB.Range) {
2891     // There is only one zero bit in the range, test for it directly.
2892     Cmp = DAG.getSetCC(
2893         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2894         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2895         ISD::SETNE);
2896   } else {
2897     // Make desired shift
2898     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2899                                     DAG.getConstant(1, dl, VT), ShiftOp);
2900 
2901     // Emit bit tests and jumps
2902     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2903                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2904     Cmp = DAG.getSetCC(
2905         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2906         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2907   }
2908 
2909   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2910   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2911   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2912   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2913   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2914   // one as they are relative probabilities (and thus work more like weights),
2915   // and hence we need to normalize them to let the sum of them become one.
2916   SwitchBB->normalizeSuccProbs();
2917 
2918   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2919                               MVT::Other, getControlRoot(),
2920                               Cmp, DAG.getBasicBlock(B.TargetBB));
2921 
2922   // Avoid emitting unnecessary branches to the next block.
2923   if (NextMBB != NextBlock(SwitchBB))
2924     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2925                         DAG.getBasicBlock(NextMBB));
2926 
2927   DAG.setRoot(BrAnd);
2928 }
2929 
2930 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2931   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2932 
2933   // Retrieve successors. Look through artificial IR level blocks like
2934   // catchswitch for successors.
2935   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2936   const BasicBlock *EHPadBB = I.getSuccessor(1);
2937 
2938   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2939   // have to do anything here to lower funclet bundles.
2940   assert(!I.hasOperandBundlesOtherThan(
2941              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2942               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2943               LLVMContext::OB_cfguardtarget,
2944               LLVMContext::OB_clang_arc_attachedcall}) &&
2945          "Cannot lower invokes with arbitrary operand bundles yet!");
2946 
2947   const Value *Callee(I.getCalledOperand());
2948   const Function *Fn = dyn_cast<Function>(Callee);
2949   if (isa<InlineAsm>(Callee))
2950     visitInlineAsm(I, EHPadBB);
2951   else if (Fn && Fn->isIntrinsic()) {
2952     switch (Fn->getIntrinsicID()) {
2953     default:
2954       llvm_unreachable("Cannot invoke this intrinsic");
2955     case Intrinsic::donothing:
2956       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2957     case Intrinsic::seh_try_begin:
2958     case Intrinsic::seh_scope_begin:
2959     case Intrinsic::seh_try_end:
2960     case Intrinsic::seh_scope_end:
2961       break;
2962     case Intrinsic::experimental_patchpoint_void:
2963     case Intrinsic::experimental_patchpoint_i64:
2964       visitPatchpoint(I, EHPadBB);
2965       break;
2966     case Intrinsic::experimental_gc_statepoint:
2967       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2968       break;
2969     case Intrinsic::wasm_rethrow: {
2970       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2971       // special because it can be invoked, so we manually lower it to a DAG
2972       // node here.
2973       SmallVector<SDValue, 8> Ops;
2974       Ops.push_back(getRoot()); // inchain
2975       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2976       Ops.push_back(
2977           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2978                                 TLI.getPointerTy(DAG.getDataLayout())));
2979       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2980       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2981       break;
2982     }
2983     }
2984   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2985     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2986     // Eventually we will support lowering the @llvm.experimental.deoptimize
2987     // intrinsic, and right now there are no plans to support other intrinsics
2988     // with deopt state.
2989     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2990   } else {
2991     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2992   }
2993 
2994   // If the value of the invoke is used outside of its defining block, make it
2995   // available as a virtual register.
2996   // We already took care of the exported value for the statepoint instruction
2997   // during call to the LowerStatepoint.
2998   if (!isa<GCStatepointInst>(I)) {
2999     CopyToExportRegsIfNeeded(&I);
3000   }
3001 
3002   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3003   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3004   BranchProbability EHPadBBProb =
3005       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3006           : BranchProbability::getZero();
3007   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3008 
3009   // Update successor info.
3010   addSuccessorWithProb(InvokeMBB, Return);
3011   for (auto &UnwindDest : UnwindDests) {
3012     UnwindDest.first->setIsEHPad();
3013     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3014   }
3015   InvokeMBB->normalizeSuccProbs();
3016 
3017   // Drop into normal successor.
3018   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3019                           DAG.getBasicBlock(Return)));
3020 }
3021 
3022 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3023   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3024 
3025   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3026   // have to do anything here to lower funclet bundles.
3027   assert(!I.hasOperandBundlesOtherThan(
3028              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3029          "Cannot lower callbrs with arbitrary operand bundles yet!");
3030 
3031   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3032   visitInlineAsm(I);
3033   CopyToExportRegsIfNeeded(&I);
3034 
3035   // Retrieve successors.
3036   SmallPtrSet<BasicBlock *, 8> Dests;
3037   Dests.insert(I.getDefaultDest());
3038   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3039 
3040   // Update successor info.
3041   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3042   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3043     BasicBlock *Dest = I.getIndirectDest(i);
3044     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3045     Target->setIsInlineAsmBrIndirectTarget();
3046     Target->setMachineBlockAddressTaken();
3047     Target->setLabelMustBeEmitted();
3048     // Don't add duplicate machine successors.
3049     if (Dests.insert(Dest).second)
3050       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3051   }
3052   CallBrMBB->normalizeSuccProbs();
3053 
3054   // Drop into default successor.
3055   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3056                           MVT::Other, getControlRoot(),
3057                           DAG.getBasicBlock(Return)));
3058 }
3059 
3060 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3061   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3062 }
3063 
3064 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3065   assert(FuncInfo.MBB->isEHPad() &&
3066          "Call to landingpad not in landing pad!");
3067 
3068   // If there aren't registers to copy the values into (e.g., during SjLj
3069   // exceptions), then don't bother to create these DAG nodes.
3070   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3071   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3072   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3073       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3074     return;
3075 
3076   // If landingpad's return type is token type, we don't create DAG nodes
3077   // for its exception pointer and selector value. The extraction of exception
3078   // pointer or selector value from token type landingpads is not currently
3079   // supported.
3080   if (LP.getType()->isTokenTy())
3081     return;
3082 
3083   SmallVector<EVT, 2> ValueVTs;
3084   SDLoc dl = getCurSDLoc();
3085   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3086   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3087 
3088   // Get the two live-in registers as SDValues. The physregs have already been
3089   // copied into virtual registers.
3090   SDValue Ops[2];
3091   if (FuncInfo.ExceptionPointerVirtReg) {
3092     Ops[0] = DAG.getZExtOrTrunc(
3093         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3094                            FuncInfo.ExceptionPointerVirtReg,
3095                            TLI.getPointerTy(DAG.getDataLayout())),
3096         dl, ValueVTs[0]);
3097   } else {
3098     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3099   }
3100   Ops[1] = DAG.getZExtOrTrunc(
3101       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3102                          FuncInfo.ExceptionSelectorVirtReg,
3103                          TLI.getPointerTy(DAG.getDataLayout())),
3104       dl, ValueVTs[1]);
3105 
3106   // Merge into one.
3107   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3108                             DAG.getVTList(ValueVTs), Ops);
3109   setValue(&LP, Res);
3110 }
3111 
3112 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3113                                            MachineBasicBlock *Last) {
3114   // Update JTCases.
3115   for (JumpTableBlock &JTB : SL->JTCases)
3116     if (JTB.first.HeaderBB == First)
3117       JTB.first.HeaderBB = Last;
3118 
3119   // Update BitTestCases.
3120   for (BitTestBlock &BTB : SL->BitTestCases)
3121     if (BTB.Parent == First)
3122       BTB.Parent = Last;
3123 }
3124 
3125 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3126   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3127 
3128   // Update machine-CFG edges with unique successors.
3129   SmallSet<BasicBlock*, 32> Done;
3130   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3131     BasicBlock *BB = I.getSuccessor(i);
3132     bool Inserted = Done.insert(BB).second;
3133     if (!Inserted)
3134         continue;
3135 
3136     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3137     addSuccessorWithProb(IndirectBrMBB, Succ);
3138   }
3139   IndirectBrMBB->normalizeSuccProbs();
3140 
3141   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3142                           MVT::Other, getControlRoot(),
3143                           getValue(I.getAddress())));
3144 }
3145 
3146 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3147   if (!DAG.getTarget().Options.TrapUnreachable)
3148     return;
3149 
3150   // We may be able to ignore unreachable behind a noreturn call.
3151   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3152     const BasicBlock &BB = *I.getParent();
3153     if (&I != &BB.front()) {
3154       BasicBlock::const_iterator PredI =
3155         std::prev(BasicBlock::const_iterator(&I));
3156       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3157         if (Call->doesNotReturn())
3158           return;
3159       }
3160     }
3161   }
3162 
3163   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3164 }
3165 
3166 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3167   SDNodeFlags Flags;
3168   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3169     Flags.copyFMF(*FPOp);
3170 
3171   SDValue Op = getValue(I.getOperand(0));
3172   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3173                                     Op, Flags);
3174   setValue(&I, UnNodeValue);
3175 }
3176 
3177 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3178   SDNodeFlags Flags;
3179   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3180     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3181     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3182   }
3183   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3184     Flags.setExact(ExactOp->isExact());
3185   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3186     Flags.copyFMF(*FPOp);
3187 
3188   SDValue Op1 = getValue(I.getOperand(0));
3189   SDValue Op2 = getValue(I.getOperand(1));
3190   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3191                                      Op1, Op2, Flags);
3192   setValue(&I, BinNodeValue);
3193 }
3194 
3195 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3196   SDValue Op1 = getValue(I.getOperand(0));
3197   SDValue Op2 = getValue(I.getOperand(1));
3198 
3199   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3200       Op1.getValueType(), DAG.getDataLayout());
3201 
3202   // Coerce the shift amount to the right type if we can. This exposes the
3203   // truncate or zext to optimization early.
3204   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3205     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3206            "Unexpected shift type");
3207     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3208   }
3209 
3210   bool nuw = false;
3211   bool nsw = false;
3212   bool exact = false;
3213 
3214   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3215 
3216     if (const OverflowingBinaryOperator *OFBinOp =
3217             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3218       nuw = OFBinOp->hasNoUnsignedWrap();
3219       nsw = OFBinOp->hasNoSignedWrap();
3220     }
3221     if (const PossiblyExactOperator *ExactOp =
3222             dyn_cast<const PossiblyExactOperator>(&I))
3223       exact = ExactOp->isExact();
3224   }
3225   SDNodeFlags Flags;
3226   Flags.setExact(exact);
3227   Flags.setNoSignedWrap(nsw);
3228   Flags.setNoUnsignedWrap(nuw);
3229   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3230                             Flags);
3231   setValue(&I, Res);
3232 }
3233 
3234 void SelectionDAGBuilder::visitSDiv(const User &I) {
3235   SDValue Op1 = getValue(I.getOperand(0));
3236   SDValue Op2 = getValue(I.getOperand(1));
3237 
3238   SDNodeFlags Flags;
3239   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3240                  cast<PossiblyExactOperator>(&I)->isExact());
3241   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3242                            Op2, Flags));
3243 }
3244 
3245 void SelectionDAGBuilder::visitICmp(const User &I) {
3246   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3247   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3248     predicate = IC->getPredicate();
3249   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3250     predicate = ICmpInst::Predicate(IC->getPredicate());
3251   SDValue Op1 = getValue(I.getOperand(0));
3252   SDValue Op2 = getValue(I.getOperand(1));
3253   ISD::CondCode Opcode = getICmpCondCode(predicate);
3254 
3255   auto &TLI = DAG.getTargetLoweringInfo();
3256   EVT MemVT =
3257       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3258 
3259   // If a pointer's DAG type is larger than its memory type then the DAG values
3260   // are zero-extended. This breaks signed comparisons so truncate back to the
3261   // underlying type before doing the compare.
3262   if (Op1.getValueType() != MemVT) {
3263     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3264     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3265   }
3266 
3267   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3268                                                         I.getType());
3269   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3270 }
3271 
3272 void SelectionDAGBuilder::visitFCmp(const User &I) {
3273   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3274   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3275     predicate = FC->getPredicate();
3276   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3277     predicate = FCmpInst::Predicate(FC->getPredicate());
3278   SDValue Op1 = getValue(I.getOperand(0));
3279   SDValue Op2 = getValue(I.getOperand(1));
3280 
3281   ISD::CondCode Condition = getFCmpCondCode(predicate);
3282   auto *FPMO = cast<FPMathOperator>(&I);
3283   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3284     Condition = getFCmpCodeWithoutNaN(Condition);
3285 
3286   SDNodeFlags Flags;
3287   Flags.copyFMF(*FPMO);
3288   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3289 
3290   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3291                                                         I.getType());
3292   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3293 }
3294 
3295 // Check if the condition of the select has one use or two users that are both
3296 // selects with the same condition.
3297 static bool hasOnlySelectUsers(const Value *Cond) {
3298   return llvm::all_of(Cond->users(), [](const Value *V) {
3299     return isa<SelectInst>(V);
3300   });
3301 }
3302 
3303 void SelectionDAGBuilder::visitSelect(const User &I) {
3304   SmallVector<EVT, 4> ValueVTs;
3305   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3306                   ValueVTs);
3307   unsigned NumValues = ValueVTs.size();
3308   if (NumValues == 0) return;
3309 
3310   SmallVector<SDValue, 4> Values(NumValues);
3311   SDValue Cond     = getValue(I.getOperand(0));
3312   SDValue LHSVal   = getValue(I.getOperand(1));
3313   SDValue RHSVal   = getValue(I.getOperand(2));
3314   SmallVector<SDValue, 1> BaseOps(1, Cond);
3315   ISD::NodeType OpCode =
3316       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3317 
3318   bool IsUnaryAbs = false;
3319   bool Negate = false;
3320 
3321   SDNodeFlags Flags;
3322   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3323     Flags.copyFMF(*FPOp);
3324 
3325   // Min/max matching is only viable if all output VTs are the same.
3326   if (all_equal(ValueVTs)) {
3327     EVT VT = ValueVTs[0];
3328     LLVMContext &Ctx = *DAG.getContext();
3329     auto &TLI = DAG.getTargetLoweringInfo();
3330 
3331     // We care about the legality of the operation after it has been type
3332     // legalized.
3333     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3334       VT = TLI.getTypeToTransformTo(Ctx, VT);
3335 
3336     // If the vselect is legal, assume we want to leave this as a vector setcc +
3337     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3338     // min/max is legal on the scalar type.
3339     bool UseScalarMinMax = VT.isVector() &&
3340       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3341 
3342     Value *LHS, *RHS;
3343     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3344     ISD::NodeType Opc = ISD::DELETED_NODE;
3345     switch (SPR.Flavor) {
3346     case SPF_UMAX:    Opc = ISD::UMAX; break;
3347     case SPF_UMIN:    Opc = ISD::UMIN; break;
3348     case SPF_SMAX:    Opc = ISD::SMAX; break;
3349     case SPF_SMIN:    Opc = ISD::SMIN; break;
3350     case SPF_FMINNUM:
3351       switch (SPR.NaNBehavior) {
3352       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3353       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3354       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3355       case SPNB_RETURNS_ANY: {
3356         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3357           Opc = ISD::FMINNUM;
3358         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3359           Opc = ISD::FMINIMUM;
3360         else if (UseScalarMinMax)
3361           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3362             ISD::FMINNUM : ISD::FMINIMUM;
3363         break;
3364       }
3365       }
3366       break;
3367     case SPF_FMAXNUM:
3368       switch (SPR.NaNBehavior) {
3369       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3370       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3371       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3372       case SPNB_RETURNS_ANY:
3373 
3374         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3375           Opc = ISD::FMAXNUM;
3376         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3377           Opc = ISD::FMAXIMUM;
3378         else if (UseScalarMinMax)
3379           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3380             ISD::FMAXNUM : ISD::FMAXIMUM;
3381         break;
3382       }
3383       break;
3384     case SPF_NABS:
3385       Negate = true;
3386       [[fallthrough]];
3387     case SPF_ABS:
3388       IsUnaryAbs = true;
3389       Opc = ISD::ABS;
3390       break;
3391     default: break;
3392     }
3393 
3394     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3395         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3396          (UseScalarMinMax &&
3397           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3398         // If the underlying comparison instruction is used by any other
3399         // instruction, the consumed instructions won't be destroyed, so it is
3400         // not profitable to convert to a min/max.
3401         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3402       OpCode = Opc;
3403       LHSVal = getValue(LHS);
3404       RHSVal = getValue(RHS);
3405       BaseOps.clear();
3406     }
3407 
3408     if (IsUnaryAbs) {
3409       OpCode = Opc;
3410       LHSVal = getValue(LHS);
3411       BaseOps.clear();
3412     }
3413   }
3414 
3415   if (IsUnaryAbs) {
3416     for (unsigned i = 0; i != NumValues; ++i) {
3417       SDLoc dl = getCurSDLoc();
3418       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3419       Values[i] =
3420           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3421       if (Negate)
3422         Values[i] = DAG.getNegative(Values[i], dl, VT);
3423     }
3424   } else {
3425     for (unsigned i = 0; i != NumValues; ++i) {
3426       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3427       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3428       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3429       Values[i] = DAG.getNode(
3430           OpCode, getCurSDLoc(),
3431           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3432     }
3433   }
3434 
3435   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3436                            DAG.getVTList(ValueVTs), Values));
3437 }
3438 
3439 void SelectionDAGBuilder::visitTrunc(const User &I) {
3440   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3441   SDValue N = getValue(I.getOperand(0));
3442   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3443                                                         I.getType());
3444   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3445 }
3446 
3447 void SelectionDAGBuilder::visitZExt(const User &I) {
3448   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3449   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3450   SDValue N = getValue(I.getOperand(0));
3451   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3452                                                         I.getType());
3453   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3454 }
3455 
3456 void SelectionDAGBuilder::visitSExt(const User &I) {
3457   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3458   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3459   SDValue N = getValue(I.getOperand(0));
3460   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3461                                                         I.getType());
3462   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3463 }
3464 
3465 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3466   // FPTrunc is never a no-op cast, no need to check
3467   SDValue N = getValue(I.getOperand(0));
3468   SDLoc dl = getCurSDLoc();
3469   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3470   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3471   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3472                            DAG.getTargetConstant(
3473                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3474 }
3475 
3476 void SelectionDAGBuilder::visitFPExt(const User &I) {
3477   // FPExt is never a no-op cast, no need to check
3478   SDValue N = getValue(I.getOperand(0));
3479   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3480                                                         I.getType());
3481   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3482 }
3483 
3484 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3485   // FPToUI is never a no-op cast, no need to check
3486   SDValue N = getValue(I.getOperand(0));
3487   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3488                                                         I.getType());
3489   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3490 }
3491 
3492 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3493   // FPToSI is never a no-op cast, no need to check
3494   SDValue N = getValue(I.getOperand(0));
3495   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3496                                                         I.getType());
3497   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3498 }
3499 
3500 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3501   // UIToFP is never a no-op cast, no need to check
3502   SDValue N = getValue(I.getOperand(0));
3503   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3504                                                         I.getType());
3505   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3506 }
3507 
3508 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3509   // SIToFP is never a no-op cast, no need to check
3510   SDValue N = getValue(I.getOperand(0));
3511   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3512                                                         I.getType());
3513   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3514 }
3515 
3516 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3517   // What to do depends on the size of the integer and the size of the pointer.
3518   // We can either truncate, zero extend, or no-op, accordingly.
3519   SDValue N = getValue(I.getOperand(0));
3520   auto &TLI = DAG.getTargetLoweringInfo();
3521   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3522                                                         I.getType());
3523   EVT PtrMemVT =
3524       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3525   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3526   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3527   setValue(&I, N);
3528 }
3529 
3530 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3531   // What to do depends on the size of the integer and the size of the pointer.
3532   // We can either truncate, zero extend, or no-op, accordingly.
3533   SDValue N = getValue(I.getOperand(0));
3534   auto &TLI = DAG.getTargetLoweringInfo();
3535   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3536   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3537   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3538   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3539   setValue(&I, N);
3540 }
3541 
3542 void SelectionDAGBuilder::visitBitCast(const User &I) {
3543   SDValue N = getValue(I.getOperand(0));
3544   SDLoc dl = getCurSDLoc();
3545   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3546                                                         I.getType());
3547 
3548   // BitCast assures us that source and destination are the same size so this is
3549   // either a BITCAST or a no-op.
3550   if (DestVT != N.getValueType())
3551     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3552                              DestVT, N)); // convert types.
3553   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3554   // might fold any kind of constant expression to an integer constant and that
3555   // is not what we are looking for. Only recognize a bitcast of a genuine
3556   // constant integer as an opaque constant.
3557   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3558     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3559                                  /*isOpaque*/true));
3560   else
3561     setValue(&I, N);            // noop cast.
3562 }
3563 
3564 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3565   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3566   const Value *SV = I.getOperand(0);
3567   SDValue N = getValue(SV);
3568   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3569 
3570   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3571   unsigned DestAS = I.getType()->getPointerAddressSpace();
3572 
3573   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3574     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3575 
3576   setValue(&I, N);
3577 }
3578 
3579 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3580   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3581   SDValue InVec = getValue(I.getOperand(0));
3582   SDValue InVal = getValue(I.getOperand(1));
3583   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3584                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3585   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3586                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3587                            InVec, InVal, InIdx));
3588 }
3589 
3590 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3591   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3592   SDValue InVec = getValue(I.getOperand(0));
3593   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3594                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3595   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3596                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3597                            InVec, InIdx));
3598 }
3599 
3600 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3601   SDValue Src1 = getValue(I.getOperand(0));
3602   SDValue Src2 = getValue(I.getOperand(1));
3603   ArrayRef<int> Mask;
3604   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3605     Mask = SVI->getShuffleMask();
3606   else
3607     Mask = cast<ConstantExpr>(I).getShuffleMask();
3608   SDLoc DL = getCurSDLoc();
3609   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3610   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3611   EVT SrcVT = Src1.getValueType();
3612 
3613   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3614       VT.isScalableVector()) {
3615     // Canonical splat form of first element of first input vector.
3616     SDValue FirstElt =
3617         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3618                     DAG.getVectorIdxConstant(0, DL));
3619     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3620     return;
3621   }
3622 
3623   // For now, we only handle splats for scalable vectors.
3624   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3625   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3626   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3627 
3628   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3629   unsigned MaskNumElts = Mask.size();
3630 
3631   if (SrcNumElts == MaskNumElts) {
3632     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3633     return;
3634   }
3635 
3636   // Normalize the shuffle vector since mask and vector length don't match.
3637   if (SrcNumElts < MaskNumElts) {
3638     // Mask is longer than the source vectors. We can use concatenate vector to
3639     // make the mask and vectors lengths match.
3640 
3641     if (MaskNumElts % SrcNumElts == 0) {
3642       // Mask length is a multiple of the source vector length.
3643       // Check if the shuffle is some kind of concatenation of the input
3644       // vectors.
3645       unsigned NumConcat = MaskNumElts / SrcNumElts;
3646       bool IsConcat = true;
3647       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3648       for (unsigned i = 0; i != MaskNumElts; ++i) {
3649         int Idx = Mask[i];
3650         if (Idx < 0)
3651           continue;
3652         // Ensure the indices in each SrcVT sized piece are sequential and that
3653         // the same source is used for the whole piece.
3654         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3655             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3656              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3657           IsConcat = false;
3658           break;
3659         }
3660         // Remember which source this index came from.
3661         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3662       }
3663 
3664       // The shuffle is concatenating multiple vectors together. Just emit
3665       // a CONCAT_VECTORS operation.
3666       if (IsConcat) {
3667         SmallVector<SDValue, 8> ConcatOps;
3668         for (auto Src : ConcatSrcs) {
3669           if (Src < 0)
3670             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3671           else if (Src == 0)
3672             ConcatOps.push_back(Src1);
3673           else
3674             ConcatOps.push_back(Src2);
3675         }
3676         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3677         return;
3678       }
3679     }
3680 
3681     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3682     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3683     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3684                                     PaddedMaskNumElts);
3685 
3686     // Pad both vectors with undefs to make them the same length as the mask.
3687     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3688 
3689     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3690     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3691     MOps1[0] = Src1;
3692     MOps2[0] = Src2;
3693 
3694     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3695     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3696 
3697     // Readjust mask for new input vector length.
3698     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3699     for (unsigned i = 0; i != MaskNumElts; ++i) {
3700       int Idx = Mask[i];
3701       if (Idx >= (int)SrcNumElts)
3702         Idx -= SrcNumElts - PaddedMaskNumElts;
3703       MappedOps[i] = Idx;
3704     }
3705 
3706     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3707 
3708     // If the concatenated vector was padded, extract a subvector with the
3709     // correct number of elements.
3710     if (MaskNumElts != PaddedMaskNumElts)
3711       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3712                            DAG.getVectorIdxConstant(0, DL));
3713 
3714     setValue(&I, Result);
3715     return;
3716   }
3717 
3718   if (SrcNumElts > MaskNumElts) {
3719     // Analyze the access pattern of the vector to see if we can extract
3720     // two subvectors and do the shuffle.
3721     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3722     bool CanExtract = true;
3723     for (int Idx : Mask) {
3724       unsigned Input = 0;
3725       if (Idx < 0)
3726         continue;
3727 
3728       if (Idx >= (int)SrcNumElts) {
3729         Input = 1;
3730         Idx -= SrcNumElts;
3731       }
3732 
3733       // If all the indices come from the same MaskNumElts sized portion of
3734       // the sources we can use extract. Also make sure the extract wouldn't
3735       // extract past the end of the source.
3736       int NewStartIdx = alignDown(Idx, MaskNumElts);
3737       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3738           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3739         CanExtract = false;
3740       // Make sure we always update StartIdx as we use it to track if all
3741       // elements are undef.
3742       StartIdx[Input] = NewStartIdx;
3743     }
3744 
3745     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3746       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3747       return;
3748     }
3749     if (CanExtract) {
3750       // Extract appropriate subvector and generate a vector shuffle
3751       for (unsigned Input = 0; Input < 2; ++Input) {
3752         SDValue &Src = Input == 0 ? Src1 : Src2;
3753         if (StartIdx[Input] < 0)
3754           Src = DAG.getUNDEF(VT);
3755         else {
3756           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3757                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3758         }
3759       }
3760 
3761       // Calculate new mask.
3762       SmallVector<int, 8> MappedOps(Mask);
3763       for (int &Idx : MappedOps) {
3764         if (Idx >= (int)SrcNumElts)
3765           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3766         else if (Idx >= 0)
3767           Idx -= StartIdx[0];
3768       }
3769 
3770       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3771       return;
3772     }
3773   }
3774 
3775   // We can't use either concat vectors or extract subvectors so fall back to
3776   // replacing the shuffle with extract and build vector.
3777   // to insert and build vector.
3778   EVT EltVT = VT.getVectorElementType();
3779   SmallVector<SDValue,8> Ops;
3780   for (int Idx : Mask) {
3781     SDValue Res;
3782 
3783     if (Idx < 0) {
3784       Res = DAG.getUNDEF(EltVT);
3785     } else {
3786       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3787       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3788 
3789       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3790                         DAG.getVectorIdxConstant(Idx, DL));
3791     }
3792 
3793     Ops.push_back(Res);
3794   }
3795 
3796   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3797 }
3798 
3799 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
3800   ArrayRef<unsigned> Indices = I.getIndices();
3801   const Value *Op0 = I.getOperand(0);
3802   const Value *Op1 = I.getOperand(1);
3803   Type *AggTy = I.getType();
3804   Type *ValTy = Op1->getType();
3805   bool IntoUndef = isa<UndefValue>(Op0);
3806   bool FromUndef = isa<UndefValue>(Op1);
3807 
3808   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3809 
3810   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3811   SmallVector<EVT, 4> AggValueVTs;
3812   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3813   SmallVector<EVT, 4> ValValueVTs;
3814   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3815 
3816   unsigned NumAggValues = AggValueVTs.size();
3817   unsigned NumValValues = ValValueVTs.size();
3818   SmallVector<SDValue, 4> Values(NumAggValues);
3819 
3820   // Ignore an insertvalue that produces an empty object
3821   if (!NumAggValues) {
3822     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3823     return;
3824   }
3825 
3826   SDValue Agg = getValue(Op0);
3827   unsigned i = 0;
3828   // Copy the beginning value(s) from the original aggregate.
3829   for (; i != LinearIndex; ++i)
3830     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3831                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3832   // Copy values from the inserted value(s).
3833   if (NumValValues) {
3834     SDValue Val = getValue(Op1);
3835     for (; i != LinearIndex + NumValValues; ++i)
3836       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3837                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3838   }
3839   // Copy remaining value(s) from the original aggregate.
3840   for (; i != NumAggValues; ++i)
3841     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3842                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3843 
3844   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3845                            DAG.getVTList(AggValueVTs), Values));
3846 }
3847 
3848 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
3849   ArrayRef<unsigned> Indices = I.getIndices();
3850   const Value *Op0 = I.getOperand(0);
3851   Type *AggTy = Op0->getType();
3852   Type *ValTy = I.getType();
3853   bool OutOfUndef = isa<UndefValue>(Op0);
3854 
3855   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3856 
3857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3858   SmallVector<EVT, 4> ValValueVTs;
3859   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3860 
3861   unsigned NumValValues = ValValueVTs.size();
3862 
3863   // Ignore a extractvalue that produces an empty object
3864   if (!NumValValues) {
3865     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3866     return;
3867   }
3868 
3869   SmallVector<SDValue, 4> Values(NumValValues);
3870 
3871   SDValue Agg = getValue(Op0);
3872   // Copy out the selected value(s).
3873   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3874     Values[i - LinearIndex] =
3875       OutOfUndef ?
3876         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3877         SDValue(Agg.getNode(), Agg.getResNo() + i);
3878 
3879   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3880                            DAG.getVTList(ValValueVTs), Values));
3881 }
3882 
3883 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3884   Value *Op0 = I.getOperand(0);
3885   // Note that the pointer operand may be a vector of pointers. Take the scalar
3886   // element which holds a pointer.
3887   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3888   SDValue N = getValue(Op0);
3889   SDLoc dl = getCurSDLoc();
3890   auto &TLI = DAG.getTargetLoweringInfo();
3891 
3892   // Normalize Vector GEP - all scalar operands should be converted to the
3893   // splat vector.
3894   bool IsVectorGEP = I.getType()->isVectorTy();
3895   ElementCount VectorElementCount =
3896       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3897                   : ElementCount::getFixed(0);
3898 
3899   if (IsVectorGEP && !N.getValueType().isVector()) {
3900     LLVMContext &Context = *DAG.getContext();
3901     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3902     N = DAG.getSplat(VT, dl, N);
3903   }
3904 
3905   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3906        GTI != E; ++GTI) {
3907     const Value *Idx = GTI.getOperand();
3908     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3909       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3910       if (Field) {
3911         // N = N + Offset
3912         uint64_t Offset =
3913             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3914 
3915         // In an inbounds GEP with an offset that is nonnegative even when
3916         // interpreted as signed, assume there is no unsigned overflow.
3917         SDNodeFlags Flags;
3918         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3919           Flags.setNoUnsignedWrap(true);
3920 
3921         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3922                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3923       }
3924     } else {
3925       // IdxSize is the width of the arithmetic according to IR semantics.
3926       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3927       // (and fix up the result later).
3928       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3929       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3930       TypeSize ElementSize =
3931           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3932       // We intentionally mask away the high bits here; ElementSize may not
3933       // fit in IdxTy.
3934       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3935       bool ElementScalable = ElementSize.isScalable();
3936 
3937       // If this is a scalar constant or a splat vector of constants,
3938       // handle it quickly.
3939       const auto *C = dyn_cast<Constant>(Idx);
3940       if (C && isa<VectorType>(C->getType()))
3941         C = C->getSplatValue();
3942 
3943       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3944       if (CI && CI->isZero())
3945         continue;
3946       if (CI && !ElementScalable) {
3947         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3948         LLVMContext &Context = *DAG.getContext();
3949         SDValue OffsVal;
3950         if (IsVectorGEP)
3951           OffsVal = DAG.getConstant(
3952               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3953         else
3954           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3955 
3956         // In an inbounds GEP with an offset that is nonnegative even when
3957         // interpreted as signed, assume there is no unsigned overflow.
3958         SDNodeFlags Flags;
3959         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3960           Flags.setNoUnsignedWrap(true);
3961 
3962         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3963 
3964         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3965         continue;
3966       }
3967 
3968       // N = N + Idx * ElementMul;
3969       SDValue IdxN = getValue(Idx);
3970 
3971       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3972         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3973                                   VectorElementCount);
3974         IdxN = DAG.getSplat(VT, dl, IdxN);
3975       }
3976 
3977       // If the index is smaller or larger than intptr_t, truncate or extend
3978       // it.
3979       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3980 
3981       if (ElementScalable) {
3982         EVT VScaleTy = N.getValueType().getScalarType();
3983         SDValue VScale = DAG.getNode(
3984             ISD::VSCALE, dl, VScaleTy,
3985             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3986         if (IsVectorGEP)
3987           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3988         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3989       } else {
3990         // If this is a multiply by a power of two, turn it into a shl
3991         // immediately.  This is a very common case.
3992         if (ElementMul != 1) {
3993           if (ElementMul.isPowerOf2()) {
3994             unsigned Amt = ElementMul.logBase2();
3995             IdxN = DAG.getNode(ISD::SHL, dl,
3996                                N.getValueType(), IdxN,
3997                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3998           } else {
3999             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4000                                             IdxN.getValueType());
4001             IdxN = DAG.getNode(ISD::MUL, dl,
4002                                N.getValueType(), IdxN, Scale);
4003           }
4004         }
4005       }
4006 
4007       N = DAG.getNode(ISD::ADD, dl,
4008                       N.getValueType(), N, IdxN);
4009     }
4010   }
4011 
4012   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4013   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4014   if (IsVectorGEP) {
4015     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4016     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4017   }
4018 
4019   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4020     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4021 
4022   setValue(&I, N);
4023 }
4024 
4025 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4026   // If this is a fixed sized alloca in the entry block of the function,
4027   // allocate it statically on the stack.
4028   if (FuncInfo.StaticAllocaMap.count(&I))
4029     return;   // getValue will auto-populate this.
4030 
4031   SDLoc dl = getCurSDLoc();
4032   Type *Ty = I.getAllocatedType();
4033   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4034   auto &DL = DAG.getDataLayout();
4035   TypeSize TySize = DL.getTypeAllocSize(Ty);
4036   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4037 
4038   SDValue AllocSize = getValue(I.getArraySize());
4039 
4040   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4041   if (AllocSize.getValueType() != IntPtr)
4042     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4043 
4044   if (TySize.isScalable())
4045     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4046                             DAG.getVScale(dl, IntPtr,
4047                                           APInt(IntPtr.getScalarSizeInBits(),
4048                                                 TySize.getKnownMinValue())));
4049   else
4050     AllocSize =
4051         DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4052                     DAG.getConstant(TySize.getFixedValue(), dl, IntPtr));
4053 
4054   // Handle alignment.  If the requested alignment is less than or equal to
4055   // the stack alignment, ignore it.  If the size is greater than or equal to
4056   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4057   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4058   if (*Alignment <= StackAlign)
4059     Alignment = None;
4060 
4061   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4062   // Round the size of the allocation up to the stack alignment size
4063   // by add SA-1 to the size. This doesn't overflow because we're computing
4064   // an address inside an alloca.
4065   SDNodeFlags Flags;
4066   Flags.setNoUnsignedWrap(true);
4067   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4068                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4069 
4070   // Mask out the low bits for alignment purposes.
4071   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4072                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4073 
4074   SDValue Ops[] = {
4075       getRoot(), AllocSize,
4076       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4077   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4078   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4079   setValue(&I, DSA);
4080   DAG.setRoot(DSA.getValue(1));
4081 
4082   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4083 }
4084 
4085 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4086   if (I.isAtomic())
4087     return visitAtomicLoad(I);
4088 
4089   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4090   const Value *SV = I.getOperand(0);
4091   if (TLI.supportSwiftError()) {
4092     // Swifterror values can come from either a function parameter with
4093     // swifterror attribute or an alloca with swifterror attribute.
4094     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4095       if (Arg->hasSwiftErrorAttr())
4096         return visitLoadFromSwiftError(I);
4097     }
4098 
4099     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4100       if (Alloca->isSwiftError())
4101         return visitLoadFromSwiftError(I);
4102     }
4103   }
4104 
4105   SDValue Ptr = getValue(SV);
4106 
4107   Type *Ty = I.getType();
4108   SmallVector<EVT, 4> ValueVTs, MemVTs;
4109   SmallVector<uint64_t, 4> Offsets;
4110   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4111   unsigned NumValues = ValueVTs.size();
4112   if (NumValues == 0)
4113     return;
4114 
4115   Align Alignment = I.getAlign();
4116   AAMDNodes AAInfo = I.getAAMetadata();
4117   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4118   bool isVolatile = I.isVolatile();
4119   MachineMemOperand::Flags MMOFlags =
4120       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4121 
4122   SDValue Root;
4123   bool ConstantMemory = false;
4124   if (isVolatile)
4125     // Serialize volatile loads with other side effects.
4126     Root = getRoot();
4127   else if (NumValues > MaxParallelChains)
4128     Root = getMemoryRoot();
4129   else if (AA &&
4130            AA->pointsToConstantMemory(MemoryLocation(
4131                SV,
4132                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4133                AAInfo))) {
4134     // Do not serialize (non-volatile) loads of constant memory with anything.
4135     Root = DAG.getEntryNode();
4136     ConstantMemory = true;
4137     MMOFlags |= MachineMemOperand::MOInvariant;
4138   } else {
4139     // Do not serialize non-volatile loads against each other.
4140     Root = DAG.getRoot();
4141   }
4142 
4143   if (isDereferenceableAndAlignedPointer(SV, Ty, Alignment, DAG.getDataLayout(),
4144                                          &I, AC, nullptr, LibInfo))
4145     MMOFlags |= MachineMemOperand::MODereferenceable;
4146 
4147   SDLoc dl = getCurSDLoc();
4148 
4149   if (isVolatile)
4150     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4151 
4152   // An aggregate load cannot wrap around the address space, so offsets to its
4153   // parts don't wrap either.
4154   SDNodeFlags Flags;
4155   Flags.setNoUnsignedWrap(true);
4156 
4157   SmallVector<SDValue, 4> Values(NumValues);
4158   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4159   EVT PtrVT = Ptr.getValueType();
4160 
4161   unsigned ChainI = 0;
4162   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4163     // Serializing loads here may result in excessive register pressure, and
4164     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4165     // could recover a bit by hoisting nodes upward in the chain by recognizing
4166     // they are side-effect free or do not alias. The optimizer should really
4167     // avoid this case by converting large object/array copies to llvm.memcpy
4168     // (MaxParallelChains should always remain as failsafe).
4169     if (ChainI == MaxParallelChains) {
4170       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4171       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4172                                   makeArrayRef(Chains.data(), ChainI));
4173       Root = Chain;
4174       ChainI = 0;
4175     }
4176     SDValue A = DAG.getNode(ISD::ADD, dl,
4177                             PtrVT, Ptr,
4178                             DAG.getConstant(Offsets[i], dl, PtrVT),
4179                             Flags);
4180 
4181     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4182                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4183                             MMOFlags, AAInfo, Ranges);
4184     Chains[ChainI] = L.getValue(1);
4185 
4186     if (MemVTs[i] != ValueVTs[i])
4187       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4188 
4189     Values[i] = L;
4190   }
4191 
4192   if (!ConstantMemory) {
4193     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4194                                 makeArrayRef(Chains.data(), ChainI));
4195     if (isVolatile)
4196       DAG.setRoot(Chain);
4197     else
4198       PendingLoads.push_back(Chain);
4199   }
4200 
4201   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4202                            DAG.getVTList(ValueVTs), Values));
4203 }
4204 
4205 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4206   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4207          "call visitStoreToSwiftError when backend supports swifterror");
4208 
4209   SmallVector<EVT, 4> ValueVTs;
4210   SmallVector<uint64_t, 4> Offsets;
4211   const Value *SrcV = I.getOperand(0);
4212   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4213                   SrcV->getType(), ValueVTs, &Offsets);
4214   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4215          "expect a single EVT for swifterror");
4216 
4217   SDValue Src = getValue(SrcV);
4218   // Create a virtual register, then update the virtual register.
4219   Register VReg =
4220       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4221   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4222   // Chain can be getRoot or getControlRoot.
4223   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4224                                       SDValue(Src.getNode(), Src.getResNo()));
4225   DAG.setRoot(CopyNode);
4226 }
4227 
4228 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4229   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4230          "call visitLoadFromSwiftError when backend supports swifterror");
4231 
4232   assert(!I.isVolatile() &&
4233          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4234          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4235          "Support volatile, non temporal, invariant for load_from_swift_error");
4236 
4237   const Value *SV = I.getOperand(0);
4238   Type *Ty = I.getType();
4239   assert(
4240       (!AA ||
4241        !AA->pointsToConstantMemory(MemoryLocation(
4242            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4243            I.getAAMetadata()))) &&
4244       "load_from_swift_error should not be constant memory");
4245 
4246   SmallVector<EVT, 4> ValueVTs;
4247   SmallVector<uint64_t, 4> Offsets;
4248   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4249                   ValueVTs, &Offsets);
4250   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4251          "expect a single EVT for swifterror");
4252 
4253   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4254   SDValue L = DAG.getCopyFromReg(
4255       getRoot(), getCurSDLoc(),
4256       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4257 
4258   setValue(&I, L);
4259 }
4260 
4261 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4262   if (I.isAtomic())
4263     return visitAtomicStore(I);
4264 
4265   const Value *SrcV = I.getOperand(0);
4266   const Value *PtrV = I.getOperand(1);
4267 
4268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4269   if (TLI.supportSwiftError()) {
4270     // Swifterror values can come from either a function parameter with
4271     // swifterror attribute or an alloca with swifterror attribute.
4272     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4273       if (Arg->hasSwiftErrorAttr())
4274         return visitStoreToSwiftError(I);
4275     }
4276 
4277     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4278       if (Alloca->isSwiftError())
4279         return visitStoreToSwiftError(I);
4280     }
4281   }
4282 
4283   SmallVector<EVT, 4> ValueVTs, MemVTs;
4284   SmallVector<uint64_t, 4> Offsets;
4285   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4286                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4287   unsigned NumValues = ValueVTs.size();
4288   if (NumValues == 0)
4289     return;
4290 
4291   // Get the lowered operands. Note that we do this after
4292   // checking if NumResults is zero, because with zero results
4293   // the operands won't have values in the map.
4294   SDValue Src = getValue(SrcV);
4295   SDValue Ptr = getValue(PtrV);
4296 
4297   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4298   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4299   SDLoc dl = getCurSDLoc();
4300   Align Alignment = I.getAlign();
4301   AAMDNodes AAInfo = I.getAAMetadata();
4302 
4303   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4304 
4305   // An aggregate load cannot wrap around the address space, so offsets to its
4306   // parts don't wrap either.
4307   SDNodeFlags Flags;
4308   Flags.setNoUnsignedWrap(true);
4309 
4310   unsigned ChainI = 0;
4311   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4312     // See visitLoad comments.
4313     if (ChainI == MaxParallelChains) {
4314       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4315                                   makeArrayRef(Chains.data(), ChainI));
4316       Root = Chain;
4317       ChainI = 0;
4318     }
4319     SDValue Add =
4320         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4321     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4322     if (MemVTs[i] != ValueVTs[i])
4323       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4324     SDValue St =
4325         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4326                      Alignment, MMOFlags, AAInfo);
4327     Chains[ChainI] = St;
4328   }
4329 
4330   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4331                                   makeArrayRef(Chains.data(), ChainI));
4332   setValue(&I, StoreNode);
4333   DAG.setRoot(StoreNode);
4334 }
4335 
4336 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4337                                            bool IsCompressing) {
4338   SDLoc sdl = getCurSDLoc();
4339 
4340   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4341                                MaybeAlign &Alignment) {
4342     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4343     Src0 = I.getArgOperand(0);
4344     Ptr = I.getArgOperand(1);
4345     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4346     Mask = I.getArgOperand(3);
4347   };
4348   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4349                                     MaybeAlign &Alignment) {
4350     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4351     Src0 = I.getArgOperand(0);
4352     Ptr = I.getArgOperand(1);
4353     Mask = I.getArgOperand(2);
4354     Alignment = None;
4355   };
4356 
4357   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4358   MaybeAlign Alignment;
4359   if (IsCompressing)
4360     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4361   else
4362     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4363 
4364   SDValue Ptr = getValue(PtrOperand);
4365   SDValue Src0 = getValue(Src0Operand);
4366   SDValue Mask = getValue(MaskOperand);
4367   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4368 
4369   EVT VT = Src0.getValueType();
4370   if (!Alignment)
4371     Alignment = DAG.getEVTAlign(VT);
4372 
4373   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4374       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4375       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4376   SDValue StoreNode =
4377       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4378                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4379   DAG.setRoot(StoreNode);
4380   setValue(&I, StoreNode);
4381 }
4382 
4383 // Get a uniform base for the Gather/Scatter intrinsic.
4384 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4385 // We try to represent it as a base pointer + vector of indices.
4386 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4387 // The first operand of the GEP may be a single pointer or a vector of pointers
4388 // Example:
4389 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4390 //  or
4391 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4392 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4393 //
4394 // When the first GEP operand is a single pointer - it is the uniform base we
4395 // are looking for. If first operand of the GEP is a splat vector - we
4396 // extract the splat value and use it as a uniform base.
4397 // In all other cases the function returns 'false'.
4398 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4399                            ISD::MemIndexType &IndexType, SDValue &Scale,
4400                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4401                            uint64_t ElemSize) {
4402   SelectionDAG& DAG = SDB->DAG;
4403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4404   const DataLayout &DL = DAG.getDataLayout();
4405 
4406   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4407 
4408   // Handle splat constant pointer.
4409   if (auto *C = dyn_cast<Constant>(Ptr)) {
4410     C = C->getSplatValue();
4411     if (!C)
4412       return false;
4413 
4414     Base = SDB->getValue(C);
4415 
4416     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4417     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4418     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4419     IndexType = ISD::SIGNED_SCALED;
4420     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4421     return true;
4422   }
4423 
4424   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4425   if (!GEP || GEP->getParent() != CurBB)
4426     return false;
4427 
4428   if (GEP->getNumOperands() != 2)
4429     return false;
4430 
4431   const Value *BasePtr = GEP->getPointerOperand();
4432   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4433 
4434   // Make sure the base is scalar and the index is a vector.
4435   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4436     return false;
4437 
4438   uint64_t ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4439 
4440   // Target may not support the required addressing mode.
4441   if (ScaleVal != 1 &&
4442       !TLI.isLegalScaleForGatherScatter(ScaleVal, ElemSize))
4443     return false;
4444 
4445   Base = SDB->getValue(BasePtr);
4446   Index = SDB->getValue(IndexVal);
4447   IndexType = ISD::SIGNED_SCALED;
4448 
4449   Scale =
4450       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4451   return true;
4452 }
4453 
4454 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4455   SDLoc sdl = getCurSDLoc();
4456 
4457   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4458   const Value *Ptr = I.getArgOperand(1);
4459   SDValue Src0 = getValue(I.getArgOperand(0));
4460   SDValue Mask = getValue(I.getArgOperand(3));
4461   EVT VT = Src0.getValueType();
4462   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4463                         ->getMaybeAlignValue()
4464                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4465   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4466 
4467   SDValue Base;
4468   SDValue Index;
4469   ISD::MemIndexType IndexType;
4470   SDValue Scale;
4471   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4472                                     I.getParent(), VT.getScalarStoreSize());
4473 
4474   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4475   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4476       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4477       // TODO: Make MachineMemOperands aware of scalable
4478       // vectors.
4479       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4480   if (!UniformBase) {
4481     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4482     Index = getValue(Ptr);
4483     IndexType = ISD::SIGNED_SCALED;
4484     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4485   }
4486 
4487   EVT IdxVT = Index.getValueType();
4488   EVT EltTy = IdxVT.getVectorElementType();
4489   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4490     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4491     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4492   }
4493 
4494   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4495   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4496                                          Ops, MMO, IndexType, false);
4497   DAG.setRoot(Scatter);
4498   setValue(&I, Scatter);
4499 }
4500 
4501 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4502   SDLoc sdl = getCurSDLoc();
4503 
4504   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4505                               MaybeAlign &Alignment) {
4506     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4507     Ptr = I.getArgOperand(0);
4508     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4509     Mask = I.getArgOperand(2);
4510     Src0 = I.getArgOperand(3);
4511   };
4512   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4513                                  MaybeAlign &Alignment) {
4514     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4515     Ptr = I.getArgOperand(0);
4516     Alignment = None;
4517     Mask = I.getArgOperand(1);
4518     Src0 = I.getArgOperand(2);
4519   };
4520 
4521   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4522   MaybeAlign Alignment;
4523   if (IsExpanding)
4524     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4525   else
4526     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4527 
4528   SDValue Ptr = getValue(PtrOperand);
4529   SDValue Src0 = getValue(Src0Operand);
4530   SDValue Mask = getValue(MaskOperand);
4531   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4532 
4533   EVT VT = Src0.getValueType();
4534   if (!Alignment)
4535     Alignment = DAG.getEVTAlign(VT);
4536 
4537   AAMDNodes AAInfo = I.getAAMetadata();
4538   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4539 
4540   // Do not serialize masked loads of constant memory with anything.
4541   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4542   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4543 
4544   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4545 
4546   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4547       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4548       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4549 
4550   SDValue Load =
4551       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4552                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4553   if (AddToChain)
4554     PendingLoads.push_back(Load.getValue(1));
4555   setValue(&I, Load);
4556 }
4557 
4558 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4559   SDLoc sdl = getCurSDLoc();
4560 
4561   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4562   const Value *Ptr = I.getArgOperand(0);
4563   SDValue Src0 = getValue(I.getArgOperand(3));
4564   SDValue Mask = getValue(I.getArgOperand(2));
4565 
4566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4567   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4568   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4569                         ->getMaybeAlignValue()
4570                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4571 
4572   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4573 
4574   SDValue Root = DAG.getRoot();
4575   SDValue Base;
4576   SDValue Index;
4577   ISD::MemIndexType IndexType;
4578   SDValue Scale;
4579   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4580                                     I.getParent(), VT.getScalarStoreSize());
4581   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4582   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4583       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4584       // TODO: Make MachineMemOperands aware of scalable
4585       // vectors.
4586       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4587 
4588   if (!UniformBase) {
4589     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4590     Index = getValue(Ptr);
4591     IndexType = ISD::SIGNED_SCALED;
4592     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4593   }
4594 
4595   EVT IdxVT = Index.getValueType();
4596   EVT EltTy = IdxVT.getVectorElementType();
4597   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4598     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4599     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4600   }
4601 
4602   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4603   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4604                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4605 
4606   PendingLoads.push_back(Gather.getValue(1));
4607   setValue(&I, Gather);
4608 }
4609 
4610 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4611   SDLoc dl = getCurSDLoc();
4612   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4613   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4614   SyncScope::ID SSID = I.getSyncScopeID();
4615 
4616   SDValue InChain = getRoot();
4617 
4618   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4619   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4620 
4621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4622   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4623 
4624   MachineFunction &MF = DAG.getMachineFunction();
4625   MachineMemOperand *MMO = MF.getMachineMemOperand(
4626       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4627       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4628       FailureOrdering);
4629 
4630   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4631                                    dl, MemVT, VTs, InChain,
4632                                    getValue(I.getPointerOperand()),
4633                                    getValue(I.getCompareOperand()),
4634                                    getValue(I.getNewValOperand()), MMO);
4635 
4636   SDValue OutChain = L.getValue(2);
4637 
4638   setValue(&I, L);
4639   DAG.setRoot(OutChain);
4640 }
4641 
4642 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4643   SDLoc dl = getCurSDLoc();
4644   ISD::NodeType NT;
4645   switch (I.getOperation()) {
4646   default: llvm_unreachable("Unknown atomicrmw operation");
4647   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4648   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4649   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4650   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4651   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4652   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4653   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4654   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4655   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4656   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4657   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4658   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4659   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4660   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
4661   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
4662   }
4663   AtomicOrdering Ordering = I.getOrdering();
4664   SyncScope::ID SSID = I.getSyncScopeID();
4665 
4666   SDValue InChain = getRoot();
4667 
4668   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4669   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4670   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4671 
4672   MachineFunction &MF = DAG.getMachineFunction();
4673   MachineMemOperand *MMO = MF.getMachineMemOperand(
4674       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4675       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4676 
4677   SDValue L =
4678     DAG.getAtomic(NT, dl, MemVT, InChain,
4679                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4680                   MMO);
4681 
4682   SDValue OutChain = L.getValue(1);
4683 
4684   setValue(&I, L);
4685   DAG.setRoot(OutChain);
4686 }
4687 
4688 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4689   SDLoc dl = getCurSDLoc();
4690   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4691   SDValue Ops[3];
4692   Ops[0] = getRoot();
4693   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4694                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4695   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4696                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4697   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
4698   setValue(&I, N);
4699   DAG.setRoot(N);
4700 }
4701 
4702 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4703   SDLoc dl = getCurSDLoc();
4704   AtomicOrdering Order = I.getOrdering();
4705   SyncScope::ID SSID = I.getSyncScopeID();
4706 
4707   SDValue InChain = getRoot();
4708 
4709   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4710   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4711   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4712 
4713   if (!TLI.supportsUnalignedAtomics() &&
4714       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4715     report_fatal_error("Cannot generate unaligned atomic load");
4716 
4717   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4718 
4719   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4720       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4721       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4722 
4723   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4724 
4725   SDValue Ptr = getValue(I.getPointerOperand());
4726 
4727   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4728     // TODO: Once this is better exercised by tests, it should be merged with
4729     // the normal path for loads to prevent future divergence.
4730     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4731     if (MemVT != VT)
4732       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4733 
4734     setValue(&I, L);
4735     SDValue OutChain = L.getValue(1);
4736     if (!I.isUnordered())
4737       DAG.setRoot(OutChain);
4738     else
4739       PendingLoads.push_back(OutChain);
4740     return;
4741   }
4742 
4743   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4744                             Ptr, MMO);
4745 
4746   SDValue OutChain = L.getValue(1);
4747   if (MemVT != VT)
4748     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4749 
4750   setValue(&I, L);
4751   DAG.setRoot(OutChain);
4752 }
4753 
4754 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4755   SDLoc dl = getCurSDLoc();
4756 
4757   AtomicOrdering Ordering = I.getOrdering();
4758   SyncScope::ID SSID = I.getSyncScopeID();
4759 
4760   SDValue InChain = getRoot();
4761 
4762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4763   EVT MemVT =
4764       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4765 
4766   if (!TLI.supportsUnalignedAtomics() &&
4767       I.getAlign().value() < MemVT.getSizeInBits() / 8)
4768     report_fatal_error("Cannot generate unaligned atomic store");
4769 
4770   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4771 
4772   MachineFunction &MF = DAG.getMachineFunction();
4773   MachineMemOperand *MMO = MF.getMachineMemOperand(
4774       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4775       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4776 
4777   SDValue Val = getValue(I.getValueOperand());
4778   if (Val.getValueType() != MemVT)
4779     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4780   SDValue Ptr = getValue(I.getPointerOperand());
4781 
4782   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4783     // TODO: Once this is better exercised by tests, it should be merged with
4784     // the normal path for stores to prevent future divergence.
4785     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4786     setValue(&I, S);
4787     DAG.setRoot(S);
4788     return;
4789   }
4790   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4791                                    Ptr, Val, MMO);
4792 
4793   setValue(&I, OutChain);
4794   DAG.setRoot(OutChain);
4795 }
4796 
4797 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4798 /// node.
4799 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4800                                                unsigned Intrinsic) {
4801   // Ignore the callsite's attributes. A specific call site may be marked with
4802   // readnone, but the lowering code will expect the chain based on the
4803   // definition.
4804   const Function *F = I.getCalledFunction();
4805   bool HasChain = !F->doesNotAccessMemory();
4806   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4807 
4808   // Build the operand list.
4809   SmallVector<SDValue, 8> Ops;
4810   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4811     if (OnlyLoad) {
4812       // We don't need to serialize loads against other loads.
4813       Ops.push_back(DAG.getRoot());
4814     } else {
4815       Ops.push_back(getRoot());
4816     }
4817   }
4818 
4819   // Info is set by getTgtMemIntrinsic
4820   TargetLowering::IntrinsicInfo Info;
4821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4822   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4823                                                DAG.getMachineFunction(),
4824                                                Intrinsic);
4825 
4826   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4827   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4828       Info.opc == ISD::INTRINSIC_W_CHAIN)
4829     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4830                                         TLI.getPointerTy(DAG.getDataLayout())));
4831 
4832   // Add all operands of the call to the operand list.
4833   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4834     const Value *Arg = I.getArgOperand(i);
4835     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4836       Ops.push_back(getValue(Arg));
4837       continue;
4838     }
4839 
4840     // Use TargetConstant instead of a regular constant for immarg.
4841     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4842     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4843       assert(CI->getBitWidth() <= 64 &&
4844              "large intrinsic immediates not handled");
4845       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4846     } else {
4847       Ops.push_back(
4848           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4849     }
4850   }
4851 
4852   SmallVector<EVT, 4> ValueVTs;
4853   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4854 
4855   if (HasChain)
4856     ValueVTs.push_back(MVT::Other);
4857 
4858   SDVTList VTs = DAG.getVTList(ValueVTs);
4859 
4860   // Propagate fast-math-flags from IR to node(s).
4861   SDNodeFlags Flags;
4862   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4863     Flags.copyFMF(*FPMO);
4864   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4865 
4866   // Create the node.
4867   SDValue Result;
4868   // In some cases, custom collection of operands from CallInst I may be needed.
4869   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
4870   if (IsTgtIntrinsic) {
4871     // This is target intrinsic that touches memory
4872     Result =
4873         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4874                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4875                                 Info.align, Info.flags, Info.size,
4876                                 I.getAAMetadata());
4877   } else if (!HasChain) {
4878     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4879   } else if (!I.getType()->isVoidTy()) {
4880     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4881   } else {
4882     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4883   }
4884 
4885   if (HasChain) {
4886     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4887     if (OnlyLoad)
4888       PendingLoads.push_back(Chain);
4889     else
4890       DAG.setRoot(Chain);
4891   }
4892 
4893   if (!I.getType()->isVoidTy()) {
4894     if (!isa<VectorType>(I.getType()))
4895       Result = lowerRangeToAssertZExt(DAG, I, Result);
4896 
4897     MaybeAlign Alignment = I.getRetAlign();
4898     if (!Alignment)
4899       Alignment = F->getAttributes().getRetAlignment();
4900     // Insert `assertalign` node if there's an alignment.
4901     if (InsertAssertAlign && Alignment) {
4902       Result =
4903           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4904     }
4905 
4906     setValue(&I, Result);
4907   }
4908 }
4909 
4910 /// GetSignificand - Get the significand and build it into a floating-point
4911 /// number with exponent of 1:
4912 ///
4913 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4914 ///
4915 /// where Op is the hexadecimal representation of floating point value.
4916 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4917   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4918                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4919   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4920                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4921   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4922 }
4923 
4924 /// GetExponent - Get the exponent:
4925 ///
4926 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4927 ///
4928 /// where Op is the hexadecimal representation of floating point value.
4929 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4930                            const TargetLowering &TLI, const SDLoc &dl) {
4931   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4932                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4933   SDValue t1 = DAG.getNode(
4934       ISD::SRL, dl, MVT::i32, t0,
4935       DAG.getConstant(23, dl,
4936                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
4937   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4938                            DAG.getConstant(127, dl, MVT::i32));
4939   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4940 }
4941 
4942 /// getF32Constant - Get 32-bit floating point constant.
4943 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4944                               const SDLoc &dl) {
4945   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4946                            MVT::f32);
4947 }
4948 
4949 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4950                                        SelectionDAG &DAG) {
4951   // TODO: What fast-math-flags should be set on the floating-point nodes?
4952 
4953   //   IntegerPartOfX = ((int32_t)(t0);
4954   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4955 
4956   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4957   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4958   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4959 
4960   //   IntegerPartOfX <<= 23;
4961   IntegerPartOfX =
4962       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4963                   DAG.getConstant(23, dl,
4964                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
4965                                       MVT::i32, DAG.getDataLayout())));
4966 
4967   SDValue TwoToFractionalPartOfX;
4968   if (LimitFloatPrecision <= 6) {
4969     // For floating-point precision of 6:
4970     //
4971     //   TwoToFractionalPartOfX =
4972     //     0.997535578f +
4973     //       (0.735607626f + 0.252464424f * x) * x;
4974     //
4975     // error 0.0144103317, which is 6 bits
4976     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4977                              getF32Constant(DAG, 0x3e814304, dl));
4978     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4979                              getF32Constant(DAG, 0x3f3c50c8, dl));
4980     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4981     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4982                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4983   } else if (LimitFloatPrecision <= 12) {
4984     // For floating-point precision of 12:
4985     //
4986     //   TwoToFractionalPartOfX =
4987     //     0.999892986f +
4988     //       (0.696457318f +
4989     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4990     //
4991     // error 0.000107046256, which is 13 to 14 bits
4992     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4993                              getF32Constant(DAG, 0x3da235e3, dl));
4994     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4995                              getF32Constant(DAG, 0x3e65b8f3, dl));
4996     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4997     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4998                              getF32Constant(DAG, 0x3f324b07, dl));
4999     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5000     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5001                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5002   } else { // LimitFloatPrecision <= 18
5003     // For floating-point precision of 18:
5004     //
5005     //   TwoToFractionalPartOfX =
5006     //     0.999999982f +
5007     //       (0.693148872f +
5008     //         (0.240227044f +
5009     //           (0.554906021e-1f +
5010     //             (0.961591928e-2f +
5011     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5012     // error 2.47208000*10^(-7), which is better than 18 bits
5013     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5014                              getF32Constant(DAG, 0x3924b03e, dl));
5015     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5016                              getF32Constant(DAG, 0x3ab24b87, dl));
5017     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5018     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5019                              getF32Constant(DAG, 0x3c1d8c17, dl));
5020     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5021     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5022                              getF32Constant(DAG, 0x3d634a1d, dl));
5023     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5024     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5025                              getF32Constant(DAG, 0x3e75fe14, dl));
5026     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5027     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5028                               getF32Constant(DAG, 0x3f317234, dl));
5029     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5030     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5031                                          getF32Constant(DAG, 0x3f800000, dl));
5032   }
5033 
5034   // Add the exponent into the result in integer domain.
5035   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5036   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5037                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5038 }
5039 
5040 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5041 /// limited-precision mode.
5042 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5043                          const TargetLowering &TLI, SDNodeFlags Flags) {
5044   if (Op.getValueType() == MVT::f32 &&
5045       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5046 
5047     // Put the exponent in the right bit position for later addition to the
5048     // final result:
5049     //
5050     // t0 = Op * log2(e)
5051 
5052     // TODO: What fast-math-flags should be set here?
5053     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5054                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5055     return getLimitedPrecisionExp2(t0, dl, DAG);
5056   }
5057 
5058   // No special expansion.
5059   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5060 }
5061 
5062 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5063 /// limited-precision mode.
5064 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5065                          const TargetLowering &TLI, SDNodeFlags Flags) {
5066   // TODO: What fast-math-flags should be set on the floating-point nodes?
5067 
5068   if (Op.getValueType() == MVT::f32 &&
5069       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5070     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5071 
5072     // Scale the exponent by log(2).
5073     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5074     SDValue LogOfExponent =
5075         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5076                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5077 
5078     // Get the significand and build it into a floating-point number with
5079     // exponent of 1.
5080     SDValue X = GetSignificand(DAG, Op1, dl);
5081 
5082     SDValue LogOfMantissa;
5083     if (LimitFloatPrecision <= 6) {
5084       // For floating-point precision of 6:
5085       //
5086       //   LogofMantissa =
5087       //     -1.1609546f +
5088       //       (1.4034025f - 0.23903021f * x) * x;
5089       //
5090       // error 0.0034276066, which is better than 8 bits
5091       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5092                                getF32Constant(DAG, 0xbe74c456, dl));
5093       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5094                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5095       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5096       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5097                                   getF32Constant(DAG, 0x3f949a29, dl));
5098     } else if (LimitFloatPrecision <= 12) {
5099       // For floating-point precision of 12:
5100       //
5101       //   LogOfMantissa =
5102       //     -1.7417939f +
5103       //       (2.8212026f +
5104       //         (-1.4699568f +
5105       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5106       //
5107       // error 0.000061011436, which is 14 bits
5108       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5109                                getF32Constant(DAG, 0xbd67b6d6, dl));
5110       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5111                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5112       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5113       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5114                                getF32Constant(DAG, 0x3fbc278b, dl));
5115       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5116       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5117                                getF32Constant(DAG, 0x40348e95, dl));
5118       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5119       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5120                                   getF32Constant(DAG, 0x3fdef31a, dl));
5121     } else { // LimitFloatPrecision <= 18
5122       // For floating-point precision of 18:
5123       //
5124       //   LogOfMantissa =
5125       //     -2.1072184f +
5126       //       (4.2372794f +
5127       //         (-3.7029485f +
5128       //           (2.2781945f +
5129       //             (-0.87823314f +
5130       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5131       //
5132       // error 0.0000023660568, which is better than 18 bits
5133       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5134                                getF32Constant(DAG, 0xbc91e5ac, dl));
5135       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5136                                getF32Constant(DAG, 0x3e4350aa, dl));
5137       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5138       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5139                                getF32Constant(DAG, 0x3f60d3e3, dl));
5140       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5141       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5142                                getF32Constant(DAG, 0x4011cdf0, dl));
5143       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5144       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5145                                getF32Constant(DAG, 0x406cfd1c, dl));
5146       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5147       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5148                                getF32Constant(DAG, 0x408797cb, dl));
5149       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5150       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5151                                   getF32Constant(DAG, 0x4006dcab, dl));
5152     }
5153 
5154     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5155   }
5156 
5157   // No special expansion.
5158   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5159 }
5160 
5161 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5162 /// limited-precision mode.
5163 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5164                           const TargetLowering &TLI, SDNodeFlags Flags) {
5165   // TODO: What fast-math-flags should be set on the floating-point nodes?
5166 
5167   if (Op.getValueType() == MVT::f32 &&
5168       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5169     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5170 
5171     // Get the exponent.
5172     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5173 
5174     // Get the significand and build it into a floating-point number with
5175     // exponent of 1.
5176     SDValue X = GetSignificand(DAG, Op1, dl);
5177 
5178     // Different possible minimax approximations of significand in
5179     // floating-point for various degrees of accuracy over [1,2].
5180     SDValue Log2ofMantissa;
5181     if (LimitFloatPrecision <= 6) {
5182       // For floating-point precision of 6:
5183       //
5184       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5185       //
5186       // error 0.0049451742, which is more than 7 bits
5187       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5188                                getF32Constant(DAG, 0xbeb08fe0, dl));
5189       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5190                                getF32Constant(DAG, 0x40019463, dl));
5191       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5192       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5193                                    getF32Constant(DAG, 0x3fd6633d, dl));
5194     } else if (LimitFloatPrecision <= 12) {
5195       // For floating-point precision of 12:
5196       //
5197       //   Log2ofMantissa =
5198       //     -2.51285454f +
5199       //       (4.07009056f +
5200       //         (-2.12067489f +
5201       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5202       //
5203       // error 0.0000876136000, which is better than 13 bits
5204       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5205                                getF32Constant(DAG, 0xbda7262e, dl));
5206       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5207                                getF32Constant(DAG, 0x3f25280b, dl));
5208       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5209       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5210                                getF32Constant(DAG, 0x4007b923, dl));
5211       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5212       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5213                                getF32Constant(DAG, 0x40823e2f, dl));
5214       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5215       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5216                                    getF32Constant(DAG, 0x4020d29c, dl));
5217     } else { // LimitFloatPrecision <= 18
5218       // For floating-point precision of 18:
5219       //
5220       //   Log2ofMantissa =
5221       //     -3.0400495f +
5222       //       (6.1129976f +
5223       //         (-5.3420409f +
5224       //           (3.2865683f +
5225       //             (-1.2669343f +
5226       //               (0.27515199f -
5227       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5228       //
5229       // error 0.0000018516, which is better than 18 bits
5230       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5231                                getF32Constant(DAG, 0xbcd2769e, dl));
5232       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5233                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5234       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5235       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5236                                getF32Constant(DAG, 0x3fa22ae7, dl));
5237       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5238       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5239                                getF32Constant(DAG, 0x40525723, dl));
5240       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5241       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5242                                getF32Constant(DAG, 0x40aaf200, dl));
5243       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5244       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5245                                getF32Constant(DAG, 0x40c39dad, dl));
5246       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5247       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5248                                    getF32Constant(DAG, 0x4042902c, dl));
5249     }
5250 
5251     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5252   }
5253 
5254   // No special expansion.
5255   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5256 }
5257 
5258 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5259 /// limited-precision mode.
5260 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5261                            const TargetLowering &TLI, SDNodeFlags Flags) {
5262   // TODO: What fast-math-flags should be set on the floating-point nodes?
5263 
5264   if (Op.getValueType() == MVT::f32 &&
5265       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5266     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5267 
5268     // Scale the exponent by log10(2) [0.30102999f].
5269     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5270     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5271                                         getF32Constant(DAG, 0x3e9a209a, dl));
5272 
5273     // Get the significand and build it into a floating-point number with
5274     // exponent of 1.
5275     SDValue X = GetSignificand(DAG, Op1, dl);
5276 
5277     SDValue Log10ofMantissa;
5278     if (LimitFloatPrecision <= 6) {
5279       // For floating-point precision of 6:
5280       //
5281       //   Log10ofMantissa =
5282       //     -0.50419619f +
5283       //       (0.60948995f - 0.10380950f * x) * x;
5284       //
5285       // error 0.0014886165, which is 6 bits
5286       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5287                                getF32Constant(DAG, 0xbdd49a13, dl));
5288       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5289                                getF32Constant(DAG, 0x3f1c0789, dl));
5290       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5291       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5292                                     getF32Constant(DAG, 0x3f011300, dl));
5293     } else if (LimitFloatPrecision <= 12) {
5294       // For floating-point precision of 12:
5295       //
5296       //   Log10ofMantissa =
5297       //     -0.64831180f +
5298       //       (0.91751397f +
5299       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5300       //
5301       // error 0.00019228036, which is better than 12 bits
5302       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5303                                getF32Constant(DAG, 0x3d431f31, dl));
5304       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5305                                getF32Constant(DAG, 0x3ea21fb2, dl));
5306       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5307       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5308                                getF32Constant(DAG, 0x3f6ae232, dl));
5309       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5310       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5311                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5312     } else { // LimitFloatPrecision <= 18
5313       // For floating-point precision of 18:
5314       //
5315       //   Log10ofMantissa =
5316       //     -0.84299375f +
5317       //       (1.5327582f +
5318       //         (-1.0688956f +
5319       //           (0.49102474f +
5320       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5321       //
5322       // error 0.0000037995730, which is better than 18 bits
5323       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5324                                getF32Constant(DAG, 0x3c5d51ce, dl));
5325       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5326                                getF32Constant(DAG, 0x3e00685a, dl));
5327       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5328       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5329                                getF32Constant(DAG, 0x3efb6798, dl));
5330       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5331       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5332                                getF32Constant(DAG, 0x3f88d192, dl));
5333       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5334       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5335                                getF32Constant(DAG, 0x3fc4316c, dl));
5336       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5337       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5338                                     getF32Constant(DAG, 0x3f57ce70, dl));
5339     }
5340 
5341     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5342   }
5343 
5344   // No special expansion.
5345   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5346 }
5347 
5348 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5349 /// limited-precision mode.
5350 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5351                           const TargetLowering &TLI, SDNodeFlags Flags) {
5352   if (Op.getValueType() == MVT::f32 &&
5353       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5354     return getLimitedPrecisionExp2(Op, dl, DAG);
5355 
5356   // No special expansion.
5357   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5358 }
5359 
5360 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5361 /// limited-precision mode with x == 10.0f.
5362 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5363                          SelectionDAG &DAG, const TargetLowering &TLI,
5364                          SDNodeFlags Flags) {
5365   bool IsExp10 = false;
5366   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5367       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5368     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5369       APFloat Ten(10.0f);
5370       IsExp10 = LHSC->isExactlyValue(Ten);
5371     }
5372   }
5373 
5374   // TODO: What fast-math-flags should be set on the FMUL node?
5375   if (IsExp10) {
5376     // Put the exponent in the right bit position for later addition to the
5377     // final result:
5378     //
5379     //   #define LOG2OF10 3.3219281f
5380     //   t0 = Op * LOG2OF10;
5381     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5382                              getF32Constant(DAG, 0x40549a78, dl));
5383     return getLimitedPrecisionExp2(t0, dl, DAG);
5384   }
5385 
5386   // No special expansion.
5387   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5388 }
5389 
5390 /// ExpandPowI - Expand a llvm.powi intrinsic.
5391 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5392                           SelectionDAG &DAG) {
5393   // If RHS is a constant, we can expand this out to a multiplication tree if
5394   // it's beneficial on the target, otherwise we end up lowering to a call to
5395   // __powidf2 (for example).
5396   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5397     unsigned Val = RHSC->getSExtValue();
5398 
5399     // powi(x, 0) -> 1.0
5400     if (Val == 0)
5401       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5402 
5403     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5404             Val, DAG.shouldOptForSize())) {
5405       // Get the exponent as a positive value.
5406       if ((int)Val < 0)
5407         Val = -Val;
5408       // We use the simple binary decomposition method to generate the multiply
5409       // sequence.  There are more optimal ways to do this (for example,
5410       // powi(x,15) generates one more multiply than it should), but this has
5411       // the benefit of being both really simple and much better than a libcall.
5412       SDValue Res; // Logically starts equal to 1.0
5413       SDValue CurSquare = LHS;
5414       // TODO: Intrinsics should have fast-math-flags that propagate to these
5415       // nodes.
5416       while (Val) {
5417         if (Val & 1) {
5418           if (Res.getNode())
5419             Res =
5420                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5421           else
5422             Res = CurSquare; // 1.0*CurSquare.
5423         }
5424 
5425         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5426                                 CurSquare, CurSquare);
5427         Val >>= 1;
5428       }
5429 
5430       // If the original was negative, invert the result, producing 1/(x*x*x).
5431       if (RHSC->getSExtValue() < 0)
5432         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5433                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5434       return Res;
5435     }
5436   }
5437 
5438   // Otherwise, expand to a libcall.
5439   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5440 }
5441 
5442 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5443                             SDValue LHS, SDValue RHS, SDValue Scale,
5444                             SelectionDAG &DAG, const TargetLowering &TLI) {
5445   EVT VT = LHS.getValueType();
5446   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5447   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5448   LLVMContext &Ctx = *DAG.getContext();
5449 
5450   // If the type is legal but the operation isn't, this node might survive all
5451   // the way to operation legalization. If we end up there and we do not have
5452   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5453   // node.
5454 
5455   // Coax the legalizer into expanding the node during type legalization instead
5456   // by bumping the size by one bit. This will force it to Promote, enabling the
5457   // early expansion and avoiding the need to expand later.
5458 
5459   // We don't have to do this if Scale is 0; that can always be expanded, unless
5460   // it's a saturating signed operation. Those can experience true integer
5461   // division overflow, a case which we must avoid.
5462 
5463   // FIXME: We wouldn't have to do this (or any of the early
5464   // expansion/promotion) if it was possible to expand a libcall of an
5465   // illegal type during operation legalization. But it's not, so things
5466   // get a bit hacky.
5467   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5468   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5469       (TLI.isTypeLegal(VT) ||
5470        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5471     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5472         Opcode, VT, ScaleInt);
5473     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5474       EVT PromVT;
5475       if (VT.isScalarInteger())
5476         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5477       else if (VT.isVector()) {
5478         PromVT = VT.getVectorElementType();
5479         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5480         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5481       } else
5482         llvm_unreachable("Wrong VT for DIVFIX?");
5483       if (Signed) {
5484         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5485         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5486       } else {
5487         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5488         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5489       }
5490       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5491       // For saturating operations, we need to shift up the LHS to get the
5492       // proper saturation width, and then shift down again afterwards.
5493       if (Saturating)
5494         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5495                           DAG.getConstant(1, DL, ShiftTy));
5496       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5497       if (Saturating)
5498         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5499                           DAG.getConstant(1, DL, ShiftTy));
5500       return DAG.getZExtOrTrunc(Res, DL, VT);
5501     }
5502   }
5503 
5504   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5505 }
5506 
5507 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5508 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5509 static void
5510 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5511                      const SDValue &N) {
5512   switch (N.getOpcode()) {
5513   case ISD::CopyFromReg: {
5514     SDValue Op = N.getOperand(1);
5515     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5516                       Op.getValueType().getSizeInBits());
5517     return;
5518   }
5519   case ISD::BITCAST:
5520   case ISD::AssertZext:
5521   case ISD::AssertSext:
5522   case ISD::TRUNCATE:
5523     getUnderlyingArgRegs(Regs, N.getOperand(0));
5524     return;
5525   case ISD::BUILD_PAIR:
5526   case ISD::BUILD_VECTOR:
5527   case ISD::CONCAT_VECTORS:
5528     for (SDValue Op : N->op_values())
5529       getUnderlyingArgRegs(Regs, Op);
5530     return;
5531   default:
5532     return;
5533   }
5534 }
5535 
5536 /// If the DbgValueInst is a dbg_value of a function argument, create the
5537 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5538 /// instruction selection, they will be inserted to the entry BB.
5539 /// We don't currently support this for variadic dbg_values, as they shouldn't
5540 /// appear for function arguments or in the prologue.
5541 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5542     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5543     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5544   const Argument *Arg = dyn_cast<Argument>(V);
5545   if (!Arg)
5546     return false;
5547 
5548   MachineFunction &MF = DAG.getMachineFunction();
5549   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5550 
5551   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5552   // we've been asked to pursue.
5553   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5554                               bool Indirect) {
5555     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5556       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5557       // pointing at the VReg, which will be patched up later.
5558       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5559       auto MIB = BuildMI(MF, DL, Inst);
5560       MIB.addReg(Reg);
5561       MIB.addImm(0);
5562       MIB.addMetadata(Variable);
5563       auto *NewDIExpr = FragExpr;
5564       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5565       // the DIExpression.
5566       if (Indirect)
5567         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5568       MIB.addMetadata(NewDIExpr);
5569       return MIB;
5570     } else {
5571       // Create a completely standard DBG_VALUE.
5572       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5573       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5574     }
5575   };
5576 
5577   if (Kind == FuncArgumentDbgValueKind::Value) {
5578     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5579     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5580     // the entry block.
5581     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5582     if (!IsInEntryBlock)
5583       return false;
5584 
5585     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5586     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5587     // variable that also is a param.
5588     //
5589     // Although, if we are at the top of the entry block already, we can still
5590     // emit using ArgDbgValue. This might catch some situations when the
5591     // dbg.value refers to an argument that isn't used in the entry block, so
5592     // any CopyToReg node would be optimized out and the only way to express
5593     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5594     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5595     // we should only emit as ArgDbgValue if the Variable is an argument to the
5596     // current function, and the dbg.value intrinsic is found in the entry
5597     // block.
5598     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5599         !DL->getInlinedAt();
5600     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5601     if (!IsInPrologue && !VariableIsFunctionInputArg)
5602       return false;
5603 
5604     // Here we assume that a function argument on IR level only can be used to
5605     // describe one input parameter on source level. If we for example have
5606     // source code like this
5607     //
5608     //    struct A { long x, y; };
5609     //    void foo(struct A a, long b) {
5610     //      ...
5611     //      b = a.x;
5612     //      ...
5613     //    }
5614     //
5615     // and IR like this
5616     //
5617     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5618     //  entry:
5619     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5620     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5621     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5622     //    ...
5623     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5624     //    ...
5625     //
5626     // then the last dbg.value is describing a parameter "b" using a value that
5627     // is an argument. But since we already has used %a1 to describe a parameter
5628     // we should not handle that last dbg.value here (that would result in an
5629     // incorrect hoisting of the DBG_VALUE to the function entry).
5630     // Notice that we allow one dbg.value per IR level argument, to accommodate
5631     // for the situation with fragments above.
5632     if (VariableIsFunctionInputArg) {
5633       unsigned ArgNo = Arg->getArgNo();
5634       if (ArgNo >= FuncInfo.DescribedArgs.size())
5635         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5636       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5637         return false;
5638       FuncInfo.DescribedArgs.set(ArgNo);
5639     }
5640   }
5641 
5642   bool IsIndirect = false;
5643   Optional<MachineOperand> Op;
5644   // Some arguments' frame index is recorded during argument lowering.
5645   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5646   if (FI != std::numeric_limits<int>::max())
5647     Op = MachineOperand::CreateFI(FI);
5648 
5649   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5650   if (!Op && N.getNode()) {
5651     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5652     Register Reg;
5653     if (ArgRegsAndSizes.size() == 1)
5654       Reg = ArgRegsAndSizes.front().first;
5655 
5656     if (Reg && Reg.isVirtual()) {
5657       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5658       Register PR = RegInfo.getLiveInPhysReg(Reg);
5659       if (PR)
5660         Reg = PR;
5661     }
5662     if (Reg) {
5663       Op = MachineOperand::CreateReg(Reg, false);
5664       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5665     }
5666   }
5667 
5668   if (!Op && N.getNode()) {
5669     // Check if frame index is available.
5670     SDValue LCandidate = peekThroughBitcasts(N);
5671     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5672       if (FrameIndexSDNode *FINode =
5673           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5674         Op = MachineOperand::CreateFI(FINode->getIndex());
5675   }
5676 
5677   if (!Op) {
5678     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5679     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5680                                          SplitRegs) {
5681       unsigned Offset = 0;
5682       for (const auto &RegAndSize : SplitRegs) {
5683         // If the expression is already a fragment, the current register
5684         // offset+size might extend beyond the fragment. In this case, only
5685         // the register bits that are inside the fragment are relevant.
5686         int RegFragmentSizeInBits = RegAndSize.second;
5687         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5688           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5689           // The register is entirely outside the expression fragment,
5690           // so is irrelevant for debug info.
5691           if (Offset >= ExprFragmentSizeInBits)
5692             break;
5693           // The register is partially outside the expression fragment, only
5694           // the low bits within the fragment are relevant for debug info.
5695           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5696             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5697           }
5698         }
5699 
5700         auto FragmentExpr = DIExpression::createFragmentExpression(
5701             Expr, Offset, RegFragmentSizeInBits);
5702         Offset += RegAndSize.second;
5703         // If a valid fragment expression cannot be created, the variable's
5704         // correct value cannot be determined and so it is set as Undef.
5705         if (!FragmentExpr) {
5706           SDDbgValue *SDV = DAG.getConstantDbgValue(
5707               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5708           DAG.AddDbgValue(SDV, false);
5709           continue;
5710         }
5711         MachineInstr *NewMI =
5712             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
5713                              Kind != FuncArgumentDbgValueKind::Value);
5714         FuncInfo.ArgDbgValues.push_back(NewMI);
5715       }
5716     };
5717 
5718     // Check if ValueMap has reg number.
5719     DenseMap<const Value *, Register>::const_iterator
5720       VMI = FuncInfo.ValueMap.find(V);
5721     if (VMI != FuncInfo.ValueMap.end()) {
5722       const auto &TLI = DAG.getTargetLoweringInfo();
5723       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5724                        V->getType(), None);
5725       if (RFV.occupiesMultipleRegs()) {
5726         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5727         return true;
5728       }
5729 
5730       Op = MachineOperand::CreateReg(VMI->second, false);
5731       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
5732     } else if (ArgRegsAndSizes.size() > 1) {
5733       // This was split due to the calling convention, and no virtual register
5734       // mapping exists for the value.
5735       splitMultiRegDbgValue(ArgRegsAndSizes);
5736       return true;
5737     }
5738   }
5739 
5740   if (!Op)
5741     return false;
5742 
5743   assert(Variable->isValidLocationForIntrinsic(DL) &&
5744          "Expected inlined-at fields to agree");
5745   MachineInstr *NewMI = nullptr;
5746 
5747   if (Op->isReg())
5748     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5749   else
5750     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5751                     Variable, Expr);
5752 
5753   // Otherwise, use ArgDbgValues.
5754   FuncInfo.ArgDbgValues.push_back(NewMI);
5755   return true;
5756 }
5757 
5758 /// Return the appropriate SDDbgValue based on N.
5759 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5760                                              DILocalVariable *Variable,
5761                                              DIExpression *Expr,
5762                                              const DebugLoc &dl,
5763                                              unsigned DbgSDNodeOrder) {
5764   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5765     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5766     // stack slot locations.
5767     //
5768     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5769     // debug values here after optimization:
5770     //
5771     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5772     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5773     //
5774     // Both describe the direct values of their associated variables.
5775     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5776                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5777   }
5778   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5779                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5780 }
5781 
5782 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5783   switch (Intrinsic) {
5784   case Intrinsic::smul_fix:
5785     return ISD::SMULFIX;
5786   case Intrinsic::umul_fix:
5787     return ISD::UMULFIX;
5788   case Intrinsic::smul_fix_sat:
5789     return ISD::SMULFIXSAT;
5790   case Intrinsic::umul_fix_sat:
5791     return ISD::UMULFIXSAT;
5792   case Intrinsic::sdiv_fix:
5793     return ISD::SDIVFIX;
5794   case Intrinsic::udiv_fix:
5795     return ISD::UDIVFIX;
5796   case Intrinsic::sdiv_fix_sat:
5797     return ISD::SDIVFIXSAT;
5798   case Intrinsic::udiv_fix_sat:
5799     return ISD::UDIVFIXSAT;
5800   default:
5801     llvm_unreachable("Unhandled fixed point intrinsic");
5802   }
5803 }
5804 
5805 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5806                                            const char *FunctionName) {
5807   assert(FunctionName && "FunctionName must not be nullptr");
5808   SDValue Callee = DAG.getExternalSymbol(
5809       FunctionName,
5810       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5811   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5812 }
5813 
5814 /// Given a @llvm.call.preallocated.setup, return the corresponding
5815 /// preallocated call.
5816 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5817   assert(cast<CallBase>(PreallocatedSetup)
5818                  ->getCalledFunction()
5819                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5820          "expected call_preallocated_setup Value");
5821   for (const auto *U : PreallocatedSetup->users()) {
5822     auto *UseCall = cast<CallBase>(U);
5823     const Function *Fn = UseCall->getCalledFunction();
5824     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5825       return UseCall;
5826     }
5827   }
5828   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5829 }
5830 
5831 /// Lower the call to the specified intrinsic function.
5832 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5833                                              unsigned Intrinsic) {
5834   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5835   SDLoc sdl = getCurSDLoc();
5836   DebugLoc dl = getCurDebugLoc();
5837   SDValue Res;
5838 
5839   SDNodeFlags Flags;
5840   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5841     Flags.copyFMF(*FPOp);
5842 
5843   switch (Intrinsic) {
5844   default:
5845     // By default, turn this into a target intrinsic node.
5846     visitTargetIntrinsic(I, Intrinsic);
5847     return;
5848   case Intrinsic::vscale: {
5849     match(&I, m_VScale(DAG.getDataLayout()));
5850     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5851     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5852     return;
5853   }
5854   case Intrinsic::vastart:  visitVAStart(I); return;
5855   case Intrinsic::vaend:    visitVAEnd(I); return;
5856   case Intrinsic::vacopy:   visitVACopy(I); return;
5857   case Intrinsic::returnaddress:
5858     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5859                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5860                              getValue(I.getArgOperand(0))));
5861     return;
5862   case Intrinsic::addressofreturnaddress:
5863     setValue(&I,
5864              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5865                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5866     return;
5867   case Intrinsic::sponentry:
5868     setValue(&I,
5869              DAG.getNode(ISD::SPONENTRY, sdl,
5870                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
5871     return;
5872   case Intrinsic::frameaddress:
5873     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5874                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5875                              getValue(I.getArgOperand(0))));
5876     return;
5877   case Intrinsic::read_volatile_register:
5878   case Intrinsic::read_register: {
5879     Value *Reg = I.getArgOperand(0);
5880     SDValue Chain = getRoot();
5881     SDValue RegName =
5882         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5883     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5884     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5885       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5886     setValue(&I, Res);
5887     DAG.setRoot(Res.getValue(1));
5888     return;
5889   }
5890   case Intrinsic::write_register: {
5891     Value *Reg = I.getArgOperand(0);
5892     Value *RegValue = I.getArgOperand(1);
5893     SDValue Chain = getRoot();
5894     SDValue RegName =
5895         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5896     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5897                             RegName, getValue(RegValue)));
5898     return;
5899   }
5900   case Intrinsic::memcpy: {
5901     const auto &MCI = cast<MemCpyInst>(I);
5902     SDValue Op1 = getValue(I.getArgOperand(0));
5903     SDValue Op2 = getValue(I.getArgOperand(1));
5904     SDValue Op3 = getValue(I.getArgOperand(2));
5905     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5906     Align DstAlign = MCI.getDestAlign().valueOrOne();
5907     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5908     Align Alignment = std::min(DstAlign, SrcAlign);
5909     bool isVol = MCI.isVolatile();
5910     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5911     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5912     // node.
5913     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5914     SDValue MC = DAG.getMemcpy(
5915         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5916         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
5917         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5918     updateDAGForMaybeTailCall(MC);
5919     return;
5920   }
5921   case Intrinsic::memcpy_inline: {
5922     const auto &MCI = cast<MemCpyInlineInst>(I);
5923     SDValue Dst = getValue(I.getArgOperand(0));
5924     SDValue Src = getValue(I.getArgOperand(1));
5925     SDValue Size = getValue(I.getArgOperand(2));
5926     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5927     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5928     Align DstAlign = MCI.getDestAlign().valueOrOne();
5929     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5930     Align Alignment = std::min(DstAlign, SrcAlign);
5931     bool isVol = MCI.isVolatile();
5932     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5933     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5934     // node.
5935     SDValue MC = DAG.getMemcpy(
5936         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5937         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
5938         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
5939     updateDAGForMaybeTailCall(MC);
5940     return;
5941   }
5942   case Intrinsic::memset: {
5943     const auto &MSI = cast<MemSetInst>(I);
5944     SDValue Op1 = getValue(I.getArgOperand(0));
5945     SDValue Op2 = getValue(I.getArgOperand(1));
5946     SDValue Op3 = getValue(I.getArgOperand(2));
5947     // @llvm.memset defines 0 and 1 to both mean no alignment.
5948     Align Alignment = MSI.getDestAlign().valueOrOne();
5949     bool isVol = MSI.isVolatile();
5950     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5951     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5952     SDValue MS = DAG.getMemset(
5953         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
5954         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
5955     updateDAGForMaybeTailCall(MS);
5956     return;
5957   }
5958   case Intrinsic::memset_inline: {
5959     const auto &MSII = cast<MemSetInlineInst>(I);
5960     SDValue Dst = getValue(I.getArgOperand(0));
5961     SDValue Value = getValue(I.getArgOperand(1));
5962     SDValue Size = getValue(I.getArgOperand(2));
5963     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
5964     // @llvm.memset defines 0 and 1 to both mean no alignment.
5965     Align DstAlign = MSII.getDestAlign().valueOrOne();
5966     bool isVol = MSII.isVolatile();
5967     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5968     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5969     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
5970                                /* AlwaysInline */ true, isTC,
5971                                MachinePointerInfo(I.getArgOperand(0)),
5972                                I.getAAMetadata());
5973     updateDAGForMaybeTailCall(MC);
5974     return;
5975   }
5976   case Intrinsic::memmove: {
5977     const auto &MMI = cast<MemMoveInst>(I);
5978     SDValue Op1 = getValue(I.getArgOperand(0));
5979     SDValue Op2 = getValue(I.getArgOperand(1));
5980     SDValue Op3 = getValue(I.getArgOperand(2));
5981     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5982     Align DstAlign = MMI.getDestAlign().valueOrOne();
5983     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5984     Align Alignment = std::min(DstAlign, SrcAlign);
5985     bool isVol = MMI.isVolatile();
5986     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5987     // FIXME: Support passing different dest/src alignments to the memmove DAG
5988     // node.
5989     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5990     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5991                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5992                                 MachinePointerInfo(I.getArgOperand(1)),
5993                                 I.getAAMetadata(), AA);
5994     updateDAGForMaybeTailCall(MM);
5995     return;
5996   }
5997   case Intrinsic::memcpy_element_unordered_atomic: {
5998     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5999     SDValue Dst = getValue(MI.getRawDest());
6000     SDValue Src = getValue(MI.getRawSource());
6001     SDValue Length = getValue(MI.getLength());
6002 
6003     Type *LengthTy = MI.getLength()->getType();
6004     unsigned ElemSz = MI.getElementSizeInBytes();
6005     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6006     SDValue MC =
6007         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6008                             isTC, MachinePointerInfo(MI.getRawDest()),
6009                             MachinePointerInfo(MI.getRawSource()));
6010     updateDAGForMaybeTailCall(MC);
6011     return;
6012   }
6013   case Intrinsic::memmove_element_unordered_atomic: {
6014     auto &MI = cast<AtomicMemMoveInst>(I);
6015     SDValue Dst = getValue(MI.getRawDest());
6016     SDValue Src = getValue(MI.getRawSource());
6017     SDValue Length = getValue(MI.getLength());
6018 
6019     Type *LengthTy = MI.getLength()->getType();
6020     unsigned ElemSz = MI.getElementSizeInBytes();
6021     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6022     SDValue MC =
6023         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6024                              isTC, MachinePointerInfo(MI.getRawDest()),
6025                              MachinePointerInfo(MI.getRawSource()));
6026     updateDAGForMaybeTailCall(MC);
6027     return;
6028   }
6029   case Intrinsic::memset_element_unordered_atomic: {
6030     auto &MI = cast<AtomicMemSetInst>(I);
6031     SDValue Dst = getValue(MI.getRawDest());
6032     SDValue Val = getValue(MI.getValue());
6033     SDValue Length = getValue(MI.getLength());
6034 
6035     Type *LengthTy = MI.getLength()->getType();
6036     unsigned ElemSz = MI.getElementSizeInBytes();
6037     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6038     SDValue MC =
6039         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6040                             isTC, MachinePointerInfo(MI.getRawDest()));
6041     updateDAGForMaybeTailCall(MC);
6042     return;
6043   }
6044   case Intrinsic::call_preallocated_setup: {
6045     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6046     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6047     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6048                               getRoot(), SrcValue);
6049     setValue(&I, Res);
6050     DAG.setRoot(Res);
6051     return;
6052   }
6053   case Intrinsic::call_preallocated_arg: {
6054     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6055     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6056     SDValue Ops[3];
6057     Ops[0] = getRoot();
6058     Ops[1] = SrcValue;
6059     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6060                                    MVT::i32); // arg index
6061     SDValue Res = DAG.getNode(
6062         ISD::PREALLOCATED_ARG, sdl,
6063         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6064     setValue(&I, Res);
6065     DAG.setRoot(Res.getValue(1));
6066     return;
6067   }
6068   case Intrinsic::dbg_addr:
6069   case Intrinsic::dbg_declare: {
6070     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6071     // they are non-variadic.
6072     const auto &DI = cast<DbgVariableIntrinsic>(I);
6073     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6074     DILocalVariable *Variable = DI.getVariable();
6075     DIExpression *Expression = DI.getExpression();
6076     dropDanglingDebugInfo(Variable, Expression);
6077     assert(Variable && "Missing variable");
6078     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6079                       << "\n");
6080     // Check if address has undef value.
6081     const Value *Address = DI.getVariableLocationOp(0);
6082     if (!Address || isa<UndefValue>(Address) ||
6083         (Address->use_empty() && !isa<Argument>(Address))) {
6084       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6085                         << " (bad/undef/unused-arg address)\n");
6086       return;
6087     }
6088 
6089     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6090 
6091     // Check if this variable can be described by a frame index, typically
6092     // either as a static alloca or a byval parameter.
6093     int FI = std::numeric_limits<int>::max();
6094     if (const auto *AI =
6095             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6096       if (AI->isStaticAlloca()) {
6097         auto I = FuncInfo.StaticAllocaMap.find(AI);
6098         if (I != FuncInfo.StaticAllocaMap.end())
6099           FI = I->second;
6100       }
6101     } else if (const auto *Arg = dyn_cast<Argument>(
6102                    Address->stripInBoundsConstantOffsets())) {
6103       FI = FuncInfo.getArgumentFrameIndex(Arg);
6104     }
6105 
6106     // llvm.dbg.addr is control dependent and always generates indirect
6107     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6108     // the MachineFunction variable table.
6109     if (FI != std::numeric_limits<int>::max()) {
6110       if (Intrinsic == Intrinsic::dbg_addr) {
6111         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6112             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6113             dl, SDNodeOrder);
6114         DAG.AddDbgValue(SDV, isParameter);
6115       } else {
6116         LLVM_DEBUG(dbgs() << "Skipping " << DI
6117                           << " (variable info stashed in MF side table)\n");
6118       }
6119       return;
6120     }
6121 
6122     SDValue &N = NodeMap[Address];
6123     if (!N.getNode() && isa<Argument>(Address))
6124       // Check unused arguments map.
6125       N = UnusedArgNodeMap[Address];
6126     SDDbgValue *SDV;
6127     if (N.getNode()) {
6128       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6129         Address = BCI->getOperand(0);
6130       // Parameters are handled specially.
6131       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6132       if (isParameter && FINode) {
6133         // Byval parameter. We have a frame index at this point.
6134         SDV =
6135             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6136                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6137       } else if (isa<Argument>(Address)) {
6138         // Address is an argument, so try to emit its dbg value using
6139         // virtual register info from the FuncInfo.ValueMap.
6140         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6141                                  FuncArgumentDbgValueKind::Declare, N);
6142         return;
6143       } else {
6144         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6145                               true, dl, SDNodeOrder);
6146       }
6147       DAG.AddDbgValue(SDV, isParameter);
6148     } else {
6149       // If Address is an argument then try to emit its dbg value using
6150       // virtual register info from the FuncInfo.ValueMap.
6151       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl,
6152                                     FuncArgumentDbgValueKind::Declare, N)) {
6153         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6154                           << " (could not emit func-arg dbg_value)\n");
6155       }
6156     }
6157     return;
6158   }
6159   case Intrinsic::dbg_label: {
6160     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6161     DILabel *Label = DI.getLabel();
6162     assert(Label && "Missing label");
6163 
6164     SDDbgLabel *SDV;
6165     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6166     DAG.AddDbgLabel(SDV);
6167     return;
6168   }
6169   case Intrinsic::dbg_value: {
6170     const DbgValueInst &DI = cast<DbgValueInst>(I);
6171     assert(DI.getVariable() && "Missing variable");
6172 
6173     DILocalVariable *Variable = DI.getVariable();
6174     DIExpression *Expression = DI.getExpression();
6175     dropDanglingDebugInfo(Variable, Expression);
6176     SmallVector<Value *, 4> Values(DI.getValues());
6177     if (Values.empty())
6178       return;
6179 
6180     if (llvm::is_contained(Values, nullptr))
6181       return;
6182 
6183     bool IsVariadic = DI.hasArgList();
6184     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6185                           SDNodeOrder, IsVariadic))
6186       addDanglingDebugInfo(&DI, DI.getDebugLoc(), SDNodeOrder);
6187     return;
6188   }
6189 
6190   case Intrinsic::eh_typeid_for: {
6191     // Find the type id for the given typeinfo.
6192     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6193     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6194     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6195     setValue(&I, Res);
6196     return;
6197   }
6198 
6199   case Intrinsic::eh_return_i32:
6200   case Intrinsic::eh_return_i64:
6201     DAG.getMachineFunction().setCallsEHReturn(true);
6202     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6203                             MVT::Other,
6204                             getControlRoot(),
6205                             getValue(I.getArgOperand(0)),
6206                             getValue(I.getArgOperand(1))));
6207     return;
6208   case Intrinsic::eh_unwind_init:
6209     DAG.getMachineFunction().setCallsUnwindInit(true);
6210     return;
6211   case Intrinsic::eh_dwarf_cfa:
6212     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6213                              TLI.getPointerTy(DAG.getDataLayout()),
6214                              getValue(I.getArgOperand(0))));
6215     return;
6216   case Intrinsic::eh_sjlj_callsite: {
6217     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6218     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6219     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6220 
6221     MMI.setCurrentCallSite(CI->getZExtValue());
6222     return;
6223   }
6224   case Intrinsic::eh_sjlj_functioncontext: {
6225     // Get and store the index of the function context.
6226     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6227     AllocaInst *FnCtx =
6228       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6229     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6230     MFI.setFunctionContextIndex(FI);
6231     return;
6232   }
6233   case Intrinsic::eh_sjlj_setjmp: {
6234     SDValue Ops[2];
6235     Ops[0] = getRoot();
6236     Ops[1] = getValue(I.getArgOperand(0));
6237     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6238                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6239     setValue(&I, Op.getValue(0));
6240     DAG.setRoot(Op.getValue(1));
6241     return;
6242   }
6243   case Intrinsic::eh_sjlj_longjmp:
6244     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6245                             getRoot(), getValue(I.getArgOperand(0))));
6246     return;
6247   case Intrinsic::eh_sjlj_setup_dispatch:
6248     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6249                             getRoot()));
6250     return;
6251   case Intrinsic::masked_gather:
6252     visitMaskedGather(I);
6253     return;
6254   case Intrinsic::masked_load:
6255     visitMaskedLoad(I);
6256     return;
6257   case Intrinsic::masked_scatter:
6258     visitMaskedScatter(I);
6259     return;
6260   case Intrinsic::masked_store:
6261     visitMaskedStore(I);
6262     return;
6263   case Intrinsic::masked_expandload:
6264     visitMaskedLoad(I, true /* IsExpanding */);
6265     return;
6266   case Intrinsic::masked_compressstore:
6267     visitMaskedStore(I, true /* IsCompressing */);
6268     return;
6269   case Intrinsic::powi:
6270     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6271                             getValue(I.getArgOperand(1)), DAG));
6272     return;
6273   case Intrinsic::log:
6274     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6275     return;
6276   case Intrinsic::log2:
6277     setValue(&I,
6278              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6279     return;
6280   case Intrinsic::log10:
6281     setValue(&I,
6282              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6283     return;
6284   case Intrinsic::exp:
6285     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6286     return;
6287   case Intrinsic::exp2:
6288     setValue(&I,
6289              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6290     return;
6291   case Intrinsic::pow:
6292     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6293                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6294     return;
6295   case Intrinsic::sqrt:
6296   case Intrinsic::fabs:
6297   case Intrinsic::sin:
6298   case Intrinsic::cos:
6299   case Intrinsic::floor:
6300   case Intrinsic::ceil:
6301   case Intrinsic::trunc:
6302   case Intrinsic::rint:
6303   case Intrinsic::nearbyint:
6304   case Intrinsic::round:
6305   case Intrinsic::roundeven:
6306   case Intrinsic::canonicalize: {
6307     unsigned Opcode;
6308     switch (Intrinsic) {
6309     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6310     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6311     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6312     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6313     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6314     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6315     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6316     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6317     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6318     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6319     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6320     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6321     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6322     }
6323 
6324     setValue(&I, DAG.getNode(Opcode, sdl,
6325                              getValue(I.getArgOperand(0)).getValueType(),
6326                              getValue(I.getArgOperand(0)), Flags));
6327     return;
6328   }
6329   case Intrinsic::lround:
6330   case Intrinsic::llround:
6331   case Intrinsic::lrint:
6332   case Intrinsic::llrint: {
6333     unsigned Opcode;
6334     switch (Intrinsic) {
6335     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6336     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6337     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6338     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6339     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6340     }
6341 
6342     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6343     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6344                              getValue(I.getArgOperand(0))));
6345     return;
6346   }
6347   case Intrinsic::minnum:
6348     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6349                              getValue(I.getArgOperand(0)).getValueType(),
6350                              getValue(I.getArgOperand(0)),
6351                              getValue(I.getArgOperand(1)), Flags));
6352     return;
6353   case Intrinsic::maxnum:
6354     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6355                              getValue(I.getArgOperand(0)).getValueType(),
6356                              getValue(I.getArgOperand(0)),
6357                              getValue(I.getArgOperand(1)), Flags));
6358     return;
6359   case Intrinsic::minimum:
6360     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6361                              getValue(I.getArgOperand(0)).getValueType(),
6362                              getValue(I.getArgOperand(0)),
6363                              getValue(I.getArgOperand(1)), Flags));
6364     return;
6365   case Intrinsic::maximum:
6366     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6367                              getValue(I.getArgOperand(0)).getValueType(),
6368                              getValue(I.getArgOperand(0)),
6369                              getValue(I.getArgOperand(1)), Flags));
6370     return;
6371   case Intrinsic::copysign:
6372     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6373                              getValue(I.getArgOperand(0)).getValueType(),
6374                              getValue(I.getArgOperand(0)),
6375                              getValue(I.getArgOperand(1)), Flags));
6376     return;
6377   case Intrinsic::arithmetic_fence: {
6378     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6379                              getValue(I.getArgOperand(0)).getValueType(),
6380                              getValue(I.getArgOperand(0)), Flags));
6381     return;
6382   }
6383   case Intrinsic::fma:
6384     setValue(&I, DAG.getNode(
6385                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6386                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6387                      getValue(I.getArgOperand(2)), Flags));
6388     return;
6389 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6390   case Intrinsic::INTRINSIC:
6391 #include "llvm/IR/ConstrainedOps.def"
6392     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6393     return;
6394 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6395 #include "llvm/IR/VPIntrinsics.def"
6396     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6397     return;
6398   case Intrinsic::fptrunc_round: {
6399     // Get the last argument, the metadata and convert it to an integer in the
6400     // call
6401     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6402     Optional<RoundingMode> RoundMode =
6403         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6404 
6405     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6406 
6407     // Propagate fast-math-flags from IR to node(s).
6408     SDNodeFlags Flags;
6409     Flags.copyFMF(*cast<FPMathOperator>(&I));
6410     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6411 
6412     SDValue Result;
6413     Result = DAG.getNode(
6414         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6415         DAG.getTargetConstant((int)*RoundMode, sdl,
6416                               TLI.getPointerTy(DAG.getDataLayout())));
6417     setValue(&I, Result);
6418 
6419     return;
6420   }
6421   case Intrinsic::fmuladd: {
6422     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6423     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6424         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6425       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6426                                getValue(I.getArgOperand(0)).getValueType(),
6427                                getValue(I.getArgOperand(0)),
6428                                getValue(I.getArgOperand(1)),
6429                                getValue(I.getArgOperand(2)), Flags));
6430     } else {
6431       // TODO: Intrinsic calls should have fast-math-flags.
6432       SDValue Mul = DAG.getNode(
6433           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6434           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6435       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6436                                 getValue(I.getArgOperand(0)).getValueType(),
6437                                 Mul, getValue(I.getArgOperand(2)), Flags);
6438       setValue(&I, Add);
6439     }
6440     return;
6441   }
6442   case Intrinsic::convert_to_fp16:
6443     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6444                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6445                                          getValue(I.getArgOperand(0)),
6446                                          DAG.getTargetConstant(0, sdl,
6447                                                                MVT::i32))));
6448     return;
6449   case Intrinsic::convert_from_fp16:
6450     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6451                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6452                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6453                                          getValue(I.getArgOperand(0)))));
6454     return;
6455   case Intrinsic::fptosi_sat: {
6456     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6457     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6458                              getValue(I.getArgOperand(0)),
6459                              DAG.getValueType(VT.getScalarType())));
6460     return;
6461   }
6462   case Intrinsic::fptoui_sat: {
6463     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6464     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6465                              getValue(I.getArgOperand(0)),
6466                              DAG.getValueType(VT.getScalarType())));
6467     return;
6468   }
6469   case Intrinsic::set_rounding:
6470     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6471                       {getRoot(), getValue(I.getArgOperand(0))});
6472     setValue(&I, Res);
6473     DAG.setRoot(Res.getValue(0));
6474     return;
6475   case Intrinsic::is_fpclass: {
6476     const DataLayout DLayout = DAG.getDataLayout();
6477     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6478     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6479     unsigned Test = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6480     MachineFunction &MF = DAG.getMachineFunction();
6481     const Function &F = MF.getFunction();
6482     SDValue Op = getValue(I.getArgOperand(0));
6483     SDNodeFlags Flags;
6484     Flags.setNoFPExcept(
6485         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6486     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6487     // expansion can use illegal types. Making expansion early allows
6488     // legalizing these types prior to selection.
6489     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6490       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6491       setValue(&I, Result);
6492       return;
6493     }
6494 
6495     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6496     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6497     setValue(&I, V);
6498     return;
6499   }
6500   case Intrinsic::pcmarker: {
6501     SDValue Tmp = getValue(I.getArgOperand(0));
6502     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6503     return;
6504   }
6505   case Intrinsic::readcyclecounter: {
6506     SDValue Op = getRoot();
6507     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6508                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6509     setValue(&I, Res);
6510     DAG.setRoot(Res.getValue(1));
6511     return;
6512   }
6513   case Intrinsic::bitreverse:
6514     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6515                              getValue(I.getArgOperand(0)).getValueType(),
6516                              getValue(I.getArgOperand(0))));
6517     return;
6518   case Intrinsic::bswap:
6519     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6520                              getValue(I.getArgOperand(0)).getValueType(),
6521                              getValue(I.getArgOperand(0))));
6522     return;
6523   case Intrinsic::cttz: {
6524     SDValue Arg = getValue(I.getArgOperand(0));
6525     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6526     EVT Ty = Arg.getValueType();
6527     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6528                              sdl, Ty, Arg));
6529     return;
6530   }
6531   case Intrinsic::ctlz: {
6532     SDValue Arg = getValue(I.getArgOperand(0));
6533     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6534     EVT Ty = Arg.getValueType();
6535     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6536                              sdl, Ty, Arg));
6537     return;
6538   }
6539   case Intrinsic::ctpop: {
6540     SDValue Arg = getValue(I.getArgOperand(0));
6541     EVT Ty = Arg.getValueType();
6542     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6543     return;
6544   }
6545   case Intrinsic::fshl:
6546   case Intrinsic::fshr: {
6547     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6548     SDValue X = getValue(I.getArgOperand(0));
6549     SDValue Y = getValue(I.getArgOperand(1));
6550     SDValue Z = getValue(I.getArgOperand(2));
6551     EVT VT = X.getValueType();
6552 
6553     if (X == Y) {
6554       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6555       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6556     } else {
6557       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6558       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6559     }
6560     return;
6561   }
6562   case Intrinsic::sadd_sat: {
6563     SDValue Op1 = getValue(I.getArgOperand(0));
6564     SDValue Op2 = getValue(I.getArgOperand(1));
6565     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6566     return;
6567   }
6568   case Intrinsic::uadd_sat: {
6569     SDValue Op1 = getValue(I.getArgOperand(0));
6570     SDValue Op2 = getValue(I.getArgOperand(1));
6571     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6572     return;
6573   }
6574   case Intrinsic::ssub_sat: {
6575     SDValue Op1 = getValue(I.getArgOperand(0));
6576     SDValue Op2 = getValue(I.getArgOperand(1));
6577     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6578     return;
6579   }
6580   case Intrinsic::usub_sat: {
6581     SDValue Op1 = getValue(I.getArgOperand(0));
6582     SDValue Op2 = getValue(I.getArgOperand(1));
6583     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6584     return;
6585   }
6586   case Intrinsic::sshl_sat: {
6587     SDValue Op1 = getValue(I.getArgOperand(0));
6588     SDValue Op2 = getValue(I.getArgOperand(1));
6589     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6590     return;
6591   }
6592   case Intrinsic::ushl_sat: {
6593     SDValue Op1 = getValue(I.getArgOperand(0));
6594     SDValue Op2 = getValue(I.getArgOperand(1));
6595     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6596     return;
6597   }
6598   case Intrinsic::smul_fix:
6599   case Intrinsic::umul_fix:
6600   case Intrinsic::smul_fix_sat:
6601   case Intrinsic::umul_fix_sat: {
6602     SDValue Op1 = getValue(I.getArgOperand(0));
6603     SDValue Op2 = getValue(I.getArgOperand(1));
6604     SDValue Op3 = getValue(I.getArgOperand(2));
6605     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6606                              Op1.getValueType(), Op1, Op2, Op3));
6607     return;
6608   }
6609   case Intrinsic::sdiv_fix:
6610   case Intrinsic::udiv_fix:
6611   case Intrinsic::sdiv_fix_sat:
6612   case Intrinsic::udiv_fix_sat: {
6613     SDValue Op1 = getValue(I.getArgOperand(0));
6614     SDValue Op2 = getValue(I.getArgOperand(1));
6615     SDValue Op3 = getValue(I.getArgOperand(2));
6616     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6617                               Op1, Op2, Op3, DAG, TLI));
6618     return;
6619   }
6620   case Intrinsic::smax: {
6621     SDValue Op1 = getValue(I.getArgOperand(0));
6622     SDValue Op2 = getValue(I.getArgOperand(1));
6623     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6624     return;
6625   }
6626   case Intrinsic::smin: {
6627     SDValue Op1 = getValue(I.getArgOperand(0));
6628     SDValue Op2 = getValue(I.getArgOperand(1));
6629     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6630     return;
6631   }
6632   case Intrinsic::umax: {
6633     SDValue Op1 = getValue(I.getArgOperand(0));
6634     SDValue Op2 = getValue(I.getArgOperand(1));
6635     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6636     return;
6637   }
6638   case Intrinsic::umin: {
6639     SDValue Op1 = getValue(I.getArgOperand(0));
6640     SDValue Op2 = getValue(I.getArgOperand(1));
6641     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6642     return;
6643   }
6644   case Intrinsic::abs: {
6645     // TODO: Preserve "int min is poison" arg in SDAG?
6646     SDValue Op1 = getValue(I.getArgOperand(0));
6647     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6648     return;
6649   }
6650   case Intrinsic::stacksave: {
6651     SDValue Op = getRoot();
6652     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6653     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6654     setValue(&I, Res);
6655     DAG.setRoot(Res.getValue(1));
6656     return;
6657   }
6658   case Intrinsic::stackrestore:
6659     Res = getValue(I.getArgOperand(0));
6660     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6661     return;
6662   case Intrinsic::get_dynamic_area_offset: {
6663     SDValue Op = getRoot();
6664     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6665     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6666     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6667     // target.
6668     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6669       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6670                          " intrinsic!");
6671     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6672                       Op);
6673     DAG.setRoot(Op);
6674     setValue(&I, Res);
6675     return;
6676   }
6677   case Intrinsic::stackguard: {
6678     MachineFunction &MF = DAG.getMachineFunction();
6679     const Module &M = *MF.getFunction().getParent();
6680     SDValue Chain = getRoot();
6681     if (TLI.useLoadStackGuardNode()) {
6682       Res = getLoadStackGuard(DAG, sdl, Chain);
6683     } else {
6684       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6685       const Value *Global = TLI.getSDagStackGuard(M);
6686       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6687       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6688                         MachinePointerInfo(Global, 0), Align,
6689                         MachineMemOperand::MOVolatile);
6690     }
6691     if (TLI.useStackGuardXorFP())
6692       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6693     DAG.setRoot(Chain);
6694     setValue(&I, Res);
6695     return;
6696   }
6697   case Intrinsic::stackprotector: {
6698     // Emit code into the DAG to store the stack guard onto the stack.
6699     MachineFunction &MF = DAG.getMachineFunction();
6700     MachineFrameInfo &MFI = MF.getFrameInfo();
6701     SDValue Src, Chain = getRoot();
6702 
6703     if (TLI.useLoadStackGuardNode())
6704       Src = getLoadStackGuard(DAG, sdl, Chain);
6705     else
6706       Src = getValue(I.getArgOperand(0));   // The guard's value.
6707 
6708     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6709 
6710     int FI = FuncInfo.StaticAllocaMap[Slot];
6711     MFI.setStackProtectorIndex(FI);
6712     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6713 
6714     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6715 
6716     // Store the stack protector onto the stack.
6717     Res = DAG.getStore(
6718         Chain, sdl, Src, FIN,
6719         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6720         MaybeAlign(), MachineMemOperand::MOVolatile);
6721     setValue(&I, Res);
6722     DAG.setRoot(Res);
6723     return;
6724   }
6725   case Intrinsic::objectsize:
6726     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6727 
6728   case Intrinsic::is_constant:
6729     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6730 
6731   case Intrinsic::annotation:
6732   case Intrinsic::ptr_annotation:
6733   case Intrinsic::launder_invariant_group:
6734   case Intrinsic::strip_invariant_group:
6735     // Drop the intrinsic, but forward the value
6736     setValue(&I, getValue(I.getOperand(0)));
6737     return;
6738 
6739   case Intrinsic::assume:
6740   case Intrinsic::experimental_noalias_scope_decl:
6741   case Intrinsic::var_annotation:
6742   case Intrinsic::sideeffect:
6743     // Discard annotate attributes, noalias scope declarations, assumptions, and
6744     // artificial side-effects.
6745     return;
6746 
6747   case Intrinsic::codeview_annotation: {
6748     // Emit a label associated with this metadata.
6749     MachineFunction &MF = DAG.getMachineFunction();
6750     MCSymbol *Label =
6751         MF.getMMI().getContext().createTempSymbol("annotation", true);
6752     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6753     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6754     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6755     DAG.setRoot(Res);
6756     return;
6757   }
6758 
6759   case Intrinsic::init_trampoline: {
6760     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6761 
6762     SDValue Ops[6];
6763     Ops[0] = getRoot();
6764     Ops[1] = getValue(I.getArgOperand(0));
6765     Ops[2] = getValue(I.getArgOperand(1));
6766     Ops[3] = getValue(I.getArgOperand(2));
6767     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6768     Ops[5] = DAG.getSrcValue(F);
6769 
6770     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6771 
6772     DAG.setRoot(Res);
6773     return;
6774   }
6775   case Intrinsic::adjust_trampoline:
6776     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6777                              TLI.getPointerTy(DAG.getDataLayout()),
6778                              getValue(I.getArgOperand(0))));
6779     return;
6780   case Intrinsic::gcroot: {
6781     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6782            "only valid in functions with gc specified, enforced by Verifier");
6783     assert(GFI && "implied by previous");
6784     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6785     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6786 
6787     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6788     GFI->addStackRoot(FI->getIndex(), TypeMap);
6789     return;
6790   }
6791   case Intrinsic::gcread:
6792   case Intrinsic::gcwrite:
6793     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6794   case Intrinsic::flt_rounds:
6795     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6796     setValue(&I, Res);
6797     DAG.setRoot(Res.getValue(1));
6798     return;
6799 
6800   case Intrinsic::expect:
6801     // Just replace __builtin_expect(exp, c) with EXP.
6802     setValue(&I, getValue(I.getArgOperand(0)));
6803     return;
6804 
6805   case Intrinsic::ubsantrap:
6806   case Intrinsic::debugtrap:
6807   case Intrinsic::trap: {
6808     StringRef TrapFuncName =
6809         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6810     if (TrapFuncName.empty()) {
6811       switch (Intrinsic) {
6812       case Intrinsic::trap:
6813         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6814         break;
6815       case Intrinsic::debugtrap:
6816         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6817         break;
6818       case Intrinsic::ubsantrap:
6819         DAG.setRoot(DAG.getNode(
6820             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6821             DAG.getTargetConstant(
6822                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6823                 MVT::i32)));
6824         break;
6825       default: llvm_unreachable("unknown trap intrinsic");
6826       }
6827       return;
6828     }
6829     TargetLowering::ArgListTy Args;
6830     if (Intrinsic == Intrinsic::ubsantrap) {
6831       Args.push_back(TargetLoweringBase::ArgListEntry());
6832       Args[0].Val = I.getArgOperand(0);
6833       Args[0].Node = getValue(Args[0].Val);
6834       Args[0].Ty = Args[0].Val->getType();
6835     }
6836 
6837     TargetLowering::CallLoweringInfo CLI(DAG);
6838     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6839         CallingConv::C, I.getType(),
6840         DAG.getExternalSymbol(TrapFuncName.data(),
6841                               TLI.getPointerTy(DAG.getDataLayout())),
6842         std::move(Args));
6843 
6844     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6845     DAG.setRoot(Result.second);
6846     return;
6847   }
6848 
6849   case Intrinsic::uadd_with_overflow:
6850   case Intrinsic::sadd_with_overflow:
6851   case Intrinsic::usub_with_overflow:
6852   case Intrinsic::ssub_with_overflow:
6853   case Intrinsic::umul_with_overflow:
6854   case Intrinsic::smul_with_overflow: {
6855     ISD::NodeType Op;
6856     switch (Intrinsic) {
6857     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6858     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6859     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6860     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6861     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6862     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6863     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6864     }
6865     SDValue Op1 = getValue(I.getArgOperand(0));
6866     SDValue Op2 = getValue(I.getArgOperand(1));
6867 
6868     EVT ResultVT = Op1.getValueType();
6869     EVT OverflowVT = MVT::i1;
6870     if (ResultVT.isVector())
6871       OverflowVT = EVT::getVectorVT(
6872           *Context, OverflowVT, ResultVT.getVectorElementCount());
6873 
6874     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6875     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6876     return;
6877   }
6878   case Intrinsic::prefetch: {
6879     SDValue Ops[5];
6880     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6881     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6882     Ops[0] = DAG.getRoot();
6883     Ops[1] = getValue(I.getArgOperand(0));
6884     Ops[2] = getValue(I.getArgOperand(1));
6885     Ops[3] = getValue(I.getArgOperand(2));
6886     Ops[4] = getValue(I.getArgOperand(3));
6887     SDValue Result = DAG.getMemIntrinsicNode(
6888         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6889         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6890         /* align */ None, Flags);
6891 
6892     // Chain the prefetch in parallell with any pending loads, to stay out of
6893     // the way of later optimizations.
6894     PendingLoads.push_back(Result);
6895     Result = getRoot();
6896     DAG.setRoot(Result);
6897     return;
6898   }
6899   case Intrinsic::lifetime_start:
6900   case Intrinsic::lifetime_end: {
6901     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6902     // Stack coloring is not enabled in O0, discard region information.
6903     if (TM.getOptLevel() == CodeGenOpt::None)
6904       return;
6905 
6906     const int64_t ObjectSize =
6907         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6908     Value *const ObjectPtr = I.getArgOperand(1);
6909     SmallVector<const Value *, 4> Allocas;
6910     getUnderlyingObjects(ObjectPtr, Allocas);
6911 
6912     for (const Value *Alloca : Allocas) {
6913       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6914 
6915       // Could not find an Alloca.
6916       if (!LifetimeObject)
6917         continue;
6918 
6919       // First check that the Alloca is static, otherwise it won't have a
6920       // valid frame index.
6921       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6922       if (SI == FuncInfo.StaticAllocaMap.end())
6923         return;
6924 
6925       const int FrameIndex = SI->second;
6926       int64_t Offset;
6927       if (GetPointerBaseWithConstantOffset(
6928               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6929         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6930       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6931                                 Offset);
6932       DAG.setRoot(Res);
6933     }
6934     return;
6935   }
6936   case Intrinsic::pseudoprobe: {
6937     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6938     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6939     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6940     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6941     DAG.setRoot(Res);
6942     return;
6943   }
6944   case Intrinsic::invariant_start:
6945     // Discard region information.
6946     setValue(&I,
6947              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
6948     return;
6949   case Intrinsic::invariant_end:
6950     // Discard region information.
6951     return;
6952   case Intrinsic::clear_cache:
6953     /// FunctionName may be null.
6954     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6955       lowerCallToExternalSymbol(I, FunctionName);
6956     return;
6957   case Intrinsic::donothing:
6958   case Intrinsic::seh_try_begin:
6959   case Intrinsic::seh_scope_begin:
6960   case Intrinsic::seh_try_end:
6961   case Intrinsic::seh_scope_end:
6962     // ignore
6963     return;
6964   case Intrinsic::experimental_stackmap:
6965     visitStackmap(I);
6966     return;
6967   case Intrinsic::experimental_patchpoint_void:
6968   case Intrinsic::experimental_patchpoint_i64:
6969     visitPatchpoint(I);
6970     return;
6971   case Intrinsic::experimental_gc_statepoint:
6972     LowerStatepoint(cast<GCStatepointInst>(I));
6973     return;
6974   case Intrinsic::experimental_gc_result:
6975     visitGCResult(cast<GCResultInst>(I));
6976     return;
6977   case Intrinsic::experimental_gc_relocate:
6978     visitGCRelocate(cast<GCRelocateInst>(I));
6979     return;
6980   case Intrinsic::instrprof_cover:
6981     llvm_unreachable("instrprof failed to lower a cover");
6982   case Intrinsic::instrprof_increment:
6983     llvm_unreachable("instrprof failed to lower an increment");
6984   case Intrinsic::instrprof_value_profile:
6985     llvm_unreachable("instrprof failed to lower a value profiling call");
6986   case Intrinsic::localescape: {
6987     MachineFunction &MF = DAG.getMachineFunction();
6988     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6989 
6990     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6991     // is the same on all targets.
6992     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6993       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6994       if (isa<ConstantPointerNull>(Arg))
6995         continue; // Skip null pointers. They represent a hole in index space.
6996       AllocaInst *Slot = cast<AllocaInst>(Arg);
6997       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6998              "can only escape static allocas");
6999       int FI = FuncInfo.StaticAllocaMap[Slot];
7000       MCSymbol *FrameAllocSym =
7001           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7002               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7003       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7004               TII->get(TargetOpcode::LOCAL_ESCAPE))
7005           .addSym(FrameAllocSym)
7006           .addFrameIndex(FI);
7007     }
7008 
7009     return;
7010   }
7011 
7012   case Intrinsic::localrecover: {
7013     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7014     MachineFunction &MF = DAG.getMachineFunction();
7015 
7016     // Get the symbol that defines the frame offset.
7017     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7018     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7019     unsigned IdxVal =
7020         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7021     MCSymbol *FrameAllocSym =
7022         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7023             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7024 
7025     Value *FP = I.getArgOperand(1);
7026     SDValue FPVal = getValue(FP);
7027     EVT PtrVT = FPVal.getValueType();
7028 
7029     // Create a MCSymbol for the label to avoid any target lowering
7030     // that would make this PC relative.
7031     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7032     SDValue OffsetVal =
7033         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7034 
7035     // Add the offset to the FP.
7036     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7037     setValue(&I, Add);
7038 
7039     return;
7040   }
7041 
7042   case Intrinsic::eh_exceptionpointer:
7043   case Intrinsic::eh_exceptioncode: {
7044     // Get the exception pointer vreg, copy from it, and resize it to fit.
7045     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7046     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7047     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7048     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7049     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7050     if (Intrinsic == Intrinsic::eh_exceptioncode)
7051       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7052     setValue(&I, N);
7053     return;
7054   }
7055   case Intrinsic::xray_customevent: {
7056     // Here we want to make sure that the intrinsic behaves as if it has a
7057     // specific calling convention, and only for x86_64.
7058     // FIXME: Support other platforms later.
7059     const auto &Triple = DAG.getTarget().getTargetTriple();
7060     if (Triple.getArch() != Triple::x86_64)
7061       return;
7062 
7063     SmallVector<SDValue, 8> Ops;
7064 
7065     // We want to say that we always want the arguments in registers.
7066     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7067     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7068     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7069     SDValue Chain = getRoot();
7070     Ops.push_back(LogEntryVal);
7071     Ops.push_back(StrSizeVal);
7072     Ops.push_back(Chain);
7073 
7074     // We need to enforce the calling convention for the callsite, so that
7075     // argument ordering is enforced correctly, and that register allocation can
7076     // see that some registers may be assumed clobbered and have to preserve
7077     // them across calls to the intrinsic.
7078     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7079                                            sdl, NodeTys, Ops);
7080     SDValue patchableNode = SDValue(MN, 0);
7081     DAG.setRoot(patchableNode);
7082     setValue(&I, patchableNode);
7083     return;
7084   }
7085   case Intrinsic::xray_typedevent: {
7086     // Here we want to make sure that the intrinsic behaves as if it has a
7087     // specific calling convention, and only for x86_64.
7088     // FIXME: Support other platforms later.
7089     const auto &Triple = DAG.getTarget().getTargetTriple();
7090     if (Triple.getArch() != Triple::x86_64)
7091       return;
7092 
7093     SmallVector<SDValue, 8> Ops;
7094 
7095     // We want to say that we always want the arguments in registers.
7096     // It's unclear to me how manipulating the selection DAG here forces callers
7097     // to provide arguments in registers instead of on the stack.
7098     SDValue LogTypeId = getValue(I.getArgOperand(0));
7099     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7100     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7101     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7102     SDValue Chain = getRoot();
7103     Ops.push_back(LogTypeId);
7104     Ops.push_back(LogEntryVal);
7105     Ops.push_back(StrSizeVal);
7106     Ops.push_back(Chain);
7107 
7108     // We need to enforce the calling convention for the callsite, so that
7109     // argument ordering is enforced correctly, and that register allocation can
7110     // see that some registers may be assumed clobbered and have to preserve
7111     // them across calls to the intrinsic.
7112     MachineSDNode *MN = DAG.getMachineNode(
7113         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7114     SDValue patchableNode = SDValue(MN, 0);
7115     DAG.setRoot(patchableNode);
7116     setValue(&I, patchableNode);
7117     return;
7118   }
7119   case Intrinsic::experimental_deoptimize:
7120     LowerDeoptimizeCall(&I);
7121     return;
7122   case Intrinsic::experimental_stepvector:
7123     visitStepVector(I);
7124     return;
7125   case Intrinsic::vector_reduce_fadd:
7126   case Intrinsic::vector_reduce_fmul:
7127   case Intrinsic::vector_reduce_add:
7128   case Intrinsic::vector_reduce_mul:
7129   case Intrinsic::vector_reduce_and:
7130   case Intrinsic::vector_reduce_or:
7131   case Intrinsic::vector_reduce_xor:
7132   case Intrinsic::vector_reduce_smax:
7133   case Intrinsic::vector_reduce_smin:
7134   case Intrinsic::vector_reduce_umax:
7135   case Intrinsic::vector_reduce_umin:
7136   case Intrinsic::vector_reduce_fmax:
7137   case Intrinsic::vector_reduce_fmin:
7138     visitVectorReduce(I, Intrinsic);
7139     return;
7140 
7141   case Intrinsic::icall_branch_funnel: {
7142     SmallVector<SDValue, 16> Ops;
7143     Ops.push_back(getValue(I.getArgOperand(0)));
7144 
7145     int64_t Offset;
7146     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7147         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7148     if (!Base)
7149       report_fatal_error(
7150           "llvm.icall.branch.funnel operand must be a GlobalValue");
7151     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7152 
7153     struct BranchFunnelTarget {
7154       int64_t Offset;
7155       SDValue Target;
7156     };
7157     SmallVector<BranchFunnelTarget, 8> Targets;
7158 
7159     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7160       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7161           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7162       if (ElemBase != Base)
7163         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7164                            "to the same GlobalValue");
7165 
7166       SDValue Val = getValue(I.getArgOperand(Op + 1));
7167       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7168       if (!GA)
7169         report_fatal_error(
7170             "llvm.icall.branch.funnel operand must be a GlobalValue");
7171       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7172                                      GA->getGlobal(), sdl, Val.getValueType(),
7173                                      GA->getOffset())});
7174     }
7175     llvm::sort(Targets,
7176                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7177                  return T1.Offset < T2.Offset;
7178                });
7179 
7180     for (auto &T : Targets) {
7181       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7182       Ops.push_back(T.Target);
7183     }
7184 
7185     Ops.push_back(DAG.getRoot()); // Chain
7186     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7187                                  MVT::Other, Ops),
7188               0);
7189     DAG.setRoot(N);
7190     setValue(&I, N);
7191     HasTailCall = true;
7192     return;
7193   }
7194 
7195   case Intrinsic::wasm_landingpad_index:
7196     // Information this intrinsic contained has been transferred to
7197     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7198     // delete it now.
7199     return;
7200 
7201   case Intrinsic::aarch64_settag:
7202   case Intrinsic::aarch64_settag_zero: {
7203     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7204     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7205     SDValue Val = TSI.EmitTargetCodeForSetTag(
7206         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7207         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7208         ZeroMemory);
7209     DAG.setRoot(Val);
7210     setValue(&I, Val);
7211     return;
7212   }
7213   case Intrinsic::ptrmask: {
7214     SDValue Ptr = getValue(I.getOperand(0));
7215     SDValue Const = getValue(I.getOperand(1));
7216 
7217     EVT PtrVT = Ptr.getValueType();
7218     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7219                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7220     return;
7221   }
7222   case Intrinsic::threadlocal_address: {
7223     setValue(&I, getValue(I.getOperand(0)));
7224     return;
7225   }
7226   case Intrinsic::get_active_lane_mask: {
7227     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7228     SDValue Index = getValue(I.getOperand(0));
7229     EVT ElementVT = Index.getValueType();
7230 
7231     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7232       visitTargetIntrinsic(I, Intrinsic);
7233       return;
7234     }
7235 
7236     SDValue TripCount = getValue(I.getOperand(1));
7237     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7238 
7239     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7240     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7241     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7242     SDValue VectorInduction = DAG.getNode(
7243         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7244     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7245                                  VectorTripCount, ISD::CondCode::SETULT);
7246     setValue(&I, SetCC);
7247     return;
7248   }
7249   case Intrinsic::vector_insert: {
7250     SDValue Vec = getValue(I.getOperand(0));
7251     SDValue SubVec = getValue(I.getOperand(1));
7252     SDValue Index = getValue(I.getOperand(2));
7253 
7254     // The intrinsic's index type is i64, but the SDNode requires an index type
7255     // suitable for the target. Convert the index as required.
7256     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7257     if (Index.getValueType() != VectorIdxTy)
7258       Index = DAG.getVectorIdxConstant(
7259           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7260 
7261     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7262     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7263                              Index));
7264     return;
7265   }
7266   case Intrinsic::vector_extract: {
7267     SDValue Vec = getValue(I.getOperand(0));
7268     SDValue Index = getValue(I.getOperand(1));
7269     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7270 
7271     // The intrinsic's index type is i64, but the SDNode requires an index type
7272     // suitable for the target. Convert the index as required.
7273     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7274     if (Index.getValueType() != VectorIdxTy)
7275       Index = DAG.getVectorIdxConstant(
7276           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7277 
7278     setValue(&I,
7279              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7280     return;
7281   }
7282   case Intrinsic::experimental_vector_reverse:
7283     visitVectorReverse(I);
7284     return;
7285   case Intrinsic::experimental_vector_splice:
7286     visitVectorSplice(I);
7287     return;
7288   }
7289 }
7290 
7291 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7292     const ConstrainedFPIntrinsic &FPI) {
7293   SDLoc sdl = getCurSDLoc();
7294 
7295   // We do not need to serialize constrained FP intrinsics against
7296   // each other or against (nonvolatile) loads, so they can be
7297   // chained like loads.
7298   SDValue Chain = DAG.getRoot();
7299   SmallVector<SDValue, 4> Opers;
7300   Opers.push_back(Chain);
7301   if (FPI.isUnaryOp()) {
7302     Opers.push_back(getValue(FPI.getArgOperand(0)));
7303   } else if (FPI.isTernaryOp()) {
7304     Opers.push_back(getValue(FPI.getArgOperand(0)));
7305     Opers.push_back(getValue(FPI.getArgOperand(1)));
7306     Opers.push_back(getValue(FPI.getArgOperand(2)));
7307   } else {
7308     Opers.push_back(getValue(FPI.getArgOperand(0)));
7309     Opers.push_back(getValue(FPI.getArgOperand(1)));
7310   }
7311 
7312   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7313     assert(Result.getNode()->getNumValues() == 2);
7314 
7315     // Push node to the appropriate list so that future instructions can be
7316     // chained up correctly.
7317     SDValue OutChain = Result.getValue(1);
7318     switch (EB) {
7319     case fp::ExceptionBehavior::ebIgnore:
7320       // The only reason why ebIgnore nodes still need to be chained is that
7321       // they might depend on the current rounding mode, and therefore must
7322       // not be moved across instruction that may change that mode.
7323       [[fallthrough]];
7324     case fp::ExceptionBehavior::ebMayTrap:
7325       // These must not be moved across calls or instructions that may change
7326       // floating-point exception masks.
7327       PendingConstrainedFP.push_back(OutChain);
7328       break;
7329     case fp::ExceptionBehavior::ebStrict:
7330       // These must not be moved across calls or instructions that may change
7331       // floating-point exception masks or read floating-point exception flags.
7332       // In addition, they cannot be optimized out even if unused.
7333       PendingConstrainedFPStrict.push_back(OutChain);
7334       break;
7335     }
7336   };
7337 
7338   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7339   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7340   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7341   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7342 
7343   SDNodeFlags Flags;
7344   if (EB == fp::ExceptionBehavior::ebIgnore)
7345     Flags.setNoFPExcept(true);
7346 
7347   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7348     Flags.copyFMF(*FPOp);
7349 
7350   unsigned Opcode;
7351   switch (FPI.getIntrinsicID()) {
7352   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7353 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7354   case Intrinsic::INTRINSIC:                                                   \
7355     Opcode = ISD::STRICT_##DAGN;                                               \
7356     break;
7357 #include "llvm/IR/ConstrainedOps.def"
7358   case Intrinsic::experimental_constrained_fmuladd: {
7359     Opcode = ISD::STRICT_FMA;
7360     // Break fmuladd into fmul and fadd.
7361     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7362         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7363       Opers.pop_back();
7364       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7365       pushOutChain(Mul, EB);
7366       Opcode = ISD::STRICT_FADD;
7367       Opers.clear();
7368       Opers.push_back(Mul.getValue(1));
7369       Opers.push_back(Mul.getValue(0));
7370       Opers.push_back(getValue(FPI.getArgOperand(2)));
7371     }
7372     break;
7373   }
7374   }
7375 
7376   // A few strict DAG nodes carry additional operands that are not
7377   // set up by the default code above.
7378   switch (Opcode) {
7379   default: break;
7380   case ISD::STRICT_FP_ROUND:
7381     Opers.push_back(
7382         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7383     break;
7384   case ISD::STRICT_FSETCC:
7385   case ISD::STRICT_FSETCCS: {
7386     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7387     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7388     if (TM.Options.NoNaNsFPMath)
7389       Condition = getFCmpCodeWithoutNaN(Condition);
7390     Opers.push_back(DAG.getCondCode(Condition));
7391     break;
7392   }
7393   }
7394 
7395   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7396   pushOutChain(Result, EB);
7397 
7398   SDValue FPResult = Result.getValue(0);
7399   setValue(&FPI, FPResult);
7400 }
7401 
7402 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7403   Optional<unsigned> ResOPC;
7404   switch (VPIntrin.getIntrinsicID()) {
7405 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
7406   case Intrinsic::VPID:                                                        \
7407     ResOPC = ISD::VPSD;                                                        \
7408     break;
7409 #include "llvm/IR/VPIntrinsics.def"
7410   }
7411 
7412   if (!ResOPC)
7413     llvm_unreachable(
7414         "Inconsistency: no SDNode available for this VPIntrinsic!");
7415 
7416   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7417       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7418     if (VPIntrin.getFastMathFlags().allowReassoc())
7419       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7420                                                 : ISD::VP_REDUCE_FMUL;
7421   }
7422 
7423   return *ResOPC;
7424 }
7425 
7426 void SelectionDAGBuilder::visitVPLoad(const VPIntrinsic &VPIntrin, EVT VT,
7427                                       SmallVector<SDValue, 7> &OpValues) {
7428   SDLoc DL = getCurSDLoc();
7429   Value *PtrOperand = VPIntrin.getArgOperand(0);
7430   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7431   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7432   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7433   SDValue LD;
7434   bool AddToChain = true;
7435   // Do not serialize variable-length loads of constant memory with
7436   // anything.
7437   if (!Alignment)
7438     Alignment = DAG.getEVTAlign(VT);
7439   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7440   AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7441   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7442   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7443       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7444       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7445   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7446                      MMO, false /*IsExpanding */);
7447   if (AddToChain)
7448     PendingLoads.push_back(LD.getValue(1));
7449   setValue(&VPIntrin, LD);
7450 }
7451 
7452 void SelectionDAGBuilder::visitVPGather(const VPIntrinsic &VPIntrin, EVT VT,
7453                                         SmallVector<SDValue, 7> &OpValues) {
7454   SDLoc DL = getCurSDLoc();
7455   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7456   Value *PtrOperand = VPIntrin.getArgOperand(0);
7457   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7458   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7459   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7460   SDValue LD;
7461   if (!Alignment)
7462     Alignment = DAG.getEVTAlign(VT.getScalarType());
7463   unsigned AS =
7464     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7465   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7466      MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7467      MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7468   SDValue Base, Index, Scale;
7469   ISD::MemIndexType IndexType;
7470   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7471                                     this, VPIntrin.getParent(),
7472                                     VT.getScalarStoreSize());
7473   if (!UniformBase) {
7474     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7475     Index = getValue(PtrOperand);
7476     IndexType = ISD::SIGNED_SCALED;
7477     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7478   }
7479   EVT IdxVT = Index.getValueType();
7480   EVT EltTy = IdxVT.getVectorElementType();
7481   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7482     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7483     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7484   }
7485   LD = DAG.getGatherVP(
7486       DAG.getVTList(VT, MVT::Other), VT, DL,
7487       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7488       IndexType);
7489   PendingLoads.push_back(LD.getValue(1));
7490   setValue(&VPIntrin, LD);
7491 }
7492 
7493 void SelectionDAGBuilder::visitVPStore(const VPIntrinsic &VPIntrin,
7494                                        SmallVector<SDValue, 7> &OpValues) {
7495   SDLoc DL = getCurSDLoc();
7496   Value *PtrOperand = VPIntrin.getArgOperand(1);
7497   EVT VT = OpValues[0].getValueType();
7498   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7499   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7500   SDValue ST;
7501   if (!Alignment)
7502     Alignment = DAG.getEVTAlign(VT);
7503   SDValue Ptr = OpValues[1];
7504   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7505   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7506       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7507       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7508   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
7509                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
7510                       /* IsTruncating */ false, /*IsCompressing*/ false);
7511   DAG.setRoot(ST);
7512   setValue(&VPIntrin, ST);
7513 }
7514 
7515 void SelectionDAGBuilder::visitVPScatter(const VPIntrinsic &VPIntrin,
7516                                               SmallVector<SDValue, 7> &OpValues) {
7517   SDLoc DL = getCurSDLoc();
7518   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7519   Value *PtrOperand = VPIntrin.getArgOperand(1);
7520   EVT VT = OpValues[0].getValueType();
7521   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7522   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7523   SDValue ST;
7524   if (!Alignment)
7525     Alignment = DAG.getEVTAlign(VT.getScalarType());
7526   unsigned AS =
7527       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7528   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7529       MachinePointerInfo(AS), MachineMemOperand::MOStore,
7530       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7531   SDValue Base, Index, Scale;
7532   ISD::MemIndexType IndexType;
7533   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7534                                     this, VPIntrin.getParent(),
7535                                     VT.getScalarStoreSize());
7536   if (!UniformBase) {
7537     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7538     Index = getValue(PtrOperand);
7539     IndexType = ISD::SIGNED_SCALED;
7540     Scale =
7541       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7542   }
7543   EVT IdxVT = Index.getValueType();
7544   EVT EltTy = IdxVT.getVectorElementType();
7545   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7546     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7547     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7548   }
7549   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7550                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7551                          OpValues[2], OpValues[3]},
7552                         MMO, IndexType);
7553   DAG.setRoot(ST);
7554   setValue(&VPIntrin, ST);
7555 }
7556 
7557 void SelectionDAGBuilder::visitVPStridedLoad(
7558     const VPIntrinsic &VPIntrin, EVT VT, SmallVectorImpl<SDValue> &OpValues) {
7559   SDLoc DL = getCurSDLoc();
7560   Value *PtrOperand = VPIntrin.getArgOperand(0);
7561   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7562   if (!Alignment)
7563     Alignment = DAG.getEVTAlign(VT.getScalarType());
7564   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7565   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7566   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7567   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7568   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7569   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7570       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7571       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7572 
7573   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
7574                                     OpValues[2], OpValues[3], MMO,
7575                                     false /*IsExpanding*/);
7576 
7577   if (AddToChain)
7578     PendingLoads.push_back(LD.getValue(1));
7579   setValue(&VPIntrin, LD);
7580 }
7581 
7582 void SelectionDAGBuilder::visitVPStridedStore(
7583     const VPIntrinsic &VPIntrin, SmallVectorImpl<SDValue> &OpValues) {
7584   SDLoc DL = getCurSDLoc();
7585   Value *PtrOperand = VPIntrin.getArgOperand(1);
7586   EVT VT = OpValues[0].getValueType();
7587   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7588   if (!Alignment)
7589     Alignment = DAG.getEVTAlign(VT.getScalarType());
7590   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7591   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7592       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7593       MemoryLocation::UnknownSize, *Alignment, AAInfo);
7594 
7595   SDValue ST = DAG.getStridedStoreVP(
7596       getMemoryRoot(), DL, OpValues[0], OpValues[1],
7597       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
7598       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
7599       /*IsCompressing*/ false);
7600 
7601   DAG.setRoot(ST);
7602   setValue(&VPIntrin, ST);
7603 }
7604 
7605 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
7606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7607   SDLoc DL = getCurSDLoc();
7608 
7609   ISD::CondCode Condition;
7610   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
7611   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
7612   if (IsFP) {
7613     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
7614     // flags, but calls that don't return floating-point types can't be
7615     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
7616     Condition = getFCmpCondCode(CondCode);
7617     if (TM.Options.NoNaNsFPMath)
7618       Condition = getFCmpCodeWithoutNaN(Condition);
7619   } else {
7620     Condition = getICmpCondCode(CondCode);
7621   }
7622 
7623   SDValue Op1 = getValue(VPIntrin.getOperand(0));
7624   SDValue Op2 = getValue(VPIntrin.getOperand(1));
7625   // #2 is the condition code
7626   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
7627   SDValue EVL = getValue(VPIntrin.getOperand(4));
7628   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7629   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7630          "Unexpected target EVL type");
7631   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
7632 
7633   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7634                                                         VPIntrin.getType());
7635   setValue(&VPIntrin,
7636            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
7637 }
7638 
7639 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7640     const VPIntrinsic &VPIntrin) {
7641   SDLoc DL = getCurSDLoc();
7642   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7643 
7644   auto IID = VPIntrin.getIntrinsicID();
7645 
7646   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
7647     return visitVPCmp(*CmpI);
7648 
7649   SmallVector<EVT, 4> ValueVTs;
7650   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7651   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7652   SDVTList VTs = DAG.getVTList(ValueVTs);
7653 
7654   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
7655 
7656   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7657   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7658          "Unexpected target EVL type");
7659 
7660   // Request operands.
7661   SmallVector<SDValue, 7> OpValues;
7662   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7663     auto Op = getValue(VPIntrin.getArgOperand(I));
7664     if (I == EVLParamPos)
7665       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7666     OpValues.push_back(Op);
7667   }
7668 
7669   switch (Opcode) {
7670   default: {
7671     SDNodeFlags SDFlags;
7672     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7673       SDFlags.copyFMF(*FPMO);
7674     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
7675     setValue(&VPIntrin, Result);
7676     break;
7677   }
7678   case ISD::VP_LOAD:
7679     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
7680     break;
7681   case ISD::VP_GATHER:
7682     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
7683     break;
7684   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
7685     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
7686     break;
7687   case ISD::VP_STORE:
7688     visitVPStore(VPIntrin, OpValues);
7689     break;
7690   case ISD::VP_SCATTER:
7691     visitVPScatter(VPIntrin, OpValues);
7692     break;
7693   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
7694     visitVPStridedStore(VPIntrin, OpValues);
7695     break;
7696   case ISD::VP_FMULADD: {
7697     assert(OpValues.size() == 5 && "Unexpected number of operands");
7698     SDNodeFlags SDFlags;
7699     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
7700       SDFlags.copyFMF(*FPMO);
7701     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7702         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
7703       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
7704     } else {
7705       SDValue Mul = DAG.getNode(
7706           ISD::VP_FMUL, DL, VTs,
7707           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
7708       SDValue Add =
7709           DAG.getNode(ISD::VP_FADD, DL, VTs,
7710                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
7711       setValue(&VPIntrin, Add);
7712     }
7713     break;
7714   }
7715   }
7716 }
7717 
7718 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7719                                           const BasicBlock *EHPadBB,
7720                                           MCSymbol *&BeginLabel) {
7721   MachineFunction &MF = DAG.getMachineFunction();
7722   MachineModuleInfo &MMI = MF.getMMI();
7723 
7724   // Insert a label before the invoke call to mark the try range.  This can be
7725   // used to detect deletion of the invoke via the MachineModuleInfo.
7726   BeginLabel = MMI.getContext().createTempSymbol();
7727 
7728   // For SjLj, keep track of which landing pads go with which invokes
7729   // so as to maintain the ordering of pads in the LSDA.
7730   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7731   if (CallSiteIndex) {
7732     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7733     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7734 
7735     // Now that the call site is handled, stop tracking it.
7736     MMI.setCurrentCallSite(0);
7737   }
7738 
7739   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7740 }
7741 
7742 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7743                                         const BasicBlock *EHPadBB,
7744                                         MCSymbol *BeginLabel) {
7745   assert(BeginLabel && "BeginLabel should've been set");
7746 
7747   MachineFunction &MF = DAG.getMachineFunction();
7748   MachineModuleInfo &MMI = MF.getMMI();
7749 
7750   // Insert a label at the end of the invoke call to mark the try range.  This
7751   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7752   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7753   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7754 
7755   // Inform MachineModuleInfo of range.
7756   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7757   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7758   // actually use outlined funclets and their LSDA info style.
7759   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7760     assert(II && "II should've been set");
7761     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7762     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7763   } else if (!isScopedEHPersonality(Pers)) {
7764     assert(EHPadBB);
7765     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7766   }
7767 
7768   return Chain;
7769 }
7770 
7771 std::pair<SDValue, SDValue>
7772 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7773                                     const BasicBlock *EHPadBB) {
7774   MCSymbol *BeginLabel = nullptr;
7775 
7776   if (EHPadBB) {
7777     // Both PendingLoads and PendingExports must be flushed here;
7778     // this call might not return.
7779     (void)getRoot();
7780     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7781     CLI.setChain(getRoot());
7782   }
7783 
7784   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7785   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7786 
7787   assert((CLI.IsTailCall || Result.second.getNode()) &&
7788          "Non-null chain expected with non-tail call!");
7789   assert((Result.second.getNode() || !Result.first.getNode()) &&
7790          "Null value expected with tail call!");
7791 
7792   if (!Result.second.getNode()) {
7793     // As a special case, a null chain means that a tail call has been emitted
7794     // and the DAG root is already updated.
7795     HasTailCall = true;
7796 
7797     // Since there's no actual continuation from this block, nothing can be
7798     // relying on us setting vregs for them.
7799     PendingExports.clear();
7800   } else {
7801     DAG.setRoot(Result.second);
7802   }
7803 
7804   if (EHPadBB) {
7805     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7806                            BeginLabel));
7807   }
7808 
7809   return Result;
7810 }
7811 
7812 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7813                                       bool isTailCall,
7814                                       bool isMustTailCall,
7815                                       const BasicBlock *EHPadBB) {
7816   auto &DL = DAG.getDataLayout();
7817   FunctionType *FTy = CB.getFunctionType();
7818   Type *RetTy = CB.getType();
7819 
7820   TargetLowering::ArgListTy Args;
7821   Args.reserve(CB.arg_size());
7822 
7823   const Value *SwiftErrorVal = nullptr;
7824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7825 
7826   if (isTailCall) {
7827     // Avoid emitting tail calls in functions with the disable-tail-calls
7828     // attribute.
7829     auto *Caller = CB.getParent()->getParent();
7830     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7831         "true" && !isMustTailCall)
7832       isTailCall = false;
7833 
7834     // We can't tail call inside a function with a swifterror argument. Lowering
7835     // does not support this yet. It would have to move into the swifterror
7836     // register before the call.
7837     if (TLI.supportSwiftError() &&
7838         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7839       isTailCall = false;
7840   }
7841 
7842   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7843     TargetLowering::ArgListEntry Entry;
7844     const Value *V = *I;
7845 
7846     // Skip empty types
7847     if (V->getType()->isEmptyTy())
7848       continue;
7849 
7850     SDValue ArgNode = getValue(V);
7851     Entry.Node = ArgNode; Entry.Ty = V->getType();
7852 
7853     Entry.setAttributes(&CB, I - CB.arg_begin());
7854 
7855     // Use swifterror virtual register as input to the call.
7856     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7857       SwiftErrorVal = V;
7858       // We find the virtual register for the actual swifterror argument.
7859       // Instead of using the Value, we use the virtual register instead.
7860       Entry.Node =
7861           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7862                           EVT(TLI.getPointerTy(DL)));
7863     }
7864 
7865     Args.push_back(Entry);
7866 
7867     // If we have an explicit sret argument that is an Instruction, (i.e., it
7868     // might point to function-local memory), we can't meaningfully tail-call.
7869     if (Entry.IsSRet && isa<Instruction>(V))
7870       isTailCall = false;
7871   }
7872 
7873   // If call site has a cfguardtarget operand bundle, create and add an
7874   // additional ArgListEntry.
7875   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7876     TargetLowering::ArgListEntry Entry;
7877     Value *V = Bundle->Inputs[0];
7878     SDValue ArgNode = getValue(V);
7879     Entry.Node = ArgNode;
7880     Entry.Ty = V->getType();
7881     Entry.IsCFGuardTarget = true;
7882     Args.push_back(Entry);
7883   }
7884 
7885   // Check if target-independent constraints permit a tail call here.
7886   // Target-dependent constraints are checked within TLI->LowerCallTo.
7887   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7888     isTailCall = false;
7889 
7890   // Disable tail calls if there is an swifterror argument. Targets have not
7891   // been updated to support tail calls.
7892   if (TLI.supportSwiftError() && SwiftErrorVal)
7893     isTailCall = false;
7894 
7895   ConstantInt *CFIType = nullptr;
7896   if (CB.isIndirectCall()) {
7897     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
7898       if (!TLI.supportKCFIBundles())
7899         report_fatal_error(
7900             "Target doesn't support calls with kcfi operand bundles.");
7901       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
7902       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
7903     }
7904   }
7905 
7906   TargetLowering::CallLoweringInfo CLI(DAG);
7907   CLI.setDebugLoc(getCurSDLoc())
7908       .setChain(getRoot())
7909       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7910       .setTailCall(isTailCall)
7911       .setConvergent(CB.isConvergent())
7912       .setIsPreallocated(
7913           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
7914       .setCFIType(CFIType);
7915   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7916 
7917   if (Result.first.getNode()) {
7918     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7919     setValue(&CB, Result.first);
7920   }
7921 
7922   // The last element of CLI.InVals has the SDValue for swifterror return.
7923   // Here we copy it to a virtual register and update SwiftErrorMap for
7924   // book-keeping.
7925   if (SwiftErrorVal && TLI.supportSwiftError()) {
7926     // Get the last element of InVals.
7927     SDValue Src = CLI.InVals.back();
7928     Register VReg =
7929         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7930     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7931     DAG.setRoot(CopyNode);
7932   }
7933 }
7934 
7935 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7936                              SelectionDAGBuilder &Builder) {
7937   // Check to see if this load can be trivially constant folded, e.g. if the
7938   // input is from a string literal.
7939   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7940     // Cast pointer to the type we really want to load.
7941     Type *LoadTy =
7942         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7943     if (LoadVT.isVector())
7944       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7945 
7946     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7947                                          PointerType::getUnqual(LoadTy));
7948 
7949     if (const Constant *LoadCst =
7950             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7951                                          LoadTy, Builder.DAG.getDataLayout()))
7952       return Builder.getValue(LoadCst);
7953   }
7954 
7955   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7956   // still constant memory, the input chain can be the entry node.
7957   SDValue Root;
7958   bool ConstantMemory = false;
7959 
7960   // Do not serialize (non-volatile) loads of constant memory with anything.
7961   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7962     Root = Builder.DAG.getEntryNode();
7963     ConstantMemory = true;
7964   } else {
7965     // Do not serialize non-volatile loads against each other.
7966     Root = Builder.DAG.getRoot();
7967   }
7968 
7969   SDValue Ptr = Builder.getValue(PtrVal);
7970   SDValue LoadVal =
7971       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7972                           MachinePointerInfo(PtrVal), Align(1));
7973 
7974   if (!ConstantMemory)
7975     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7976   return LoadVal;
7977 }
7978 
7979 /// Record the value for an instruction that produces an integer result,
7980 /// converting the type where necessary.
7981 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7982                                                   SDValue Value,
7983                                                   bool IsSigned) {
7984   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7985                                                     I.getType(), true);
7986   if (IsSigned)
7987     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7988   else
7989     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7990   setValue(&I, Value);
7991 }
7992 
7993 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7994 /// true and lower it. Otherwise return false, and it will be lowered like a
7995 /// normal call.
7996 /// The caller already checked that \p I calls the appropriate LibFunc with a
7997 /// correct prototype.
7998 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7999   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8000   const Value *Size = I.getArgOperand(2);
8001   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8002   if (CSize && CSize->getZExtValue() == 0) {
8003     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8004                                                           I.getType(), true);
8005     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8006     return true;
8007   }
8008 
8009   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8010   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8011       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8012       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8013   if (Res.first.getNode()) {
8014     processIntegerCallValue(I, Res.first, true);
8015     PendingLoads.push_back(Res.second);
8016     return true;
8017   }
8018 
8019   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8020   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8021   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8022     return false;
8023 
8024   // If the target has a fast compare for the given size, it will return a
8025   // preferred load type for that size. Require that the load VT is legal and
8026   // that the target supports unaligned loads of that type. Otherwise, return
8027   // INVALID.
8028   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8029     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8030     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8031     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8032       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8033       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8034       // TODO: Check alignment of src and dest ptrs.
8035       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8036       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8037       if (!TLI.isTypeLegal(LVT) ||
8038           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8039           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8040         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8041     }
8042 
8043     return LVT;
8044   };
8045 
8046   // This turns into unaligned loads. We only do this if the target natively
8047   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8048   // we'll only produce a small number of byte loads.
8049   MVT LoadVT;
8050   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8051   switch (NumBitsToCompare) {
8052   default:
8053     return false;
8054   case 16:
8055     LoadVT = MVT::i16;
8056     break;
8057   case 32:
8058     LoadVT = MVT::i32;
8059     break;
8060   case 64:
8061   case 128:
8062   case 256:
8063     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8064     break;
8065   }
8066 
8067   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8068     return false;
8069 
8070   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8071   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8072 
8073   // Bitcast to a wide integer type if the loads are vectors.
8074   if (LoadVT.isVector()) {
8075     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8076     LoadL = DAG.getBitcast(CmpVT, LoadL);
8077     LoadR = DAG.getBitcast(CmpVT, LoadR);
8078   }
8079 
8080   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8081   processIntegerCallValue(I, Cmp, false);
8082   return true;
8083 }
8084 
8085 /// See if we can lower a memchr call into an optimized form. If so, return
8086 /// true and lower it. Otherwise return false, and it will be lowered like a
8087 /// normal call.
8088 /// The caller already checked that \p I calls the appropriate LibFunc with a
8089 /// correct prototype.
8090 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8091   const Value *Src = I.getArgOperand(0);
8092   const Value *Char = I.getArgOperand(1);
8093   const Value *Length = I.getArgOperand(2);
8094 
8095   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8096   std::pair<SDValue, SDValue> Res =
8097     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8098                                 getValue(Src), getValue(Char), getValue(Length),
8099                                 MachinePointerInfo(Src));
8100   if (Res.first.getNode()) {
8101     setValue(&I, Res.first);
8102     PendingLoads.push_back(Res.second);
8103     return true;
8104   }
8105 
8106   return false;
8107 }
8108 
8109 /// See if we can lower a mempcpy call into an optimized form. If so, return
8110 /// true and lower it. Otherwise return false, and it will be lowered like a
8111 /// normal call.
8112 /// The caller already checked that \p I calls the appropriate LibFunc with a
8113 /// correct prototype.
8114 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8115   SDValue Dst = getValue(I.getArgOperand(0));
8116   SDValue Src = getValue(I.getArgOperand(1));
8117   SDValue Size = getValue(I.getArgOperand(2));
8118 
8119   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8120   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8121   // DAG::getMemcpy needs Alignment to be defined.
8122   Align Alignment = std::min(DstAlign, SrcAlign);
8123 
8124   bool isVol = false;
8125   SDLoc sdl = getCurSDLoc();
8126 
8127   // In the mempcpy context we need to pass in a false value for isTailCall
8128   // because the return pointer needs to be adjusted by the size of
8129   // the copied memory.
8130   SDValue Root = isVol ? getRoot() : getMemoryRoot();
8131   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
8132                              /*isTailCall=*/false,
8133                              MachinePointerInfo(I.getArgOperand(0)),
8134                              MachinePointerInfo(I.getArgOperand(1)),
8135                              I.getAAMetadata());
8136   assert(MC.getNode() != nullptr &&
8137          "** memcpy should not be lowered as TailCall in mempcpy context **");
8138   DAG.setRoot(MC);
8139 
8140   // Check if Size needs to be truncated or extended.
8141   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8142 
8143   // Adjust return pointer to point just past the last dst byte.
8144   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8145                                     Dst, Size);
8146   setValue(&I, DstPlusSize);
8147   return true;
8148 }
8149 
8150 /// See if we can lower a strcpy call into an optimized form.  If so, return
8151 /// true and lower it, otherwise return false and it will be lowered like a
8152 /// normal call.
8153 /// The caller already checked that \p I calls the appropriate LibFunc with a
8154 /// correct prototype.
8155 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8156   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8157 
8158   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8159   std::pair<SDValue, SDValue> Res =
8160     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8161                                 getValue(Arg0), getValue(Arg1),
8162                                 MachinePointerInfo(Arg0),
8163                                 MachinePointerInfo(Arg1), isStpcpy);
8164   if (Res.first.getNode()) {
8165     setValue(&I, Res.first);
8166     DAG.setRoot(Res.second);
8167     return true;
8168   }
8169 
8170   return false;
8171 }
8172 
8173 /// See if we can lower a strcmp call into an optimized form.  If so, return
8174 /// true and lower it, otherwise return false and it will be lowered like a
8175 /// normal call.
8176 /// The caller already checked that \p I calls the appropriate LibFunc with a
8177 /// correct prototype.
8178 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8179   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8180 
8181   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8182   std::pair<SDValue, SDValue> Res =
8183     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8184                                 getValue(Arg0), getValue(Arg1),
8185                                 MachinePointerInfo(Arg0),
8186                                 MachinePointerInfo(Arg1));
8187   if (Res.first.getNode()) {
8188     processIntegerCallValue(I, Res.first, true);
8189     PendingLoads.push_back(Res.second);
8190     return true;
8191   }
8192 
8193   return false;
8194 }
8195 
8196 /// See if we can lower a strlen call into an optimized form.  If so, return
8197 /// true and lower it, otherwise return false and it will be lowered like a
8198 /// normal call.
8199 /// The caller already checked that \p I calls the appropriate LibFunc with a
8200 /// correct prototype.
8201 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8202   const Value *Arg0 = I.getArgOperand(0);
8203 
8204   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8205   std::pair<SDValue, SDValue> Res =
8206     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8207                                 getValue(Arg0), MachinePointerInfo(Arg0));
8208   if (Res.first.getNode()) {
8209     processIntegerCallValue(I, Res.first, false);
8210     PendingLoads.push_back(Res.second);
8211     return true;
8212   }
8213 
8214   return false;
8215 }
8216 
8217 /// See if we can lower a strnlen call into an optimized form.  If so, return
8218 /// true and lower it, otherwise return false and it will be lowered like a
8219 /// normal call.
8220 /// The caller already checked that \p I calls the appropriate LibFunc with a
8221 /// correct prototype.
8222 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8223   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8224 
8225   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8226   std::pair<SDValue, SDValue> Res =
8227     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8228                                  getValue(Arg0), getValue(Arg1),
8229                                  MachinePointerInfo(Arg0));
8230   if (Res.first.getNode()) {
8231     processIntegerCallValue(I, Res.first, false);
8232     PendingLoads.push_back(Res.second);
8233     return true;
8234   }
8235 
8236   return false;
8237 }
8238 
8239 /// See if we can lower a unary floating-point operation into an SDNode with
8240 /// the specified Opcode.  If so, return true and lower it, otherwise return
8241 /// false and it will be lowered like a normal call.
8242 /// The caller already checked that \p I calls the appropriate LibFunc with a
8243 /// correct prototype.
8244 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8245                                               unsigned Opcode) {
8246   // We already checked this call's prototype; verify it doesn't modify errno.
8247   if (!I.onlyReadsMemory())
8248     return false;
8249 
8250   SDNodeFlags Flags;
8251   Flags.copyFMF(cast<FPMathOperator>(I));
8252 
8253   SDValue Tmp = getValue(I.getArgOperand(0));
8254   setValue(&I,
8255            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8256   return true;
8257 }
8258 
8259 /// See if we can lower a binary floating-point operation into an SDNode with
8260 /// the specified Opcode. If so, return true and lower it. Otherwise return
8261 /// false, and it will be lowered like a normal call.
8262 /// The caller already checked that \p I calls the appropriate LibFunc with a
8263 /// correct prototype.
8264 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8265                                                unsigned Opcode) {
8266   // We already checked this call's prototype; verify it doesn't modify errno.
8267   if (!I.onlyReadsMemory())
8268     return false;
8269 
8270   SDNodeFlags Flags;
8271   Flags.copyFMF(cast<FPMathOperator>(I));
8272 
8273   SDValue Tmp0 = getValue(I.getArgOperand(0));
8274   SDValue Tmp1 = getValue(I.getArgOperand(1));
8275   EVT VT = Tmp0.getValueType();
8276   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8277   return true;
8278 }
8279 
8280 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8281   // Handle inline assembly differently.
8282   if (I.isInlineAsm()) {
8283     visitInlineAsm(I);
8284     return;
8285   }
8286 
8287   if (Function *F = I.getCalledFunction()) {
8288     diagnoseDontCall(I);
8289 
8290     if (F->isDeclaration()) {
8291       // Is this an LLVM intrinsic or a target-specific intrinsic?
8292       unsigned IID = F->getIntrinsicID();
8293       if (!IID)
8294         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8295           IID = II->getIntrinsicID(F);
8296 
8297       if (IID) {
8298         visitIntrinsicCall(I, IID);
8299         return;
8300       }
8301     }
8302 
8303     // Check for well-known libc/libm calls.  If the function is internal, it
8304     // can't be a library call.  Don't do the check if marked as nobuiltin for
8305     // some reason or the call site requires strict floating point semantics.
8306     LibFunc Func;
8307     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8308         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8309         LibInfo->hasOptimizedCodeGen(Func)) {
8310       switch (Func) {
8311       default: break;
8312       case LibFunc_bcmp:
8313         if (visitMemCmpBCmpCall(I))
8314           return;
8315         break;
8316       case LibFunc_copysign:
8317       case LibFunc_copysignf:
8318       case LibFunc_copysignl:
8319         // We already checked this call's prototype; verify it doesn't modify
8320         // errno.
8321         if (I.onlyReadsMemory()) {
8322           SDValue LHS = getValue(I.getArgOperand(0));
8323           SDValue RHS = getValue(I.getArgOperand(1));
8324           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8325                                    LHS.getValueType(), LHS, RHS));
8326           return;
8327         }
8328         break;
8329       case LibFunc_fabs:
8330       case LibFunc_fabsf:
8331       case LibFunc_fabsl:
8332         if (visitUnaryFloatCall(I, ISD::FABS))
8333           return;
8334         break;
8335       case LibFunc_fmin:
8336       case LibFunc_fminf:
8337       case LibFunc_fminl:
8338         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8339           return;
8340         break;
8341       case LibFunc_fmax:
8342       case LibFunc_fmaxf:
8343       case LibFunc_fmaxl:
8344         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8345           return;
8346         break;
8347       case LibFunc_sin:
8348       case LibFunc_sinf:
8349       case LibFunc_sinl:
8350         if (visitUnaryFloatCall(I, ISD::FSIN))
8351           return;
8352         break;
8353       case LibFunc_cos:
8354       case LibFunc_cosf:
8355       case LibFunc_cosl:
8356         if (visitUnaryFloatCall(I, ISD::FCOS))
8357           return;
8358         break;
8359       case LibFunc_sqrt:
8360       case LibFunc_sqrtf:
8361       case LibFunc_sqrtl:
8362       case LibFunc_sqrt_finite:
8363       case LibFunc_sqrtf_finite:
8364       case LibFunc_sqrtl_finite:
8365         if (visitUnaryFloatCall(I, ISD::FSQRT))
8366           return;
8367         break;
8368       case LibFunc_floor:
8369       case LibFunc_floorf:
8370       case LibFunc_floorl:
8371         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8372           return;
8373         break;
8374       case LibFunc_nearbyint:
8375       case LibFunc_nearbyintf:
8376       case LibFunc_nearbyintl:
8377         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8378           return;
8379         break;
8380       case LibFunc_ceil:
8381       case LibFunc_ceilf:
8382       case LibFunc_ceill:
8383         if (visitUnaryFloatCall(I, ISD::FCEIL))
8384           return;
8385         break;
8386       case LibFunc_rint:
8387       case LibFunc_rintf:
8388       case LibFunc_rintl:
8389         if (visitUnaryFloatCall(I, ISD::FRINT))
8390           return;
8391         break;
8392       case LibFunc_round:
8393       case LibFunc_roundf:
8394       case LibFunc_roundl:
8395         if (visitUnaryFloatCall(I, ISD::FROUND))
8396           return;
8397         break;
8398       case LibFunc_trunc:
8399       case LibFunc_truncf:
8400       case LibFunc_truncl:
8401         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8402           return;
8403         break;
8404       case LibFunc_log2:
8405       case LibFunc_log2f:
8406       case LibFunc_log2l:
8407         if (visitUnaryFloatCall(I, ISD::FLOG2))
8408           return;
8409         break;
8410       case LibFunc_exp2:
8411       case LibFunc_exp2f:
8412       case LibFunc_exp2l:
8413         if (visitUnaryFloatCall(I, ISD::FEXP2))
8414           return;
8415         break;
8416       case LibFunc_memcmp:
8417         if (visitMemCmpBCmpCall(I))
8418           return;
8419         break;
8420       case LibFunc_mempcpy:
8421         if (visitMemPCpyCall(I))
8422           return;
8423         break;
8424       case LibFunc_memchr:
8425         if (visitMemChrCall(I))
8426           return;
8427         break;
8428       case LibFunc_strcpy:
8429         if (visitStrCpyCall(I, false))
8430           return;
8431         break;
8432       case LibFunc_stpcpy:
8433         if (visitStrCpyCall(I, true))
8434           return;
8435         break;
8436       case LibFunc_strcmp:
8437         if (visitStrCmpCall(I))
8438           return;
8439         break;
8440       case LibFunc_strlen:
8441         if (visitStrLenCall(I))
8442           return;
8443         break;
8444       case LibFunc_strnlen:
8445         if (visitStrNLenCall(I))
8446           return;
8447         break;
8448       }
8449     }
8450   }
8451 
8452   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8453   // have to do anything here to lower funclet bundles.
8454   // CFGuardTarget bundles are lowered in LowerCallTo.
8455   assert(!I.hasOperandBundlesOtherThan(
8456              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8457               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8458               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi}) &&
8459          "Cannot lower calls with arbitrary operand bundles!");
8460 
8461   SDValue Callee = getValue(I.getCalledOperand());
8462 
8463   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8464     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8465   else
8466     // Check if we can potentially perform a tail call. More detailed checking
8467     // is be done within LowerCallTo, after more information about the call is
8468     // known.
8469     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8470 }
8471 
8472 namespace {
8473 
8474 /// AsmOperandInfo - This contains information for each constraint that we are
8475 /// lowering.
8476 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8477 public:
8478   /// CallOperand - If this is the result output operand or a clobber
8479   /// this is null, otherwise it is the incoming operand to the CallInst.
8480   /// This gets modified as the asm is processed.
8481   SDValue CallOperand;
8482 
8483   /// AssignedRegs - If this is a register or register class operand, this
8484   /// contains the set of register corresponding to the operand.
8485   RegsForValue AssignedRegs;
8486 
8487   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8488     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8489   }
8490 
8491   /// Whether or not this operand accesses memory
8492   bool hasMemory(const TargetLowering &TLI) const {
8493     // Indirect operand accesses access memory.
8494     if (isIndirect)
8495       return true;
8496 
8497     for (const auto &Code : Codes)
8498       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8499         return true;
8500 
8501     return false;
8502   }
8503 };
8504 
8505 
8506 } // end anonymous namespace
8507 
8508 /// Make sure that the output operand \p OpInfo and its corresponding input
8509 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8510 /// out).
8511 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8512                                SDISelAsmOperandInfo &MatchingOpInfo,
8513                                SelectionDAG &DAG) {
8514   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8515     return;
8516 
8517   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8518   const auto &TLI = DAG.getTargetLoweringInfo();
8519 
8520   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8521       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8522                                        OpInfo.ConstraintVT);
8523   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8524       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8525                                        MatchingOpInfo.ConstraintVT);
8526   if ((OpInfo.ConstraintVT.isInteger() !=
8527        MatchingOpInfo.ConstraintVT.isInteger()) ||
8528       (MatchRC.second != InputRC.second)) {
8529     // FIXME: error out in a more elegant fashion
8530     report_fatal_error("Unsupported asm: input constraint"
8531                        " with a matching output constraint of"
8532                        " incompatible type!");
8533   }
8534   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8535 }
8536 
8537 /// Get a direct memory input to behave well as an indirect operand.
8538 /// This may introduce stores, hence the need for a \p Chain.
8539 /// \return The (possibly updated) chain.
8540 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8541                                         SDISelAsmOperandInfo &OpInfo,
8542                                         SelectionDAG &DAG) {
8543   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8544 
8545   // If we don't have an indirect input, put it in the constpool if we can,
8546   // otherwise spill it to a stack slot.
8547   // TODO: This isn't quite right. We need to handle these according to
8548   // the addressing mode that the constraint wants. Also, this may take
8549   // an additional register for the computation and we don't want that
8550   // either.
8551 
8552   // If the operand is a float, integer, or vector constant, spill to a
8553   // constant pool entry to get its address.
8554   const Value *OpVal = OpInfo.CallOperandVal;
8555   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8556       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8557     OpInfo.CallOperand = DAG.getConstantPool(
8558         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8559     return Chain;
8560   }
8561 
8562   // Otherwise, create a stack slot and emit a store to it before the asm.
8563   Type *Ty = OpVal->getType();
8564   auto &DL = DAG.getDataLayout();
8565   uint64_t TySize = DL.getTypeAllocSize(Ty);
8566   MachineFunction &MF = DAG.getMachineFunction();
8567   int SSFI = MF.getFrameInfo().CreateStackObject(
8568       TySize, DL.getPrefTypeAlign(Ty), false);
8569   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8570   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8571                             MachinePointerInfo::getFixedStack(MF, SSFI),
8572                             TLI.getMemValueType(DL, Ty));
8573   OpInfo.CallOperand = StackSlot;
8574 
8575   return Chain;
8576 }
8577 
8578 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8579 /// specified operand.  We prefer to assign virtual registers, to allow the
8580 /// register allocator to handle the assignment process.  However, if the asm
8581 /// uses features that we can't model on machineinstrs, we have SDISel do the
8582 /// allocation.  This produces generally horrible, but correct, code.
8583 ///
8584 ///   OpInfo describes the operand
8585 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8586 static llvm::Optional<unsigned>
8587 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8588                      SDISelAsmOperandInfo &OpInfo,
8589                      SDISelAsmOperandInfo &RefOpInfo) {
8590   LLVMContext &Context = *DAG.getContext();
8591   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8592 
8593   MachineFunction &MF = DAG.getMachineFunction();
8594   SmallVector<unsigned, 4> Regs;
8595   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8596 
8597   // No work to do for memory/address operands.
8598   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8599       OpInfo.ConstraintType == TargetLowering::C_Address)
8600     return None;
8601 
8602   // If this is a constraint for a single physreg, or a constraint for a
8603   // register class, find it.
8604   unsigned AssignedReg;
8605   const TargetRegisterClass *RC;
8606   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8607       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8608   // RC is unset only on failure. Return immediately.
8609   if (!RC)
8610     return None;
8611 
8612   // Get the actual register value type.  This is important, because the user
8613   // may have asked for (e.g.) the AX register in i32 type.  We need to
8614   // remember that AX is actually i16 to get the right extension.
8615   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8616 
8617   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8618     // If this is an FP operand in an integer register (or visa versa), or more
8619     // generally if the operand value disagrees with the register class we plan
8620     // to stick it in, fix the operand type.
8621     //
8622     // If this is an input value, the bitcast to the new type is done now.
8623     // Bitcast for output value is done at the end of visitInlineAsm().
8624     if ((OpInfo.Type == InlineAsm::isOutput ||
8625          OpInfo.Type == InlineAsm::isInput) &&
8626         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8627       // Try to convert to the first EVT that the reg class contains.  If the
8628       // types are identical size, use a bitcast to convert (e.g. two differing
8629       // vector types).  Note: output bitcast is done at the end of
8630       // visitInlineAsm().
8631       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8632         // Exclude indirect inputs while they are unsupported because the code
8633         // to perform the load is missing and thus OpInfo.CallOperand still
8634         // refers to the input address rather than the pointed-to value.
8635         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8636           OpInfo.CallOperand =
8637               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8638         OpInfo.ConstraintVT = RegVT;
8639         // If the operand is an FP value and we want it in integer registers,
8640         // use the corresponding integer type. This turns an f64 value into
8641         // i64, which can be passed with two i32 values on a 32-bit machine.
8642       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8643         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8644         if (OpInfo.Type == InlineAsm::isInput)
8645           OpInfo.CallOperand =
8646               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8647         OpInfo.ConstraintVT = VT;
8648       }
8649     }
8650   }
8651 
8652   // No need to allocate a matching input constraint since the constraint it's
8653   // matching to has already been allocated.
8654   if (OpInfo.isMatchingInputConstraint())
8655     return None;
8656 
8657   EVT ValueVT = OpInfo.ConstraintVT;
8658   if (OpInfo.ConstraintVT == MVT::Other)
8659     ValueVT = RegVT;
8660 
8661   // Initialize NumRegs.
8662   unsigned NumRegs = 1;
8663   if (OpInfo.ConstraintVT != MVT::Other)
8664     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8665 
8666   // If this is a constraint for a specific physical register, like {r17},
8667   // assign it now.
8668 
8669   // If this associated to a specific register, initialize iterator to correct
8670   // place. If virtual, make sure we have enough registers
8671 
8672   // Initialize iterator if necessary
8673   TargetRegisterClass::iterator I = RC->begin();
8674   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8675 
8676   // Do not check for single registers.
8677   if (AssignedReg) {
8678     I = std::find(I, RC->end(), AssignedReg);
8679     if (I == RC->end()) {
8680       // RC does not contain the selected register, which indicates a
8681       // mismatch between the register and the required type/bitwidth.
8682       return {AssignedReg};
8683     }
8684   }
8685 
8686   for (; NumRegs; --NumRegs, ++I) {
8687     assert(I != RC->end() && "Ran out of registers to allocate!");
8688     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8689     Regs.push_back(R);
8690   }
8691 
8692   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8693   return None;
8694 }
8695 
8696 static unsigned
8697 findMatchingInlineAsmOperand(unsigned OperandNo,
8698                              const std::vector<SDValue> &AsmNodeOperands) {
8699   // Scan until we find the definition we already emitted of this operand.
8700   unsigned CurOp = InlineAsm::Op_FirstOperand;
8701   for (; OperandNo; --OperandNo) {
8702     // Advance to the next operand.
8703     unsigned OpFlag =
8704         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8705     assert((InlineAsm::isRegDefKind(OpFlag) ||
8706             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8707             InlineAsm::isMemKind(OpFlag)) &&
8708            "Skipped past definitions?");
8709     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8710   }
8711   return CurOp;
8712 }
8713 
8714 namespace {
8715 
8716 class ExtraFlags {
8717   unsigned Flags = 0;
8718 
8719 public:
8720   explicit ExtraFlags(const CallBase &Call) {
8721     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8722     if (IA->hasSideEffects())
8723       Flags |= InlineAsm::Extra_HasSideEffects;
8724     if (IA->isAlignStack())
8725       Flags |= InlineAsm::Extra_IsAlignStack;
8726     if (Call.isConvergent())
8727       Flags |= InlineAsm::Extra_IsConvergent;
8728     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8729   }
8730 
8731   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8732     // Ideally, we would only check against memory constraints.  However, the
8733     // meaning of an Other constraint can be target-specific and we can't easily
8734     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8735     // for Other constraints as well.
8736     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8737         OpInfo.ConstraintType == TargetLowering::C_Other) {
8738       if (OpInfo.Type == InlineAsm::isInput)
8739         Flags |= InlineAsm::Extra_MayLoad;
8740       else if (OpInfo.Type == InlineAsm::isOutput)
8741         Flags |= InlineAsm::Extra_MayStore;
8742       else if (OpInfo.Type == InlineAsm::isClobber)
8743         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8744     }
8745   }
8746 
8747   unsigned get() const { return Flags; }
8748 };
8749 
8750 } // end anonymous namespace
8751 
8752 static bool isFunction(SDValue Op) {
8753   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
8754     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8755       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
8756 
8757       // In normal "call dllimport func" instruction (non-inlineasm) it force
8758       // indirect access by specifing call opcode. And usually specially print
8759       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
8760       // not do in this way now. (In fact, this is similar with "Data Access"
8761       // action). So here we ignore dllimport function.
8762       if (Fn && !Fn->hasDLLImportStorageClass())
8763         return true;
8764     }
8765   }
8766   return false;
8767 }
8768 
8769 /// visitInlineAsm - Handle a call to an InlineAsm object.
8770 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8771                                          const BasicBlock *EHPadBB) {
8772   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8773 
8774   /// ConstraintOperands - Information about all of the constraints.
8775   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8776 
8777   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8778   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8779       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8780 
8781   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8782   // AsmDialect, MayLoad, MayStore).
8783   bool HasSideEffect = IA->hasSideEffects();
8784   ExtraFlags ExtraInfo(Call);
8785 
8786   for (auto &T : TargetConstraints) {
8787     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8788     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8789 
8790     if (OpInfo.CallOperandVal)
8791       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8792 
8793     if (!HasSideEffect)
8794       HasSideEffect = OpInfo.hasMemory(TLI);
8795 
8796     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8797     // FIXME: Could we compute this on OpInfo rather than T?
8798 
8799     // Compute the constraint code and ConstraintType to use.
8800     TLI.ComputeConstraintToUse(T, SDValue());
8801 
8802     if (T.ConstraintType == TargetLowering::C_Immediate &&
8803         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8804       // We've delayed emitting a diagnostic like the "n" constraint because
8805       // inlining could cause an integer showing up.
8806       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8807                                           "' expects an integer constant "
8808                                           "expression");
8809 
8810     ExtraInfo.update(T);
8811   }
8812 
8813   // We won't need to flush pending loads if this asm doesn't touch
8814   // memory and is nonvolatile.
8815   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8816 
8817   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8818   if (EmitEHLabels) {
8819     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8820   }
8821   bool IsCallBr = isa<CallBrInst>(Call);
8822 
8823   if (IsCallBr || EmitEHLabels) {
8824     // If this is a callbr or invoke we need to flush pending exports since
8825     // inlineasm_br and invoke are terminators.
8826     // We need to do this before nodes are glued to the inlineasm_br node.
8827     Chain = getControlRoot();
8828   }
8829 
8830   MCSymbol *BeginLabel = nullptr;
8831   if (EmitEHLabels) {
8832     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8833   }
8834 
8835   int OpNo = -1;
8836   SmallVector<StringRef> AsmStrs;
8837   IA->collectAsmStrs(AsmStrs);
8838 
8839   // Second pass over the constraints: compute which constraint option to use.
8840   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8841     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
8842       OpNo++;
8843 
8844     // If this is an output operand with a matching input operand, look up the
8845     // matching input. If their types mismatch, e.g. one is an integer, the
8846     // other is floating point, or their sizes are different, flag it as an
8847     // error.
8848     if (OpInfo.hasMatchingInput()) {
8849       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8850       patchMatchingInput(OpInfo, Input, DAG);
8851     }
8852 
8853     // Compute the constraint code and ConstraintType to use.
8854     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8855 
8856     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
8857          OpInfo.Type == InlineAsm::isClobber) ||
8858         OpInfo.ConstraintType == TargetLowering::C_Address)
8859       continue;
8860 
8861     // In Linux PIC model, there are 4 cases about value/label addressing:
8862     //
8863     // 1: Function call or Label jmp inside the module.
8864     // 2: Data access (such as global variable, static variable) inside module.
8865     // 3: Function call or Label jmp outside the module.
8866     // 4: Data access (such as global variable) outside the module.
8867     //
8868     // Due to current llvm inline asm architecture designed to not "recognize"
8869     // the asm code, there are quite troubles for us to treat mem addressing
8870     // differently for same value/adress used in different instuctions.
8871     // For example, in pic model, call a func may in plt way or direclty
8872     // pc-related, but lea/mov a function adress may use got.
8873     //
8874     // Here we try to "recognize" function call for the case 1 and case 3 in
8875     // inline asm. And try to adjust the constraint for them.
8876     //
8877     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
8878     // label, so here we don't handle jmp function label now, but we need to
8879     // enhance it (especilly in PIC model) if we meet meaningful requirements.
8880     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
8881         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
8882         TM.getCodeModel() != CodeModel::Large) {
8883       OpInfo.isIndirect = false;
8884       OpInfo.ConstraintType = TargetLowering::C_Address;
8885     }
8886 
8887     // If this is a memory input, and if the operand is not indirect, do what we
8888     // need to provide an address for the memory input.
8889     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8890         !OpInfo.isIndirect) {
8891       assert((OpInfo.isMultipleAlternative ||
8892               (OpInfo.Type == InlineAsm::isInput)) &&
8893              "Can only indirectify direct input operands!");
8894 
8895       // Memory operands really want the address of the value.
8896       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8897 
8898       // There is no longer a Value* corresponding to this operand.
8899       OpInfo.CallOperandVal = nullptr;
8900 
8901       // It is now an indirect operand.
8902       OpInfo.isIndirect = true;
8903     }
8904 
8905   }
8906 
8907   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8908   std::vector<SDValue> AsmNodeOperands;
8909   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8910   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8911       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8912 
8913   // If we have a !srcloc metadata node associated with it, we want to attach
8914   // this to the ultimately generated inline asm machineinstr.  To do this, we
8915   // pass in the third operand as this (potentially null) inline asm MDNode.
8916   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8917   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8918 
8919   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8920   // bits as operand 3.
8921   AsmNodeOperands.push_back(DAG.getTargetConstant(
8922       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8923 
8924   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8925   // this, assign virtual and physical registers for inputs and otput.
8926   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8927     // Assign Registers.
8928     SDISelAsmOperandInfo &RefOpInfo =
8929         OpInfo.isMatchingInputConstraint()
8930             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8931             : OpInfo;
8932     const auto RegError =
8933         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8934     if (RegError) {
8935       const MachineFunction &MF = DAG.getMachineFunction();
8936       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8937       const char *RegName = TRI.getName(RegError.value());
8938       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8939                                    "' allocated for constraint '" +
8940                                    Twine(OpInfo.ConstraintCode) +
8941                                    "' does not match required type");
8942       return;
8943     }
8944 
8945     auto DetectWriteToReservedRegister = [&]() {
8946       const MachineFunction &MF = DAG.getMachineFunction();
8947       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8948       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8949         if (Register::isPhysicalRegister(Reg) &&
8950             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8951           const char *RegName = TRI.getName(Reg);
8952           emitInlineAsmError(Call, "write to reserved register '" +
8953                                        Twine(RegName) + "'");
8954           return true;
8955         }
8956       }
8957       return false;
8958     };
8959     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
8960             (OpInfo.Type == InlineAsm::isInput &&
8961              !OpInfo.isMatchingInputConstraint())) &&
8962            "Only address as input operand is allowed.");
8963 
8964     switch (OpInfo.Type) {
8965     case InlineAsm::isOutput:
8966       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8967         unsigned ConstraintID =
8968             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8969         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8970                "Failed to convert memory constraint code to constraint id.");
8971 
8972         // Add information to the INLINEASM node to know about this output.
8973         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8974         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8975         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8976                                                         MVT::i32));
8977         AsmNodeOperands.push_back(OpInfo.CallOperand);
8978       } else {
8979         // Otherwise, this outputs to a register (directly for C_Register /
8980         // C_RegisterClass, and a target-defined fashion for
8981         // C_Immediate/C_Other). Find a register that we can use.
8982         if (OpInfo.AssignedRegs.Regs.empty()) {
8983           emitInlineAsmError(
8984               Call, "couldn't allocate output register for constraint '" +
8985                         Twine(OpInfo.ConstraintCode) + "'");
8986           return;
8987         }
8988 
8989         if (DetectWriteToReservedRegister())
8990           return;
8991 
8992         // Add information to the INLINEASM node to know that this register is
8993         // set.
8994         OpInfo.AssignedRegs.AddInlineAsmOperands(
8995             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8996                                   : InlineAsm::Kind_RegDef,
8997             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8998       }
8999       break;
9000 
9001     case InlineAsm::isInput:
9002     case InlineAsm::isLabel: {
9003       SDValue InOperandVal = OpInfo.CallOperand;
9004 
9005       if (OpInfo.isMatchingInputConstraint()) {
9006         // If this is required to match an output register we have already set,
9007         // just use its register.
9008         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9009                                                   AsmNodeOperands);
9010         unsigned OpFlag =
9011           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
9012         if (InlineAsm::isRegDefKind(OpFlag) ||
9013             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
9014           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
9015           if (OpInfo.isIndirect) {
9016             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9017             emitInlineAsmError(Call, "inline asm not supported yet: "
9018                                      "don't know how to handle tied "
9019                                      "indirect register inputs");
9020             return;
9021           }
9022 
9023           SmallVector<unsigned, 4> Regs;
9024           MachineFunction &MF = DAG.getMachineFunction();
9025           MachineRegisterInfo &MRI = MF.getRegInfo();
9026           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9027           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9028           Register TiedReg = R->getReg();
9029           MVT RegVT = R->getSimpleValueType(0);
9030           const TargetRegisterClass *RC =
9031               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9032               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9033                                       : TRI.getMinimalPhysRegClass(TiedReg);
9034           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
9035           for (unsigned i = 0; i != NumRegs; ++i)
9036             Regs.push_back(MRI.createVirtualRegister(RC));
9037 
9038           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9039 
9040           SDLoc dl = getCurSDLoc();
9041           // Use the produced MatchedRegs object to
9042           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
9043           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
9044                                            true, OpInfo.getMatchedOperand(), dl,
9045                                            DAG, AsmNodeOperands);
9046           break;
9047         }
9048 
9049         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
9050         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
9051                "Unexpected number of operands");
9052         // Add information to the INLINEASM node to know about this input.
9053         // See InlineAsm.h isUseOperandTiedToDef.
9054         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
9055         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
9056                                                     OpInfo.getMatchedOperand());
9057         AsmNodeOperands.push_back(DAG.getTargetConstant(
9058             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9059         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9060         break;
9061       }
9062 
9063       // Treat indirect 'X' constraint as memory.
9064       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9065           OpInfo.isIndirect)
9066         OpInfo.ConstraintType = TargetLowering::C_Memory;
9067 
9068       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9069           OpInfo.ConstraintType == TargetLowering::C_Other) {
9070         std::vector<SDValue> Ops;
9071         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9072                                           Ops, DAG);
9073         if (Ops.empty()) {
9074           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9075             if (isa<ConstantSDNode>(InOperandVal)) {
9076               emitInlineAsmError(Call, "value out of range for constraint '" +
9077                                            Twine(OpInfo.ConstraintCode) + "'");
9078               return;
9079             }
9080 
9081           emitInlineAsmError(Call,
9082                              "invalid operand for inline asm constraint '" +
9083                                  Twine(OpInfo.ConstraintCode) + "'");
9084           return;
9085         }
9086 
9087         // Add information to the INLINEASM node to know about this input.
9088         unsigned ResOpType =
9089           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
9090         AsmNodeOperands.push_back(DAG.getTargetConstant(
9091             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9092         llvm::append_range(AsmNodeOperands, Ops);
9093         break;
9094       }
9095 
9096       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9097         assert((OpInfo.isIndirect ||
9098                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9099                "Operand must be indirect to be a mem!");
9100         assert(InOperandVal.getValueType() ==
9101                    TLI.getPointerTy(DAG.getDataLayout()) &&
9102                "Memory operands expect pointer values");
9103 
9104         unsigned ConstraintID =
9105             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9106         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9107                "Failed to convert memory constraint code to constraint id.");
9108 
9109         // Add information to the INLINEASM node to know about this input.
9110         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9111         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9112         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9113                                                         getCurSDLoc(),
9114                                                         MVT::i32));
9115         AsmNodeOperands.push_back(InOperandVal);
9116         break;
9117       }
9118 
9119       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9120         assert(InOperandVal.getValueType() ==
9121                    TLI.getPointerTy(DAG.getDataLayout()) &&
9122                "Address operands expect pointer values");
9123 
9124         unsigned ConstraintID =
9125             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9126         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
9127                "Failed to convert memory constraint code to constraint id.");
9128 
9129         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
9130 
9131         SDValue AsmOp = InOperandVal;
9132         if (isFunction(InOperandVal)) {
9133           auto *GA = dyn_cast<GlobalAddressSDNode>(InOperandVal);
9134           ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Func, 1);
9135           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9136                                              InOperandVal.getValueType(),
9137                                              GA->getOffset());
9138         }
9139 
9140         // Add information to the INLINEASM node to know about this input.
9141         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
9142 
9143         AsmNodeOperands.push_back(
9144             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9145 
9146         AsmNodeOperands.push_back(AsmOp);
9147         break;
9148       }
9149 
9150       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9151               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9152              "Unknown constraint type!");
9153 
9154       // TODO: Support this.
9155       if (OpInfo.isIndirect) {
9156         emitInlineAsmError(
9157             Call, "Don't know how to handle indirect register inputs yet "
9158                   "for constraint '" +
9159                       Twine(OpInfo.ConstraintCode) + "'");
9160         return;
9161       }
9162 
9163       // Copy the input into the appropriate registers.
9164       if (OpInfo.AssignedRegs.Regs.empty()) {
9165         emitInlineAsmError(Call,
9166                            "couldn't allocate input reg for constraint '" +
9167                                Twine(OpInfo.ConstraintCode) + "'");
9168         return;
9169       }
9170 
9171       if (DetectWriteToReservedRegister())
9172         return;
9173 
9174       SDLoc dl = getCurSDLoc();
9175 
9176       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
9177                                         &Call);
9178 
9179       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
9180                                                dl, DAG, AsmNodeOperands);
9181       break;
9182     }
9183     case InlineAsm::isClobber:
9184       // Add the clobbered value to the operand list, so that the register
9185       // allocator is aware that the physreg got clobbered.
9186       if (!OpInfo.AssignedRegs.Regs.empty())
9187         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
9188                                                  false, 0, getCurSDLoc(), DAG,
9189                                                  AsmNodeOperands);
9190       break;
9191     }
9192   }
9193 
9194   // Finish up input operands.  Set the input chain and add the flag last.
9195   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9196   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
9197 
9198   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9199   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9200                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9201   Flag = Chain.getValue(1);
9202 
9203   // Do additional work to generate outputs.
9204 
9205   SmallVector<EVT, 1> ResultVTs;
9206   SmallVector<SDValue, 1> ResultValues;
9207   SmallVector<SDValue, 8> OutChains;
9208 
9209   llvm::Type *CallResultType = Call.getType();
9210   ArrayRef<Type *> ResultTypes;
9211   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9212     ResultTypes = StructResult->elements();
9213   else if (!CallResultType->isVoidTy())
9214     ResultTypes = makeArrayRef(CallResultType);
9215 
9216   auto CurResultType = ResultTypes.begin();
9217   auto handleRegAssign = [&](SDValue V) {
9218     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9219     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9220     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9221     ++CurResultType;
9222     // If the type of the inline asm call site return value is different but has
9223     // same size as the type of the asm output bitcast it.  One example of this
9224     // is for vectors with different width / number of elements.  This can
9225     // happen for register classes that can contain multiple different value
9226     // types.  The preg or vreg allocated may not have the same VT as was
9227     // expected.
9228     //
9229     // This can also happen for a return value that disagrees with the register
9230     // class it is put in, eg. a double in a general-purpose register on a
9231     // 32-bit machine.
9232     if (ResultVT != V.getValueType() &&
9233         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9234       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9235     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9236              V.getValueType().isInteger()) {
9237       // If a result value was tied to an input value, the computed result
9238       // may have a wider width than the expected result.  Extract the
9239       // relevant portion.
9240       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9241     }
9242     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9243     ResultVTs.push_back(ResultVT);
9244     ResultValues.push_back(V);
9245   };
9246 
9247   // Deal with output operands.
9248   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9249     if (OpInfo.Type == InlineAsm::isOutput) {
9250       SDValue Val;
9251       // Skip trivial output operands.
9252       if (OpInfo.AssignedRegs.Regs.empty())
9253         continue;
9254 
9255       switch (OpInfo.ConstraintType) {
9256       case TargetLowering::C_Register:
9257       case TargetLowering::C_RegisterClass:
9258         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9259                                                   Chain, &Flag, &Call);
9260         break;
9261       case TargetLowering::C_Immediate:
9262       case TargetLowering::C_Other:
9263         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9264                                               OpInfo, DAG);
9265         break;
9266       case TargetLowering::C_Memory:
9267         break; // Already handled.
9268       case TargetLowering::C_Address:
9269         break; // Silence warning.
9270       case TargetLowering::C_Unknown:
9271         assert(false && "Unexpected unknown constraint");
9272       }
9273 
9274       // Indirect output manifest as stores. Record output chains.
9275       if (OpInfo.isIndirect) {
9276         const Value *Ptr = OpInfo.CallOperandVal;
9277         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9278         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9279                                      MachinePointerInfo(Ptr));
9280         OutChains.push_back(Store);
9281       } else {
9282         // generate CopyFromRegs to associated registers.
9283         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9284         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9285           for (const SDValue &V : Val->op_values())
9286             handleRegAssign(V);
9287         } else
9288           handleRegAssign(Val);
9289       }
9290     }
9291   }
9292 
9293   // Set results.
9294   if (!ResultValues.empty()) {
9295     assert(CurResultType == ResultTypes.end() &&
9296            "Mismatch in number of ResultTypes");
9297     assert(ResultValues.size() == ResultTypes.size() &&
9298            "Mismatch in number of output operands in asm result");
9299 
9300     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9301                             DAG.getVTList(ResultVTs), ResultValues);
9302     setValue(&Call, V);
9303   }
9304 
9305   // Collect store chains.
9306   if (!OutChains.empty())
9307     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9308 
9309   if (EmitEHLabels) {
9310     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9311   }
9312 
9313   // Only Update Root if inline assembly has a memory effect.
9314   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9315       EmitEHLabels)
9316     DAG.setRoot(Chain);
9317 }
9318 
9319 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9320                                              const Twine &Message) {
9321   LLVMContext &Ctx = *DAG.getContext();
9322   Ctx.emitError(&Call, Message);
9323 
9324   // Make sure we leave the DAG in a valid state
9325   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9326   SmallVector<EVT, 1> ValueVTs;
9327   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9328 
9329   if (ValueVTs.empty())
9330     return;
9331 
9332   SmallVector<SDValue, 1> Ops;
9333   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9334     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9335 
9336   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9337 }
9338 
9339 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9340   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9341                           MVT::Other, getRoot(),
9342                           getValue(I.getArgOperand(0)),
9343                           DAG.getSrcValue(I.getArgOperand(0))));
9344 }
9345 
9346 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9348   const DataLayout &DL = DAG.getDataLayout();
9349   SDValue V = DAG.getVAArg(
9350       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9351       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9352       DL.getABITypeAlign(I.getType()).value());
9353   DAG.setRoot(V.getValue(1));
9354 
9355   if (I.getType()->isPointerTy())
9356     V = DAG.getPtrExtOrTrunc(
9357         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9358   setValue(&I, V);
9359 }
9360 
9361 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9362   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9363                           MVT::Other, getRoot(),
9364                           getValue(I.getArgOperand(0)),
9365                           DAG.getSrcValue(I.getArgOperand(0))));
9366 }
9367 
9368 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9369   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9370                           MVT::Other, getRoot(),
9371                           getValue(I.getArgOperand(0)),
9372                           getValue(I.getArgOperand(1)),
9373                           DAG.getSrcValue(I.getArgOperand(0)),
9374                           DAG.getSrcValue(I.getArgOperand(1))));
9375 }
9376 
9377 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9378                                                     const Instruction &I,
9379                                                     SDValue Op) {
9380   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9381   if (!Range)
9382     return Op;
9383 
9384   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9385   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9386     return Op;
9387 
9388   APInt Lo = CR.getUnsignedMin();
9389   if (!Lo.isMinValue())
9390     return Op;
9391 
9392   APInt Hi = CR.getUnsignedMax();
9393   unsigned Bits = std::max(Hi.getActiveBits(),
9394                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9395 
9396   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9397 
9398   SDLoc SL = getCurSDLoc();
9399 
9400   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9401                              DAG.getValueType(SmallVT));
9402   unsigned NumVals = Op.getNode()->getNumValues();
9403   if (NumVals == 1)
9404     return ZExt;
9405 
9406   SmallVector<SDValue, 4> Ops;
9407 
9408   Ops.push_back(ZExt);
9409   for (unsigned I = 1; I != NumVals; ++I)
9410     Ops.push_back(Op.getValue(I));
9411 
9412   return DAG.getMergeValues(Ops, SL);
9413 }
9414 
9415 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9416 /// the call being lowered.
9417 ///
9418 /// This is a helper for lowering intrinsics that follow a target calling
9419 /// convention or require stack pointer adjustment. Only a subset of the
9420 /// intrinsic's operands need to participate in the calling convention.
9421 void SelectionDAGBuilder::populateCallLoweringInfo(
9422     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9423     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9424     bool IsPatchPoint) {
9425   TargetLowering::ArgListTy Args;
9426   Args.reserve(NumArgs);
9427 
9428   // Populate the argument list.
9429   // Attributes for args start at offset 1, after the return attribute.
9430   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9431        ArgI != ArgE; ++ArgI) {
9432     const Value *V = Call->getOperand(ArgI);
9433 
9434     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9435 
9436     TargetLowering::ArgListEntry Entry;
9437     Entry.Node = getValue(V);
9438     Entry.Ty = V->getType();
9439     Entry.setAttributes(Call, ArgI);
9440     Args.push_back(Entry);
9441   }
9442 
9443   CLI.setDebugLoc(getCurSDLoc())
9444       .setChain(getRoot())
9445       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9446       .setDiscardResult(Call->use_empty())
9447       .setIsPatchPoint(IsPatchPoint)
9448       .setIsPreallocated(
9449           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9450 }
9451 
9452 /// Add a stack map intrinsic call's live variable operands to a stackmap
9453 /// or patchpoint target node's operand list.
9454 ///
9455 /// Constants are converted to TargetConstants purely as an optimization to
9456 /// avoid constant materialization and register allocation.
9457 ///
9458 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9459 /// generate addess computation nodes, and so FinalizeISel can convert the
9460 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9461 /// address materialization and register allocation, but may also be required
9462 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9463 /// alloca in the entry block, then the runtime may assume that the alloca's
9464 /// StackMap location can be read immediately after compilation and that the
9465 /// location is valid at any point during execution (this is similar to the
9466 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9467 /// only available in a register, then the runtime would need to trap when
9468 /// execution reaches the StackMap in order to read the alloca's location.
9469 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9470                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9471                                 SelectionDAGBuilder &Builder) {
9472   SelectionDAG &DAG = Builder.DAG;
9473   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
9474     SDValue Op = Builder.getValue(Call.getArgOperand(I));
9475 
9476     // Things on the stack are pointer-typed, meaning that they are already
9477     // legal and can be emitted directly to target nodes.
9478     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
9479       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
9480     } else {
9481       // Otherwise emit a target independent node to be legalised.
9482       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
9483     }
9484   }
9485 }
9486 
9487 /// Lower llvm.experimental.stackmap.
9488 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9489   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
9490   //                                  [live variables...])
9491 
9492   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9493 
9494   SDValue Chain, InFlag, Callee;
9495   SmallVector<SDValue, 32> Ops;
9496 
9497   SDLoc DL = getCurSDLoc();
9498   Callee = getValue(CI.getCalledOperand());
9499 
9500   // The stackmap intrinsic only records the live variables (the arguments
9501   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9502   // intrinsic, this won't be lowered to a function call. This means we don't
9503   // have to worry about calling conventions and target specific lowering code.
9504   // Instead we perform the call lowering right here.
9505   //
9506   // chain, flag = CALLSEQ_START(chain, 0, 0)
9507   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9508   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9509   //
9510   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9511   InFlag = Chain.getValue(1);
9512 
9513   // Add the STACKMAP operands, starting with DAG house-keeping.
9514   Ops.push_back(Chain);
9515   Ops.push_back(InFlag);
9516 
9517   // Add the <id>, <numShadowBytes> operands.
9518   //
9519   // These do not require legalisation, and can be emitted directly to target
9520   // constant nodes.
9521   SDValue ID = getValue(CI.getArgOperand(0));
9522   assert(ID.getValueType() == MVT::i64);
9523   SDValue IDConst = DAG.getTargetConstant(
9524       cast<ConstantSDNode>(ID)->getZExtValue(), DL, ID.getValueType());
9525   Ops.push_back(IDConst);
9526 
9527   SDValue Shad = getValue(CI.getArgOperand(1));
9528   assert(Shad.getValueType() == MVT::i32);
9529   SDValue ShadConst = DAG.getTargetConstant(
9530       cast<ConstantSDNode>(Shad)->getZExtValue(), DL, Shad.getValueType());
9531   Ops.push_back(ShadConst);
9532 
9533   // Add the live variables.
9534   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9535 
9536   // Create the STACKMAP node.
9537   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9538   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
9539   InFlag = Chain.getValue(1);
9540 
9541   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InFlag, DL);
9542 
9543   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9544 
9545   // Set the root to the target-lowered call chain.
9546   DAG.setRoot(Chain);
9547 
9548   // Inform the Frame Information that we have a stackmap in this function.
9549   FuncInfo.MF->getFrameInfo().setHasStackMap();
9550 }
9551 
9552 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9553 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9554                                           const BasicBlock *EHPadBB) {
9555   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9556   //                                                 i32 <numBytes>,
9557   //                                                 i8* <target>,
9558   //                                                 i32 <numArgs>,
9559   //                                                 [Args...],
9560   //                                                 [live variables...])
9561 
9562   CallingConv::ID CC = CB.getCallingConv();
9563   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9564   bool HasDef = !CB.getType()->isVoidTy();
9565   SDLoc dl = getCurSDLoc();
9566   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9567 
9568   // Handle immediate and symbolic callees.
9569   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9570     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9571                                    /*isTarget=*/true);
9572   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9573     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9574                                          SDLoc(SymbolicCallee),
9575                                          SymbolicCallee->getValueType(0));
9576 
9577   // Get the real number of arguments participating in the call <numArgs>
9578   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9579   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9580 
9581   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9582   // Intrinsics include all meta-operands up to but not including CC.
9583   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9584   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9585          "Not enough arguments provided to the patchpoint intrinsic");
9586 
9587   // For AnyRegCC the arguments are lowered later on manually.
9588   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9589   Type *ReturnTy =
9590       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9591 
9592   TargetLowering::CallLoweringInfo CLI(DAG);
9593   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9594                            ReturnTy, true);
9595   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9596 
9597   SDNode *CallEnd = Result.second.getNode();
9598   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9599     CallEnd = CallEnd->getOperand(0).getNode();
9600 
9601   /// Get a call instruction from the call sequence chain.
9602   /// Tail calls are not allowed.
9603   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9604          "Expected a callseq node.");
9605   SDNode *Call = CallEnd->getOperand(0).getNode();
9606   bool HasGlue = Call->getGluedNode();
9607 
9608   // Replace the target specific call node with the patchable intrinsic.
9609   SmallVector<SDValue, 8> Ops;
9610 
9611   // Push the chain.
9612   Ops.push_back(*(Call->op_begin()));
9613 
9614   // Optionally, push the glue (if any).
9615   if (HasGlue)
9616     Ops.push_back(*(Call->op_end() - 1));
9617 
9618   // Push the register mask info.
9619   if (HasGlue)
9620     Ops.push_back(*(Call->op_end() - 2));
9621   else
9622     Ops.push_back(*(Call->op_end() - 1));
9623 
9624   // Add the <id> and <numBytes> constants.
9625   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9626   Ops.push_back(DAG.getTargetConstant(
9627                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9628   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9629   Ops.push_back(DAG.getTargetConstant(
9630                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9631                   MVT::i32));
9632 
9633   // Add the callee.
9634   Ops.push_back(Callee);
9635 
9636   // Adjust <numArgs> to account for any arguments that have been passed on the
9637   // stack instead.
9638   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9639   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9640   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9641   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9642 
9643   // Add the calling convention
9644   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9645 
9646   // Add the arguments we omitted previously. The register allocator should
9647   // place these in any free register.
9648   if (IsAnyRegCC)
9649     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9650       Ops.push_back(getValue(CB.getArgOperand(i)));
9651 
9652   // Push the arguments from the call instruction.
9653   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9654   Ops.append(Call->op_begin() + 2, e);
9655 
9656   // Push live variables for the stack map.
9657   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9658 
9659   SDVTList NodeTys;
9660   if (IsAnyRegCC && HasDef) {
9661     // Create the return types based on the intrinsic definition
9662     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9663     SmallVector<EVT, 3> ValueVTs;
9664     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9665     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9666 
9667     // There is always a chain and a glue type at the end
9668     ValueVTs.push_back(MVT::Other);
9669     ValueVTs.push_back(MVT::Glue);
9670     NodeTys = DAG.getVTList(ValueVTs);
9671   } else
9672     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9673 
9674   // Replace the target specific call node with a PATCHPOINT node.
9675   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
9676 
9677   // Update the NodeMap.
9678   if (HasDef) {
9679     if (IsAnyRegCC)
9680       setValue(&CB, SDValue(PPV.getNode(), 0));
9681     else
9682       setValue(&CB, Result.first);
9683   }
9684 
9685   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9686   // call sequence. Furthermore the location of the chain and glue can change
9687   // when the AnyReg calling convention is used and the intrinsic returns a
9688   // value.
9689   if (IsAnyRegCC && HasDef) {
9690     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9691     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
9692     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9693   } else
9694     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
9695   DAG.DeleteNode(Call);
9696 
9697   // Inform the Frame Information that we have a patchpoint in this function.
9698   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9699 }
9700 
9701 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9702                                             unsigned Intrinsic) {
9703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9704   SDValue Op1 = getValue(I.getArgOperand(0));
9705   SDValue Op2;
9706   if (I.arg_size() > 1)
9707     Op2 = getValue(I.getArgOperand(1));
9708   SDLoc dl = getCurSDLoc();
9709   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9710   SDValue Res;
9711   SDNodeFlags SDFlags;
9712   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9713     SDFlags.copyFMF(*FPMO);
9714 
9715   switch (Intrinsic) {
9716   case Intrinsic::vector_reduce_fadd:
9717     if (SDFlags.hasAllowReassociation())
9718       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9719                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9720                         SDFlags);
9721     else
9722       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9723     break;
9724   case Intrinsic::vector_reduce_fmul:
9725     if (SDFlags.hasAllowReassociation())
9726       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9727                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9728                         SDFlags);
9729     else
9730       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9731     break;
9732   case Intrinsic::vector_reduce_add:
9733     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9734     break;
9735   case Intrinsic::vector_reduce_mul:
9736     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9737     break;
9738   case Intrinsic::vector_reduce_and:
9739     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9740     break;
9741   case Intrinsic::vector_reduce_or:
9742     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9743     break;
9744   case Intrinsic::vector_reduce_xor:
9745     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9746     break;
9747   case Intrinsic::vector_reduce_smax:
9748     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9749     break;
9750   case Intrinsic::vector_reduce_smin:
9751     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9752     break;
9753   case Intrinsic::vector_reduce_umax:
9754     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9755     break;
9756   case Intrinsic::vector_reduce_umin:
9757     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9758     break;
9759   case Intrinsic::vector_reduce_fmax:
9760     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9761     break;
9762   case Intrinsic::vector_reduce_fmin:
9763     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9764     break;
9765   default:
9766     llvm_unreachable("Unhandled vector reduce intrinsic");
9767   }
9768   setValue(&I, Res);
9769 }
9770 
9771 /// Returns an AttributeList representing the attributes applied to the return
9772 /// value of the given call.
9773 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9774   SmallVector<Attribute::AttrKind, 2> Attrs;
9775   if (CLI.RetSExt)
9776     Attrs.push_back(Attribute::SExt);
9777   if (CLI.RetZExt)
9778     Attrs.push_back(Attribute::ZExt);
9779   if (CLI.IsInReg)
9780     Attrs.push_back(Attribute::InReg);
9781 
9782   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9783                             Attrs);
9784 }
9785 
9786 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9787 /// implementation, which just calls LowerCall.
9788 /// FIXME: When all targets are
9789 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9790 std::pair<SDValue, SDValue>
9791 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9792   // Handle the incoming return values from the call.
9793   CLI.Ins.clear();
9794   Type *OrigRetTy = CLI.RetTy;
9795   SmallVector<EVT, 4> RetTys;
9796   SmallVector<uint64_t, 4> Offsets;
9797   auto &DL = CLI.DAG.getDataLayout();
9798   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9799 
9800   if (CLI.IsPostTypeLegalization) {
9801     // If we are lowering a libcall after legalization, split the return type.
9802     SmallVector<EVT, 4> OldRetTys;
9803     SmallVector<uint64_t, 4> OldOffsets;
9804     RetTys.swap(OldRetTys);
9805     Offsets.swap(OldOffsets);
9806 
9807     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9808       EVT RetVT = OldRetTys[i];
9809       uint64_t Offset = OldOffsets[i];
9810       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9811       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9812       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9813       RetTys.append(NumRegs, RegisterVT);
9814       for (unsigned j = 0; j != NumRegs; ++j)
9815         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9816     }
9817   }
9818 
9819   SmallVector<ISD::OutputArg, 4> Outs;
9820   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9821 
9822   bool CanLowerReturn =
9823       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9824                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9825 
9826   SDValue DemoteStackSlot;
9827   int DemoteStackIdx = -100;
9828   if (!CanLowerReturn) {
9829     // FIXME: equivalent assert?
9830     // assert(!CS.hasInAllocaArgument() &&
9831     //        "sret demotion is incompatible with inalloca");
9832     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9833     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9834     MachineFunction &MF = CLI.DAG.getMachineFunction();
9835     DemoteStackIdx =
9836         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9837     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9838                                               DL.getAllocaAddrSpace());
9839 
9840     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9841     ArgListEntry Entry;
9842     Entry.Node = DemoteStackSlot;
9843     Entry.Ty = StackSlotPtrType;
9844     Entry.IsSExt = false;
9845     Entry.IsZExt = false;
9846     Entry.IsInReg = false;
9847     Entry.IsSRet = true;
9848     Entry.IsNest = false;
9849     Entry.IsByVal = false;
9850     Entry.IsByRef = false;
9851     Entry.IsReturned = false;
9852     Entry.IsSwiftSelf = false;
9853     Entry.IsSwiftAsync = false;
9854     Entry.IsSwiftError = false;
9855     Entry.IsCFGuardTarget = false;
9856     Entry.Alignment = Alignment;
9857     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9858     CLI.NumFixedArgs += 1;
9859     CLI.getArgs()[0].IndirectType = CLI.RetTy;
9860     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9861 
9862     // sret demotion isn't compatible with tail-calls, since the sret argument
9863     // points into the callers stack frame.
9864     CLI.IsTailCall = false;
9865   } else {
9866     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9867         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9868     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9869       ISD::ArgFlagsTy Flags;
9870       if (NeedsRegBlock) {
9871         Flags.setInConsecutiveRegs();
9872         if (I == RetTys.size() - 1)
9873           Flags.setInConsecutiveRegsLast();
9874       }
9875       EVT VT = RetTys[I];
9876       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9877                                                      CLI.CallConv, VT);
9878       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9879                                                        CLI.CallConv, VT);
9880       for (unsigned i = 0; i != NumRegs; ++i) {
9881         ISD::InputArg MyFlags;
9882         MyFlags.Flags = Flags;
9883         MyFlags.VT = RegisterVT;
9884         MyFlags.ArgVT = VT;
9885         MyFlags.Used = CLI.IsReturnValueUsed;
9886         if (CLI.RetTy->isPointerTy()) {
9887           MyFlags.Flags.setPointer();
9888           MyFlags.Flags.setPointerAddrSpace(
9889               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9890         }
9891         if (CLI.RetSExt)
9892           MyFlags.Flags.setSExt();
9893         if (CLI.RetZExt)
9894           MyFlags.Flags.setZExt();
9895         if (CLI.IsInReg)
9896           MyFlags.Flags.setInReg();
9897         CLI.Ins.push_back(MyFlags);
9898       }
9899     }
9900   }
9901 
9902   // We push in swifterror return as the last element of CLI.Ins.
9903   ArgListTy &Args = CLI.getArgs();
9904   if (supportSwiftError()) {
9905     for (const ArgListEntry &Arg : Args) {
9906       if (Arg.IsSwiftError) {
9907         ISD::InputArg MyFlags;
9908         MyFlags.VT = getPointerTy(DL);
9909         MyFlags.ArgVT = EVT(getPointerTy(DL));
9910         MyFlags.Flags.setSwiftError();
9911         CLI.Ins.push_back(MyFlags);
9912       }
9913     }
9914   }
9915 
9916   // Handle all of the outgoing arguments.
9917   CLI.Outs.clear();
9918   CLI.OutVals.clear();
9919   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9920     SmallVector<EVT, 4> ValueVTs;
9921     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9922     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9923     Type *FinalType = Args[i].Ty;
9924     if (Args[i].IsByVal)
9925       FinalType = Args[i].IndirectType;
9926     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9927         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9928     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9929          ++Value) {
9930       EVT VT = ValueVTs[Value];
9931       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9932       SDValue Op = SDValue(Args[i].Node.getNode(),
9933                            Args[i].Node.getResNo() + Value);
9934       ISD::ArgFlagsTy Flags;
9935 
9936       // Certain targets (such as MIPS), may have a different ABI alignment
9937       // for a type depending on the context. Give the target a chance to
9938       // specify the alignment it wants.
9939       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9940       Flags.setOrigAlign(OriginalAlignment);
9941 
9942       if (Args[i].Ty->isPointerTy()) {
9943         Flags.setPointer();
9944         Flags.setPointerAddrSpace(
9945             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9946       }
9947       if (Args[i].IsZExt)
9948         Flags.setZExt();
9949       if (Args[i].IsSExt)
9950         Flags.setSExt();
9951       if (Args[i].IsInReg) {
9952         // If we are using vectorcall calling convention, a structure that is
9953         // passed InReg - is surely an HVA
9954         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9955             isa<StructType>(FinalType)) {
9956           // The first value of a structure is marked
9957           if (0 == Value)
9958             Flags.setHvaStart();
9959           Flags.setHva();
9960         }
9961         // Set InReg Flag
9962         Flags.setInReg();
9963       }
9964       if (Args[i].IsSRet)
9965         Flags.setSRet();
9966       if (Args[i].IsSwiftSelf)
9967         Flags.setSwiftSelf();
9968       if (Args[i].IsSwiftAsync)
9969         Flags.setSwiftAsync();
9970       if (Args[i].IsSwiftError)
9971         Flags.setSwiftError();
9972       if (Args[i].IsCFGuardTarget)
9973         Flags.setCFGuardTarget();
9974       if (Args[i].IsByVal)
9975         Flags.setByVal();
9976       if (Args[i].IsByRef)
9977         Flags.setByRef();
9978       if (Args[i].IsPreallocated) {
9979         Flags.setPreallocated();
9980         // Set the byval flag for CCAssignFn callbacks that don't know about
9981         // preallocated.  This way we can know how many bytes we should've
9982         // allocated and how many bytes a callee cleanup function will pop.  If
9983         // we port preallocated to more targets, we'll have to add custom
9984         // preallocated handling in the various CC lowering callbacks.
9985         Flags.setByVal();
9986       }
9987       if (Args[i].IsInAlloca) {
9988         Flags.setInAlloca();
9989         // Set the byval flag for CCAssignFn callbacks that don't know about
9990         // inalloca.  This way we can know how many bytes we should've allocated
9991         // and how many bytes a callee cleanup function will pop.  If we port
9992         // inalloca to more targets, we'll have to add custom inalloca handling
9993         // in the various CC lowering callbacks.
9994         Flags.setByVal();
9995       }
9996       Align MemAlign;
9997       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9998         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9999         Flags.setByValSize(FrameSize);
10000 
10001         // info is not there but there are cases it cannot get right.
10002         if (auto MA = Args[i].Alignment)
10003           MemAlign = *MA;
10004         else
10005           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10006       } else if (auto MA = Args[i].Alignment) {
10007         MemAlign = *MA;
10008       } else {
10009         MemAlign = OriginalAlignment;
10010       }
10011       Flags.setMemAlign(MemAlign);
10012       if (Args[i].IsNest)
10013         Flags.setNest();
10014       if (NeedsRegBlock)
10015         Flags.setInConsecutiveRegs();
10016 
10017       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10018                                                  CLI.CallConv, VT);
10019       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10020                                                         CLI.CallConv, VT);
10021       SmallVector<SDValue, 4> Parts(NumParts);
10022       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10023 
10024       if (Args[i].IsSExt)
10025         ExtendKind = ISD::SIGN_EXTEND;
10026       else if (Args[i].IsZExt)
10027         ExtendKind = ISD::ZERO_EXTEND;
10028 
10029       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10030       // for now.
10031       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10032           CanLowerReturn) {
10033         assert((CLI.RetTy == Args[i].Ty ||
10034                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10035                  CLI.RetTy->getPointerAddressSpace() ==
10036                      Args[i].Ty->getPointerAddressSpace())) &&
10037                RetTys.size() == NumValues && "unexpected use of 'returned'");
10038         // Before passing 'returned' to the target lowering code, ensure that
10039         // either the register MVT and the actual EVT are the same size or that
10040         // the return value and argument are extended in the same way; in these
10041         // cases it's safe to pass the argument register value unchanged as the
10042         // return register value (although it's at the target's option whether
10043         // to do so)
10044         // TODO: allow code generation to take advantage of partially preserved
10045         // registers rather than clobbering the entire register when the
10046         // parameter extension method is not compatible with the return
10047         // extension method
10048         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10049             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10050              CLI.RetZExt == Args[i].IsZExt))
10051           Flags.setReturned();
10052       }
10053 
10054       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10055                      CLI.CallConv, ExtendKind);
10056 
10057       for (unsigned j = 0; j != NumParts; ++j) {
10058         // if it isn't first piece, alignment must be 1
10059         // For scalable vectors the scalable part is currently handled
10060         // by individual targets, so we just use the known minimum size here.
10061         ISD::OutputArg MyFlags(
10062             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10063             i < CLI.NumFixedArgs, i,
10064             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
10065         if (NumParts > 1 && j == 0)
10066           MyFlags.Flags.setSplit();
10067         else if (j != 0) {
10068           MyFlags.Flags.setOrigAlign(Align(1));
10069           if (j == NumParts - 1)
10070             MyFlags.Flags.setSplitEnd();
10071         }
10072 
10073         CLI.Outs.push_back(MyFlags);
10074         CLI.OutVals.push_back(Parts[j]);
10075       }
10076 
10077       if (NeedsRegBlock && Value == NumValues - 1)
10078         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10079     }
10080   }
10081 
10082   SmallVector<SDValue, 4> InVals;
10083   CLI.Chain = LowerCall(CLI, InVals);
10084 
10085   // Update CLI.InVals to use outside of this function.
10086   CLI.InVals = InVals;
10087 
10088   // Verify that the target's LowerCall behaved as expected.
10089   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10090          "LowerCall didn't return a valid chain!");
10091   assert((!CLI.IsTailCall || InVals.empty()) &&
10092          "LowerCall emitted a return value for a tail call!");
10093   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10094          "LowerCall didn't emit the correct number of values!");
10095 
10096   // For a tail call, the return value is merely live-out and there aren't
10097   // any nodes in the DAG representing it. Return a special value to
10098   // indicate that a tail call has been emitted and no more Instructions
10099   // should be processed in the current block.
10100   if (CLI.IsTailCall) {
10101     CLI.DAG.setRoot(CLI.Chain);
10102     return std::make_pair(SDValue(), SDValue());
10103   }
10104 
10105 #ifndef NDEBUG
10106   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10107     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10108     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10109            "LowerCall emitted a value with the wrong type!");
10110   }
10111 #endif
10112 
10113   SmallVector<SDValue, 4> ReturnValues;
10114   if (!CanLowerReturn) {
10115     // The instruction result is the result of loading from the
10116     // hidden sret parameter.
10117     SmallVector<EVT, 1> PVTs;
10118     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
10119 
10120     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10121     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10122     EVT PtrVT = PVTs[0];
10123 
10124     unsigned NumValues = RetTys.size();
10125     ReturnValues.resize(NumValues);
10126     SmallVector<SDValue, 4> Chains(NumValues);
10127 
10128     // An aggregate return value cannot wrap around the address space, so
10129     // offsets to its parts don't wrap either.
10130     SDNodeFlags Flags;
10131     Flags.setNoUnsignedWrap(true);
10132 
10133     MachineFunction &MF = CLI.DAG.getMachineFunction();
10134     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10135     for (unsigned i = 0; i < NumValues; ++i) {
10136       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10137                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10138                                                         PtrVT), Flags);
10139       SDValue L = CLI.DAG.getLoad(
10140           RetTys[i], CLI.DL, CLI.Chain, Add,
10141           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10142                                             DemoteStackIdx, Offsets[i]),
10143           HiddenSRetAlign);
10144       ReturnValues[i] = L;
10145       Chains[i] = L.getValue(1);
10146     }
10147 
10148     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10149   } else {
10150     // Collect the legal value parts into potentially illegal values
10151     // that correspond to the original function's return values.
10152     Optional<ISD::NodeType> AssertOp;
10153     if (CLI.RetSExt)
10154       AssertOp = ISD::AssertSext;
10155     else if (CLI.RetZExt)
10156       AssertOp = ISD::AssertZext;
10157     unsigned CurReg = 0;
10158     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10159       EVT VT = RetTys[I];
10160       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10161                                                      CLI.CallConv, VT);
10162       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10163                                                        CLI.CallConv, VT);
10164 
10165       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
10166                                               NumRegs, RegisterVT, VT, nullptr,
10167                                               CLI.CallConv, AssertOp));
10168       CurReg += NumRegs;
10169     }
10170 
10171     // For a function returning void, there is no return value. We can't create
10172     // such a node, so we just return a null return value in that case. In
10173     // that case, nothing will actually look at the value.
10174     if (ReturnValues.empty())
10175       return std::make_pair(SDValue(), CLI.Chain);
10176   }
10177 
10178   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10179                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10180   return std::make_pair(Res, CLI.Chain);
10181 }
10182 
10183 /// Places new result values for the node in Results (their number
10184 /// and types must exactly match those of the original return values of
10185 /// the node), or leaves Results empty, which indicates that the node is not
10186 /// to be custom lowered after all.
10187 void TargetLowering::LowerOperationWrapper(SDNode *N,
10188                                            SmallVectorImpl<SDValue> &Results,
10189                                            SelectionDAG &DAG) const {
10190   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10191 
10192   if (!Res.getNode())
10193     return;
10194 
10195   // If the original node has one result, take the return value from
10196   // LowerOperation as is. It might not be result number 0.
10197   if (N->getNumValues() == 1) {
10198     Results.push_back(Res);
10199     return;
10200   }
10201 
10202   // If the original node has multiple results, then the return node should
10203   // have the same number of results.
10204   assert((N->getNumValues() == Res->getNumValues()) &&
10205       "Lowering returned the wrong number of results!");
10206 
10207   // Places new result values base on N result number.
10208   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10209     Results.push_back(Res.getValue(I));
10210 }
10211 
10212 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10213   llvm_unreachable("LowerOperation not implemented for this target!");
10214 }
10215 
10216 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10217                                                      unsigned Reg,
10218                                                      ISD::NodeType ExtendType) {
10219   SDValue Op = getNonRegisterValue(V);
10220   assert((Op.getOpcode() != ISD::CopyFromReg ||
10221           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10222          "Copy from a reg to the same reg!");
10223   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10224 
10225   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10226   // If this is an InlineAsm we have to match the registers required, not the
10227   // notional registers required by the type.
10228 
10229   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10230                    None); // This is not an ABI copy.
10231   SDValue Chain = DAG.getEntryNode();
10232 
10233   if (ExtendType == ISD::ANY_EXTEND) {
10234     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10235     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10236       ExtendType = PreferredExtendIt->second;
10237   }
10238   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10239   PendingExports.push_back(Chain);
10240 }
10241 
10242 #include "llvm/CodeGen/SelectionDAGISel.h"
10243 
10244 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10245 /// entry block, return true.  This includes arguments used by switches, since
10246 /// the switch may expand into multiple basic blocks.
10247 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10248   // With FastISel active, we may be splitting blocks, so force creation
10249   // of virtual registers for all non-dead arguments.
10250   if (FastISel)
10251     return A->use_empty();
10252 
10253   const BasicBlock &Entry = A->getParent()->front();
10254   for (const User *U : A->users())
10255     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10256       return false;  // Use not in entry block.
10257 
10258   return true;
10259 }
10260 
10261 using ArgCopyElisionMapTy =
10262     DenseMap<const Argument *,
10263              std::pair<const AllocaInst *, const StoreInst *>>;
10264 
10265 /// Scan the entry block of the function in FuncInfo for arguments that look
10266 /// like copies into a local alloca. Record any copied arguments in
10267 /// ArgCopyElisionCandidates.
10268 static void
10269 findArgumentCopyElisionCandidates(const DataLayout &DL,
10270                                   FunctionLoweringInfo *FuncInfo,
10271                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10272   // Record the state of every static alloca used in the entry block. Argument
10273   // allocas are all used in the entry block, so we need approximately as many
10274   // entries as we have arguments.
10275   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10276   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10277   unsigned NumArgs = FuncInfo->Fn->arg_size();
10278   StaticAllocas.reserve(NumArgs * 2);
10279 
10280   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10281     if (!V)
10282       return nullptr;
10283     V = V->stripPointerCasts();
10284     const auto *AI = dyn_cast<AllocaInst>(V);
10285     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10286       return nullptr;
10287     auto Iter = StaticAllocas.insert({AI, Unknown});
10288     return &Iter.first->second;
10289   };
10290 
10291   // Look for stores of arguments to static allocas. Look through bitcasts and
10292   // GEPs to handle type coercions, as long as the alloca is fully initialized
10293   // by the store. Any non-store use of an alloca escapes it and any subsequent
10294   // unanalyzed store might write it.
10295   // FIXME: Handle structs initialized with multiple stores.
10296   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10297     // Look for stores, and handle non-store uses conservatively.
10298     const auto *SI = dyn_cast<StoreInst>(&I);
10299     if (!SI) {
10300       // We will look through cast uses, so ignore them completely.
10301       if (I.isCast())
10302         continue;
10303       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10304       // to allocas.
10305       if (I.isDebugOrPseudoInst())
10306         continue;
10307       // This is an unknown instruction. Assume it escapes or writes to all
10308       // static alloca operands.
10309       for (const Use &U : I.operands()) {
10310         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10311           *Info = StaticAllocaInfo::Clobbered;
10312       }
10313       continue;
10314     }
10315 
10316     // If the stored value is a static alloca, mark it as escaped.
10317     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10318       *Info = StaticAllocaInfo::Clobbered;
10319 
10320     // Check if the destination is a static alloca.
10321     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10322     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10323     if (!Info)
10324       continue;
10325     const AllocaInst *AI = cast<AllocaInst>(Dst);
10326 
10327     // Skip allocas that have been initialized or clobbered.
10328     if (*Info != StaticAllocaInfo::Unknown)
10329       continue;
10330 
10331     // Check if the stored value is an argument, and that this store fully
10332     // initializes the alloca.
10333     // If the argument type has padding bits we can't directly forward a pointer
10334     // as the upper bits may contain garbage.
10335     // Don't elide copies from the same argument twice.
10336     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10337     const auto *Arg = dyn_cast<Argument>(Val);
10338     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10339         Arg->getType()->isEmptyTy() ||
10340         DL.getTypeStoreSize(Arg->getType()) !=
10341             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10342         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10343         ArgCopyElisionCandidates.count(Arg)) {
10344       *Info = StaticAllocaInfo::Clobbered;
10345       continue;
10346     }
10347 
10348     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10349                       << '\n');
10350 
10351     // Mark this alloca and store for argument copy elision.
10352     *Info = StaticAllocaInfo::Elidable;
10353     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10354 
10355     // Stop scanning if we've seen all arguments. This will happen early in -O0
10356     // builds, which is useful, because -O0 builds have large entry blocks and
10357     // many allocas.
10358     if (ArgCopyElisionCandidates.size() == NumArgs)
10359       break;
10360   }
10361 }
10362 
10363 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10364 /// ArgVal is a load from a suitable fixed stack object.
10365 static void tryToElideArgumentCopy(
10366     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10367     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10368     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10369     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10370     SDValue ArgVal, bool &ArgHasUses) {
10371   // Check if this is a load from a fixed stack object.
10372   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10373   if (!LNode)
10374     return;
10375   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10376   if (!FINode)
10377     return;
10378 
10379   // Check that the fixed stack object is the right size and alignment.
10380   // Look at the alignment that the user wrote on the alloca instead of looking
10381   // at the stack object.
10382   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10383   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10384   const AllocaInst *AI = ArgCopyIter->second.first;
10385   int FixedIndex = FINode->getIndex();
10386   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10387   int OldIndex = AllocaIndex;
10388   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10389   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10390     LLVM_DEBUG(
10391         dbgs() << "  argument copy elision failed due to bad fixed stack "
10392                   "object size\n");
10393     return;
10394   }
10395   Align RequiredAlignment = AI->getAlign();
10396   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10397     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10398                          "greater than stack argument alignment ("
10399                       << DebugStr(RequiredAlignment) << " vs "
10400                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10401     return;
10402   }
10403 
10404   // Perform the elision. Delete the old stack object and replace its only use
10405   // in the variable info map. Mark the stack object as mutable.
10406   LLVM_DEBUG({
10407     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10408            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10409            << '\n';
10410   });
10411   MFI.RemoveStackObject(OldIndex);
10412   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10413   AllocaIndex = FixedIndex;
10414   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10415   Chains.push_back(ArgVal.getValue(1));
10416 
10417   // Avoid emitting code for the store implementing the copy.
10418   const StoreInst *SI = ArgCopyIter->second.second;
10419   ElidedArgCopyInstrs.insert(SI);
10420 
10421   // Check for uses of the argument again so that we can avoid exporting ArgVal
10422   // if it is't used by anything other than the store.
10423   for (const Value *U : Arg.users()) {
10424     if (U != SI) {
10425       ArgHasUses = true;
10426       break;
10427     }
10428   }
10429 }
10430 
10431 void SelectionDAGISel::LowerArguments(const Function &F) {
10432   SelectionDAG &DAG = SDB->DAG;
10433   SDLoc dl = SDB->getCurSDLoc();
10434   const DataLayout &DL = DAG.getDataLayout();
10435   SmallVector<ISD::InputArg, 16> Ins;
10436 
10437   // In Naked functions we aren't going to save any registers.
10438   if (F.hasFnAttribute(Attribute::Naked))
10439     return;
10440 
10441   if (!FuncInfo->CanLowerReturn) {
10442     // Put in an sret pointer parameter before all the other parameters.
10443     SmallVector<EVT, 1> ValueVTs;
10444     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10445                     F.getReturnType()->getPointerTo(
10446                         DAG.getDataLayout().getAllocaAddrSpace()),
10447                     ValueVTs);
10448 
10449     // NOTE: Assuming that a pointer will never break down to more than one VT
10450     // or one register.
10451     ISD::ArgFlagsTy Flags;
10452     Flags.setSRet();
10453     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10454     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10455                          ISD::InputArg::NoArgIndex, 0);
10456     Ins.push_back(RetArg);
10457   }
10458 
10459   // Look for stores of arguments to static allocas. Mark such arguments with a
10460   // flag to ask the target to give us the memory location of that argument if
10461   // available.
10462   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10463   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10464                                     ArgCopyElisionCandidates);
10465 
10466   // Set up the incoming argument description vector.
10467   for (const Argument &Arg : F.args()) {
10468     unsigned ArgNo = Arg.getArgNo();
10469     SmallVector<EVT, 4> ValueVTs;
10470     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10471     bool isArgValueUsed = !Arg.use_empty();
10472     unsigned PartBase = 0;
10473     Type *FinalType = Arg.getType();
10474     if (Arg.hasAttribute(Attribute::ByVal))
10475       FinalType = Arg.getParamByValType();
10476     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10477         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10478     for (unsigned Value = 0, NumValues = ValueVTs.size();
10479          Value != NumValues; ++Value) {
10480       EVT VT = ValueVTs[Value];
10481       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10482       ISD::ArgFlagsTy Flags;
10483 
10484 
10485       if (Arg.getType()->isPointerTy()) {
10486         Flags.setPointer();
10487         Flags.setPointerAddrSpace(
10488             cast<PointerType>(Arg.getType())->getAddressSpace());
10489       }
10490       if (Arg.hasAttribute(Attribute::ZExt))
10491         Flags.setZExt();
10492       if (Arg.hasAttribute(Attribute::SExt))
10493         Flags.setSExt();
10494       if (Arg.hasAttribute(Attribute::InReg)) {
10495         // If we are using vectorcall calling convention, a structure that is
10496         // passed InReg - is surely an HVA
10497         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10498             isa<StructType>(Arg.getType())) {
10499           // The first value of a structure is marked
10500           if (0 == Value)
10501             Flags.setHvaStart();
10502           Flags.setHva();
10503         }
10504         // Set InReg Flag
10505         Flags.setInReg();
10506       }
10507       if (Arg.hasAttribute(Attribute::StructRet))
10508         Flags.setSRet();
10509       if (Arg.hasAttribute(Attribute::SwiftSelf))
10510         Flags.setSwiftSelf();
10511       if (Arg.hasAttribute(Attribute::SwiftAsync))
10512         Flags.setSwiftAsync();
10513       if (Arg.hasAttribute(Attribute::SwiftError))
10514         Flags.setSwiftError();
10515       if (Arg.hasAttribute(Attribute::ByVal))
10516         Flags.setByVal();
10517       if (Arg.hasAttribute(Attribute::ByRef))
10518         Flags.setByRef();
10519       if (Arg.hasAttribute(Attribute::InAlloca)) {
10520         Flags.setInAlloca();
10521         // Set the byval flag for CCAssignFn callbacks that don't know about
10522         // inalloca.  This way we can know how many bytes we should've allocated
10523         // and how many bytes a callee cleanup function will pop.  If we port
10524         // inalloca to more targets, we'll have to add custom inalloca handling
10525         // in the various CC lowering callbacks.
10526         Flags.setByVal();
10527       }
10528       if (Arg.hasAttribute(Attribute::Preallocated)) {
10529         Flags.setPreallocated();
10530         // Set the byval flag for CCAssignFn callbacks that don't know about
10531         // preallocated.  This way we can know how many bytes we should've
10532         // allocated and how many bytes a callee cleanup function will pop.  If
10533         // we port preallocated to more targets, we'll have to add custom
10534         // preallocated handling in the various CC lowering callbacks.
10535         Flags.setByVal();
10536       }
10537 
10538       // Certain targets (such as MIPS), may have a different ABI alignment
10539       // for a type depending on the context. Give the target a chance to
10540       // specify the alignment it wants.
10541       const Align OriginalAlignment(
10542           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10543       Flags.setOrigAlign(OriginalAlignment);
10544 
10545       Align MemAlign;
10546       Type *ArgMemTy = nullptr;
10547       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10548           Flags.isByRef()) {
10549         if (!ArgMemTy)
10550           ArgMemTy = Arg.getPointeeInMemoryValueType();
10551 
10552         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10553 
10554         // For in-memory arguments, size and alignment should be passed from FE.
10555         // BE will guess if this info is not there but there are cases it cannot
10556         // get right.
10557         if (auto ParamAlign = Arg.getParamStackAlign())
10558           MemAlign = *ParamAlign;
10559         else if ((ParamAlign = Arg.getParamAlign()))
10560           MemAlign = *ParamAlign;
10561         else
10562           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10563         if (Flags.isByRef())
10564           Flags.setByRefSize(MemSize);
10565         else
10566           Flags.setByValSize(MemSize);
10567       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10568         MemAlign = *ParamAlign;
10569       } else {
10570         MemAlign = OriginalAlignment;
10571       }
10572       Flags.setMemAlign(MemAlign);
10573 
10574       if (Arg.hasAttribute(Attribute::Nest))
10575         Flags.setNest();
10576       if (NeedsRegBlock)
10577         Flags.setInConsecutiveRegs();
10578       if (ArgCopyElisionCandidates.count(&Arg))
10579         Flags.setCopyElisionCandidate();
10580       if (Arg.hasAttribute(Attribute::Returned))
10581         Flags.setReturned();
10582 
10583       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10584           *CurDAG->getContext(), F.getCallingConv(), VT);
10585       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10586           *CurDAG->getContext(), F.getCallingConv(), VT);
10587       for (unsigned i = 0; i != NumRegs; ++i) {
10588         // For scalable vectors, use the minimum size; individual targets
10589         // are responsible for handling scalable vector arguments and
10590         // return values.
10591         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10592                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10593         if (NumRegs > 1 && i == 0)
10594           MyFlags.Flags.setSplit();
10595         // if it isn't first piece, alignment must be 1
10596         else if (i > 0) {
10597           MyFlags.Flags.setOrigAlign(Align(1));
10598           if (i == NumRegs - 1)
10599             MyFlags.Flags.setSplitEnd();
10600         }
10601         Ins.push_back(MyFlags);
10602       }
10603       if (NeedsRegBlock && Value == NumValues - 1)
10604         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10605       PartBase += VT.getStoreSize().getKnownMinSize();
10606     }
10607   }
10608 
10609   // Call the target to set up the argument values.
10610   SmallVector<SDValue, 8> InVals;
10611   SDValue NewRoot = TLI->LowerFormalArguments(
10612       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10613 
10614   // Verify that the target's LowerFormalArguments behaved as expected.
10615   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10616          "LowerFormalArguments didn't return a valid chain!");
10617   assert(InVals.size() == Ins.size() &&
10618          "LowerFormalArguments didn't emit the correct number of values!");
10619   LLVM_DEBUG({
10620     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10621       assert(InVals[i].getNode() &&
10622              "LowerFormalArguments emitted a null value!");
10623       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10624              "LowerFormalArguments emitted a value with the wrong type!");
10625     }
10626   });
10627 
10628   // Update the DAG with the new chain value resulting from argument lowering.
10629   DAG.setRoot(NewRoot);
10630 
10631   // Set up the argument values.
10632   unsigned i = 0;
10633   if (!FuncInfo->CanLowerReturn) {
10634     // Create a virtual register for the sret pointer, and put in a copy
10635     // from the sret argument into it.
10636     SmallVector<EVT, 1> ValueVTs;
10637     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10638                     F.getReturnType()->getPointerTo(
10639                         DAG.getDataLayout().getAllocaAddrSpace()),
10640                     ValueVTs);
10641     MVT VT = ValueVTs[0].getSimpleVT();
10642     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10643     Optional<ISD::NodeType> AssertOp;
10644     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10645                                         nullptr, F.getCallingConv(), AssertOp);
10646 
10647     MachineFunction& MF = SDB->DAG.getMachineFunction();
10648     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10649     Register SRetReg =
10650         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10651     FuncInfo->DemoteRegister = SRetReg;
10652     NewRoot =
10653         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10654     DAG.setRoot(NewRoot);
10655 
10656     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10657     ++i;
10658   }
10659 
10660   SmallVector<SDValue, 4> Chains;
10661   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10662   for (const Argument &Arg : F.args()) {
10663     SmallVector<SDValue, 4> ArgValues;
10664     SmallVector<EVT, 4> ValueVTs;
10665     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10666     unsigned NumValues = ValueVTs.size();
10667     if (NumValues == 0)
10668       continue;
10669 
10670     bool ArgHasUses = !Arg.use_empty();
10671 
10672     // Elide the copying store if the target loaded this argument from a
10673     // suitable fixed stack object.
10674     if (Ins[i].Flags.isCopyElisionCandidate()) {
10675       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10676                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10677                              InVals[i], ArgHasUses);
10678     }
10679 
10680     // If this argument is unused then remember its value. It is used to generate
10681     // debugging information.
10682     bool isSwiftErrorArg =
10683         TLI->supportSwiftError() &&
10684         Arg.hasAttribute(Attribute::SwiftError);
10685     if (!ArgHasUses && !isSwiftErrorArg) {
10686       SDB->setUnusedArgValue(&Arg, InVals[i]);
10687 
10688       // Also remember any frame index for use in FastISel.
10689       if (FrameIndexSDNode *FI =
10690           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10691         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10692     }
10693 
10694     for (unsigned Val = 0; Val != NumValues; ++Val) {
10695       EVT VT = ValueVTs[Val];
10696       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10697                                                       F.getCallingConv(), VT);
10698       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10699           *CurDAG->getContext(), F.getCallingConv(), VT);
10700 
10701       // Even an apparent 'unused' swifterror argument needs to be returned. So
10702       // we do generate a copy for it that can be used on return from the
10703       // function.
10704       if (ArgHasUses || isSwiftErrorArg) {
10705         Optional<ISD::NodeType> AssertOp;
10706         if (Arg.hasAttribute(Attribute::SExt))
10707           AssertOp = ISD::AssertSext;
10708         else if (Arg.hasAttribute(Attribute::ZExt))
10709           AssertOp = ISD::AssertZext;
10710 
10711         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10712                                              PartVT, VT, nullptr,
10713                                              F.getCallingConv(), AssertOp));
10714       }
10715 
10716       i += NumParts;
10717     }
10718 
10719     // We don't need to do anything else for unused arguments.
10720     if (ArgValues.empty())
10721       continue;
10722 
10723     // Note down frame index.
10724     if (FrameIndexSDNode *FI =
10725         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10726       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10727 
10728     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10729                                      SDB->getCurSDLoc());
10730 
10731     SDB->setValue(&Arg, Res);
10732     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10733       // We want to associate the argument with the frame index, among
10734       // involved operands, that correspond to the lowest address. The
10735       // getCopyFromParts function, called earlier, is swapping the order of
10736       // the operands to BUILD_PAIR depending on endianness. The result of
10737       // that swapping is that the least significant bits of the argument will
10738       // be in the first operand of the BUILD_PAIR node, and the most
10739       // significant bits will be in the second operand.
10740       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10741       if (LoadSDNode *LNode =
10742           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10743         if (FrameIndexSDNode *FI =
10744             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10745           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10746     }
10747 
10748     // Analyses past this point are naive and don't expect an assertion.
10749     if (Res.getOpcode() == ISD::AssertZext)
10750       Res = Res.getOperand(0);
10751 
10752     // Update the SwiftErrorVRegDefMap.
10753     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10754       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10755       if (Register::isVirtualRegister(Reg))
10756         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10757                                    Reg);
10758     }
10759 
10760     // If this argument is live outside of the entry block, insert a copy from
10761     // wherever we got it to the vreg that other BB's will reference it as.
10762     if (Res.getOpcode() == ISD::CopyFromReg) {
10763       // If we can, though, try to skip creating an unnecessary vreg.
10764       // FIXME: This isn't very clean... it would be nice to make this more
10765       // general.
10766       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10767       if (Register::isVirtualRegister(Reg)) {
10768         FuncInfo->ValueMap[&Arg] = Reg;
10769         continue;
10770       }
10771     }
10772     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10773       FuncInfo->InitializeRegForValue(&Arg);
10774       SDB->CopyToExportRegsIfNeeded(&Arg);
10775     }
10776   }
10777 
10778   if (!Chains.empty()) {
10779     Chains.push_back(NewRoot);
10780     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10781   }
10782 
10783   DAG.setRoot(NewRoot);
10784 
10785   assert(i == InVals.size() && "Argument register count mismatch!");
10786 
10787   // If any argument copy elisions occurred and we have debug info, update the
10788   // stale frame indices used in the dbg.declare variable info table.
10789   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10790   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10791     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10792       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10793       if (I != ArgCopyElisionFrameIndexMap.end())
10794         VI.Slot = I->second;
10795     }
10796   }
10797 
10798   // Finally, if the target has anything special to do, allow it to do so.
10799   emitFunctionEntryCode();
10800 }
10801 
10802 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10803 /// ensure constants are generated when needed.  Remember the virtual registers
10804 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10805 /// directly add them, because expansion might result in multiple MBB's for one
10806 /// BB.  As such, the start of the BB might correspond to a different MBB than
10807 /// the end.
10808 void
10809 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10810   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10811 
10812   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10813 
10814   // Check PHI nodes in successors that expect a value to be available from this
10815   // block.
10816   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
10817     if (!isa<PHINode>(SuccBB->begin())) continue;
10818     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10819 
10820     // If this terminator has multiple identical successors (common for
10821     // switches), only handle each succ once.
10822     if (!SuccsHandled.insert(SuccMBB).second)
10823       continue;
10824 
10825     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10826 
10827     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10828     // nodes and Machine PHI nodes, but the incoming operands have not been
10829     // emitted yet.
10830     for (const PHINode &PN : SuccBB->phis()) {
10831       // Ignore dead phi's.
10832       if (PN.use_empty())
10833         continue;
10834 
10835       // Skip empty types
10836       if (PN.getType()->isEmptyTy())
10837         continue;
10838 
10839       unsigned Reg;
10840       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10841 
10842       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
10843         unsigned &RegOut = ConstantsOut[C];
10844         if (RegOut == 0) {
10845           RegOut = FuncInfo.CreateRegs(C);
10846           // We need to zero/sign extend ConstantInt phi operands to match
10847           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
10848           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
10849           if (auto *CI = dyn_cast<ConstantInt>(C))
10850             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
10851                                                     : ISD::ZERO_EXTEND;
10852           CopyValueToVirtualRegister(C, RegOut, ExtendType);
10853         }
10854         Reg = RegOut;
10855       } else {
10856         DenseMap<const Value *, Register>::iterator I =
10857           FuncInfo.ValueMap.find(PHIOp);
10858         if (I != FuncInfo.ValueMap.end())
10859           Reg = I->second;
10860         else {
10861           assert(isa<AllocaInst>(PHIOp) &&
10862                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10863                  "Didn't codegen value into a register!??");
10864           Reg = FuncInfo.CreateRegs(PHIOp);
10865           CopyValueToVirtualRegister(PHIOp, Reg);
10866         }
10867       }
10868 
10869       // Remember that this register needs to added to the machine PHI node as
10870       // the input for this MBB.
10871       SmallVector<EVT, 4> ValueVTs;
10872       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10873       for (EVT VT : ValueVTs) {
10874         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10875         for (unsigned i = 0; i != NumRegisters; ++i)
10876           FuncInfo.PHINodesToUpdate.push_back(
10877               std::make_pair(&*MBBI++, Reg + i));
10878         Reg += NumRegisters;
10879       }
10880     }
10881   }
10882 
10883   ConstantsOut.clear();
10884 }
10885 
10886 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10887   MachineFunction::iterator I(MBB);
10888   if (++I == FuncInfo.MF->end())
10889     return nullptr;
10890   return &*I;
10891 }
10892 
10893 /// During lowering new call nodes can be created (such as memset, etc.).
10894 /// Those will become new roots of the current DAG, but complications arise
10895 /// when they are tail calls. In such cases, the call lowering will update
10896 /// the root, but the builder still needs to know that a tail call has been
10897 /// lowered in order to avoid generating an additional return.
10898 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10899   // If the node is null, we do have a tail call.
10900   if (MaybeTC.getNode() != nullptr)
10901     DAG.setRoot(MaybeTC);
10902   else
10903     HasTailCall = true;
10904 }
10905 
10906 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10907                                         MachineBasicBlock *SwitchMBB,
10908                                         MachineBasicBlock *DefaultMBB) {
10909   MachineFunction *CurMF = FuncInfo.MF;
10910   MachineBasicBlock *NextMBB = nullptr;
10911   MachineFunction::iterator BBI(W.MBB);
10912   if (++BBI != FuncInfo.MF->end())
10913     NextMBB = &*BBI;
10914 
10915   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10916 
10917   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10918 
10919   if (Size == 2 && W.MBB == SwitchMBB) {
10920     // If any two of the cases has the same destination, and if one value
10921     // is the same as the other, but has one bit unset that the other has set,
10922     // use bit manipulation to do two compares at once.  For example:
10923     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10924     // TODO: This could be extended to merge any 2 cases in switches with 3
10925     // cases.
10926     // TODO: Handle cases where W.CaseBB != SwitchBB.
10927     CaseCluster &Small = *W.FirstCluster;
10928     CaseCluster &Big = *W.LastCluster;
10929 
10930     if (Small.Low == Small.High && Big.Low == Big.High &&
10931         Small.MBB == Big.MBB) {
10932       const APInt &SmallValue = Small.Low->getValue();
10933       const APInt &BigValue = Big.Low->getValue();
10934 
10935       // Check that there is only one bit different.
10936       APInt CommonBit = BigValue ^ SmallValue;
10937       if (CommonBit.isPowerOf2()) {
10938         SDValue CondLHS = getValue(Cond);
10939         EVT VT = CondLHS.getValueType();
10940         SDLoc DL = getCurSDLoc();
10941 
10942         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10943                                  DAG.getConstant(CommonBit, DL, VT));
10944         SDValue Cond = DAG.getSetCC(
10945             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10946             ISD::SETEQ);
10947 
10948         // Update successor info.
10949         // Both Small and Big will jump to Small.BB, so we sum up the
10950         // probabilities.
10951         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10952         if (BPI)
10953           addSuccessorWithProb(
10954               SwitchMBB, DefaultMBB,
10955               // The default destination is the first successor in IR.
10956               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10957         else
10958           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10959 
10960         // Insert the true branch.
10961         SDValue BrCond =
10962             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10963                         DAG.getBasicBlock(Small.MBB));
10964         // Insert the false branch.
10965         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10966                              DAG.getBasicBlock(DefaultMBB));
10967 
10968         DAG.setRoot(BrCond);
10969         return;
10970       }
10971     }
10972   }
10973 
10974   if (TM.getOptLevel() != CodeGenOpt::None) {
10975     // Here, we order cases by probability so the most likely case will be
10976     // checked first. However, two clusters can have the same probability in
10977     // which case their relative ordering is non-deterministic. So we use Low
10978     // as a tie-breaker as clusters are guaranteed to never overlap.
10979     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10980                [](const CaseCluster &a, const CaseCluster &b) {
10981       return a.Prob != b.Prob ?
10982              a.Prob > b.Prob :
10983              a.Low->getValue().slt(b.Low->getValue());
10984     });
10985 
10986     // Rearrange the case blocks so that the last one falls through if possible
10987     // without changing the order of probabilities.
10988     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10989       --I;
10990       if (I->Prob > W.LastCluster->Prob)
10991         break;
10992       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10993         std::swap(*I, *W.LastCluster);
10994         break;
10995       }
10996     }
10997   }
10998 
10999   // Compute total probability.
11000   BranchProbability DefaultProb = W.DefaultProb;
11001   BranchProbability UnhandledProbs = DefaultProb;
11002   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11003     UnhandledProbs += I->Prob;
11004 
11005   MachineBasicBlock *CurMBB = W.MBB;
11006   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11007     bool FallthroughUnreachable = false;
11008     MachineBasicBlock *Fallthrough;
11009     if (I == W.LastCluster) {
11010       // For the last cluster, fall through to the default destination.
11011       Fallthrough = DefaultMBB;
11012       FallthroughUnreachable = isa<UnreachableInst>(
11013           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11014     } else {
11015       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11016       CurMF->insert(BBI, Fallthrough);
11017       // Put Cond in a virtual register to make it available from the new blocks.
11018       ExportFromCurrentBlock(Cond);
11019     }
11020     UnhandledProbs -= I->Prob;
11021 
11022     switch (I->Kind) {
11023       case CC_JumpTable: {
11024         // FIXME: Optimize away range check based on pivot comparisons.
11025         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11026         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11027 
11028         // The jump block hasn't been inserted yet; insert it here.
11029         MachineBasicBlock *JumpMBB = JT->MBB;
11030         CurMF->insert(BBI, JumpMBB);
11031 
11032         auto JumpProb = I->Prob;
11033         auto FallthroughProb = UnhandledProbs;
11034 
11035         // If the default statement is a target of the jump table, we evenly
11036         // distribute the default probability to successors of CurMBB. Also
11037         // update the probability on the edge from JumpMBB to Fallthrough.
11038         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11039                                               SE = JumpMBB->succ_end();
11040              SI != SE; ++SI) {
11041           if (*SI == DefaultMBB) {
11042             JumpProb += DefaultProb / 2;
11043             FallthroughProb -= DefaultProb / 2;
11044             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11045             JumpMBB->normalizeSuccProbs();
11046             break;
11047           }
11048         }
11049 
11050         if (FallthroughUnreachable)
11051           JTH->FallthroughUnreachable = true;
11052 
11053         if (!JTH->FallthroughUnreachable)
11054           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11055         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11056         CurMBB->normalizeSuccProbs();
11057 
11058         // The jump table header will be inserted in our current block, do the
11059         // range check, and fall through to our fallthrough block.
11060         JTH->HeaderBB = CurMBB;
11061         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11062 
11063         // If we're in the right place, emit the jump table header right now.
11064         if (CurMBB == SwitchMBB) {
11065           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11066           JTH->Emitted = true;
11067         }
11068         break;
11069       }
11070       case CC_BitTests: {
11071         // FIXME: Optimize away range check based on pivot comparisons.
11072         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11073 
11074         // The bit test blocks haven't been inserted yet; insert them here.
11075         for (BitTestCase &BTC : BTB->Cases)
11076           CurMF->insert(BBI, BTC.ThisBB);
11077 
11078         // Fill in fields of the BitTestBlock.
11079         BTB->Parent = CurMBB;
11080         BTB->Default = Fallthrough;
11081 
11082         BTB->DefaultProb = UnhandledProbs;
11083         // If the cases in bit test don't form a contiguous range, we evenly
11084         // distribute the probability on the edge to Fallthrough to two
11085         // successors of CurMBB.
11086         if (!BTB->ContiguousRange) {
11087           BTB->Prob += DefaultProb / 2;
11088           BTB->DefaultProb -= DefaultProb / 2;
11089         }
11090 
11091         if (FallthroughUnreachable)
11092           BTB->FallthroughUnreachable = true;
11093 
11094         // If we're in the right place, emit the bit test header right now.
11095         if (CurMBB == SwitchMBB) {
11096           visitBitTestHeader(*BTB, SwitchMBB);
11097           BTB->Emitted = true;
11098         }
11099         break;
11100       }
11101       case CC_Range: {
11102         const Value *RHS, *LHS, *MHS;
11103         ISD::CondCode CC;
11104         if (I->Low == I->High) {
11105           // Check Cond == I->Low.
11106           CC = ISD::SETEQ;
11107           LHS = Cond;
11108           RHS=I->Low;
11109           MHS = nullptr;
11110         } else {
11111           // Check I->Low <= Cond <= I->High.
11112           CC = ISD::SETLE;
11113           LHS = I->Low;
11114           MHS = Cond;
11115           RHS = I->High;
11116         }
11117 
11118         // If Fallthrough is unreachable, fold away the comparison.
11119         if (FallthroughUnreachable)
11120           CC = ISD::SETTRUE;
11121 
11122         // The false probability is the sum of all unhandled cases.
11123         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11124                      getCurSDLoc(), I->Prob, UnhandledProbs);
11125 
11126         if (CurMBB == SwitchMBB)
11127           visitSwitchCase(CB, SwitchMBB);
11128         else
11129           SL->SwitchCases.push_back(CB);
11130 
11131         break;
11132       }
11133     }
11134     CurMBB = Fallthrough;
11135   }
11136 }
11137 
11138 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
11139                                               CaseClusterIt First,
11140                                               CaseClusterIt Last) {
11141   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
11142     if (X.Prob != CC.Prob)
11143       return X.Prob > CC.Prob;
11144 
11145     // Ties are broken by comparing the case value.
11146     return X.Low->getValue().slt(CC.Low->getValue());
11147   });
11148 }
11149 
11150 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11151                                         const SwitchWorkListItem &W,
11152                                         Value *Cond,
11153                                         MachineBasicBlock *SwitchMBB) {
11154   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11155          "Clusters not sorted?");
11156 
11157   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11158 
11159   // Balance the tree based on branch probabilities to create a near-optimal (in
11160   // terms of search time given key frequency) binary search tree. See e.g. Kurt
11161   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
11162   CaseClusterIt LastLeft = W.FirstCluster;
11163   CaseClusterIt FirstRight = W.LastCluster;
11164   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
11165   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
11166 
11167   // Move LastLeft and FirstRight towards each other from opposite directions to
11168   // find a partitioning of the clusters which balances the probability on both
11169   // sides. If LeftProb and RightProb are equal, alternate which side is
11170   // taken to ensure 0-probability nodes are distributed evenly.
11171   unsigned I = 0;
11172   while (LastLeft + 1 < FirstRight) {
11173     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
11174       LeftProb += (++LastLeft)->Prob;
11175     else
11176       RightProb += (--FirstRight)->Prob;
11177     I++;
11178   }
11179 
11180   while (true) {
11181     // Our binary search tree differs from a typical BST in that ours can have up
11182     // to three values in each leaf. The pivot selection above doesn't take that
11183     // into account, which means the tree might require more nodes and be less
11184     // efficient. We compensate for this here.
11185 
11186     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
11187     unsigned NumRight = W.LastCluster - FirstRight + 1;
11188 
11189     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
11190       // If one side has less than 3 clusters, and the other has more than 3,
11191       // consider taking a cluster from the other side.
11192 
11193       if (NumLeft < NumRight) {
11194         // Consider moving the first cluster on the right to the left side.
11195         CaseCluster &CC = *FirstRight;
11196         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11197         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11198         if (LeftSideRank <= RightSideRank) {
11199           // Moving the cluster to the left does not demote it.
11200           ++LastLeft;
11201           ++FirstRight;
11202           continue;
11203         }
11204       } else {
11205         assert(NumRight < NumLeft);
11206         // Consider moving the last element on the left to the right side.
11207         CaseCluster &CC = *LastLeft;
11208         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
11209         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
11210         if (RightSideRank <= LeftSideRank) {
11211           // Moving the cluster to the right does not demot it.
11212           --LastLeft;
11213           --FirstRight;
11214           continue;
11215         }
11216       }
11217     }
11218     break;
11219   }
11220 
11221   assert(LastLeft + 1 == FirstRight);
11222   assert(LastLeft >= W.FirstCluster);
11223   assert(FirstRight <= W.LastCluster);
11224 
11225   // Use the first element on the right as pivot since we will make less-than
11226   // comparisons against it.
11227   CaseClusterIt PivotCluster = FirstRight;
11228   assert(PivotCluster > W.FirstCluster);
11229   assert(PivotCluster <= W.LastCluster);
11230 
11231   CaseClusterIt FirstLeft = W.FirstCluster;
11232   CaseClusterIt LastRight = W.LastCluster;
11233 
11234   const ConstantInt *Pivot = PivotCluster->Low;
11235 
11236   // New blocks will be inserted immediately after the current one.
11237   MachineFunction::iterator BBI(W.MBB);
11238   ++BBI;
11239 
11240   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11241   // we can branch to its destination directly if it's squeezed exactly in
11242   // between the known lower bound and Pivot - 1.
11243   MachineBasicBlock *LeftMBB;
11244   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11245       FirstLeft->Low == W.GE &&
11246       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11247     LeftMBB = FirstLeft->MBB;
11248   } else {
11249     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11250     FuncInfo.MF->insert(BBI, LeftMBB);
11251     WorkList.push_back(
11252         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11253     // Put Cond in a virtual register to make it available from the new blocks.
11254     ExportFromCurrentBlock(Cond);
11255   }
11256 
11257   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11258   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11259   // directly if RHS.High equals the current upper bound.
11260   MachineBasicBlock *RightMBB;
11261   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11262       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11263     RightMBB = FirstRight->MBB;
11264   } else {
11265     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11266     FuncInfo.MF->insert(BBI, RightMBB);
11267     WorkList.push_back(
11268         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11269     // Put Cond in a virtual register to make it available from the new blocks.
11270     ExportFromCurrentBlock(Cond);
11271   }
11272 
11273   // Create the CaseBlock record that will be used to lower the branch.
11274   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11275                getCurSDLoc(), LeftProb, RightProb);
11276 
11277   if (W.MBB == SwitchMBB)
11278     visitSwitchCase(CB, SwitchMBB);
11279   else
11280     SL->SwitchCases.push_back(CB);
11281 }
11282 
11283 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11284 // from the swith statement.
11285 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11286                                             BranchProbability PeeledCaseProb) {
11287   if (PeeledCaseProb == BranchProbability::getOne())
11288     return BranchProbability::getZero();
11289   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11290 
11291   uint32_t Numerator = CaseProb.getNumerator();
11292   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11293   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11294 }
11295 
11296 // Try to peel the top probability case if it exceeds the threshold.
11297 // Return current MachineBasicBlock for the switch statement if the peeling
11298 // does not occur.
11299 // If the peeling is performed, return the newly created MachineBasicBlock
11300 // for the peeled switch statement. Also update Clusters to remove the peeled
11301 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11302 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11303     const SwitchInst &SI, CaseClusterVector &Clusters,
11304     BranchProbability &PeeledCaseProb) {
11305   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11306   // Don't perform if there is only one cluster or optimizing for size.
11307   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11308       TM.getOptLevel() == CodeGenOpt::None ||
11309       SwitchMBB->getParent()->getFunction().hasMinSize())
11310     return SwitchMBB;
11311 
11312   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11313   unsigned PeeledCaseIndex = 0;
11314   bool SwitchPeeled = false;
11315   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11316     CaseCluster &CC = Clusters[Index];
11317     if (CC.Prob < TopCaseProb)
11318       continue;
11319     TopCaseProb = CC.Prob;
11320     PeeledCaseIndex = Index;
11321     SwitchPeeled = true;
11322   }
11323   if (!SwitchPeeled)
11324     return SwitchMBB;
11325 
11326   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11327                     << TopCaseProb << "\n");
11328 
11329   // Record the MBB for the peeled switch statement.
11330   MachineFunction::iterator BBI(SwitchMBB);
11331   ++BBI;
11332   MachineBasicBlock *PeeledSwitchMBB =
11333       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11334   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11335 
11336   ExportFromCurrentBlock(SI.getCondition());
11337   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11338   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11339                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11340   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11341 
11342   Clusters.erase(PeeledCaseIt);
11343   for (CaseCluster &CC : Clusters) {
11344     LLVM_DEBUG(
11345         dbgs() << "Scale the probablity for one cluster, before scaling: "
11346                << CC.Prob << "\n");
11347     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11348     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11349   }
11350   PeeledCaseProb = TopCaseProb;
11351   return PeeledSwitchMBB;
11352 }
11353 
11354 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11355   // Extract cases from the switch.
11356   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11357   CaseClusterVector Clusters;
11358   Clusters.reserve(SI.getNumCases());
11359   for (auto I : SI.cases()) {
11360     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11361     const ConstantInt *CaseVal = I.getCaseValue();
11362     BranchProbability Prob =
11363         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11364             : BranchProbability(1, SI.getNumCases() + 1);
11365     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11366   }
11367 
11368   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11369 
11370   // Cluster adjacent cases with the same destination. We do this at all
11371   // optimization levels because it's cheap to do and will make codegen faster
11372   // if there are many clusters.
11373   sortAndRangeify(Clusters);
11374 
11375   // The branch probablity of the peeled case.
11376   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11377   MachineBasicBlock *PeeledSwitchMBB =
11378       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11379 
11380   // If there is only the default destination, jump there directly.
11381   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11382   if (Clusters.empty()) {
11383     assert(PeeledSwitchMBB == SwitchMBB);
11384     SwitchMBB->addSuccessor(DefaultMBB);
11385     if (DefaultMBB != NextBlock(SwitchMBB)) {
11386       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11387                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11388     }
11389     return;
11390   }
11391 
11392   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11393   SL->findBitTestClusters(Clusters, &SI);
11394 
11395   LLVM_DEBUG({
11396     dbgs() << "Case clusters: ";
11397     for (const CaseCluster &C : Clusters) {
11398       if (C.Kind == CC_JumpTable)
11399         dbgs() << "JT:";
11400       if (C.Kind == CC_BitTests)
11401         dbgs() << "BT:";
11402 
11403       C.Low->getValue().print(dbgs(), true);
11404       if (C.Low != C.High) {
11405         dbgs() << '-';
11406         C.High->getValue().print(dbgs(), true);
11407       }
11408       dbgs() << ' ';
11409     }
11410     dbgs() << '\n';
11411   });
11412 
11413   assert(!Clusters.empty());
11414   SwitchWorkList WorkList;
11415   CaseClusterIt First = Clusters.begin();
11416   CaseClusterIt Last = Clusters.end() - 1;
11417   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11418   // Scale the branchprobability for DefaultMBB if the peel occurs and
11419   // DefaultMBB is not replaced.
11420   if (PeeledCaseProb != BranchProbability::getZero() &&
11421       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11422     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11423   WorkList.push_back(
11424       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11425 
11426   while (!WorkList.empty()) {
11427     SwitchWorkListItem W = WorkList.pop_back_val();
11428     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11429 
11430     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11431         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11432       // For optimized builds, lower large range as a balanced binary tree.
11433       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11434       continue;
11435     }
11436 
11437     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11438   }
11439 }
11440 
11441 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11443   auto DL = getCurSDLoc();
11444   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11445   setValue(&I, DAG.getStepVector(DL, ResultVT));
11446 }
11447 
11448 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11450   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11451 
11452   SDLoc DL = getCurSDLoc();
11453   SDValue V = getValue(I.getOperand(0));
11454   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11455 
11456   if (VT.isScalableVector()) {
11457     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11458     return;
11459   }
11460 
11461   // Use VECTOR_SHUFFLE for the fixed-length vector
11462   // to maintain existing behavior.
11463   SmallVector<int, 8> Mask;
11464   unsigned NumElts = VT.getVectorMinNumElements();
11465   for (unsigned i = 0; i != NumElts; ++i)
11466     Mask.push_back(NumElts - 1 - i);
11467 
11468   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11469 }
11470 
11471 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11472   SmallVector<EVT, 4> ValueVTs;
11473   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11474                   ValueVTs);
11475   unsigned NumValues = ValueVTs.size();
11476   if (NumValues == 0) return;
11477 
11478   SmallVector<SDValue, 4> Values(NumValues);
11479   SDValue Op = getValue(I.getOperand(0));
11480 
11481   for (unsigned i = 0; i != NumValues; ++i)
11482     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11483                             SDValue(Op.getNode(), Op.getResNo() + i));
11484 
11485   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11486                            DAG.getVTList(ValueVTs), Values));
11487 }
11488 
11489 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11490   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11491   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11492 
11493   SDLoc DL = getCurSDLoc();
11494   SDValue V1 = getValue(I.getOperand(0));
11495   SDValue V2 = getValue(I.getOperand(1));
11496   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11497 
11498   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11499   if (VT.isScalableVector()) {
11500     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11501     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11502                              DAG.getConstant(Imm, DL, IdxVT)));
11503     return;
11504   }
11505 
11506   unsigned NumElts = VT.getVectorNumElements();
11507 
11508   uint64_t Idx = (NumElts + Imm) % NumElts;
11509 
11510   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11511   SmallVector<int, 8> Mask;
11512   for (unsigned i = 0; i < NumElts; ++i)
11513     Mask.push_back(Idx + i);
11514   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11515 }
11516